package log
import (
"encoding"
"encoding/json"
"fmt"
"io"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/pkgerrors"
)
func init() {
zerolog.InterfaceMarshalFunc = func(i any) ([]byte, error) {
switch v := i.(type) {
case json.Marshaler:
return json.Marshal(i)
case encoding.TextMarshaler:
return json.Marshal(i)
case fmt.Stringer:
return json.Marshal(v.String())
default:
return json.Marshal(i)
}
}
}
// ModuleKey defines a module logging key.
const ModuleKey = "module"
// ContextKey is used to store the logger in the context.
var ContextKey contextKey
type contextKey struct{}
// Logger is the Cosmos SDK logger interface.
// It extends cosmossdk.io/core/log.Logger to return a child logger.
// Use cosmossdk.io/core/log.Logger instead in modules.
type Logger interface {
// Info takes a message and a set of key/value pairs and logs with level INFO.
// The key of the tuple must be a string.
Info(msg string, keyVals ...any)
// Warn takes a message and a set of key/value pairs and logs with level WARN.
// The key of the tuple must be a string.
Warn(msg string, keyVals ...any)
// Error takes a message and a set of key/value pairs and logs with level ERR.
// The key of the tuple must be a string.
Error(msg string, keyVals ...any)
// Debug takes a message and a set of key/value pairs and logs with level DEBUG.
// The key of the tuple must be a string.
Debug(msg string, keyVals ...any)
// With returns a new wrapped logger with additional context provided by a set.
With(keyVals ...any) Logger
// Impl returns the underlying logger implementation.
// It is used to access the full functionalities of the underlying logger.
// Advanced users can type cast the returned value to the actual logger.
Impl() any
}
// WithJSONMarshal configures zerolog global json encoding.
func WithJSONMarshal(marshaler func(v any) ([]byte, error)) {
zerolog.InterfaceMarshalFunc = func(i any) ([]byte, error) {
switch v := i.(type) {
case json.Marshaler:
return marshaler(i)
case encoding.TextMarshaler:
return marshaler(i)
case fmt.Stringer:
return marshaler(v.String())
default:
return marshaler(i)
}
}
}
type zeroLogWrapper struct {
*zerolog.Logger
}
// NewLogger returns a new logger that writes to the given destination.
//
// Typical usage from a main function is:
//
// logger := log.NewLogger(os.Stderr)
//
// Stderr is the typical destination for logs,
// so that any output from your application can still be piped to other processes.
// The returned value can be safely cast to cosmossdk.io/core/log.Logger.
func NewLogger(dst io.Writer, options ...Option) Logger {
logCfg := defaultConfig
for _, opt := range options {
opt(&logCfg)
}
output := dst
if !logCfg.OutputJSON {
output = zerolog.ConsoleWriter{
Out: dst,
NoColor: !logCfg.Color,
TimeFormat: logCfg.TimeFormat,
}
}
if logCfg.Filter != nil {
output = NewFilterWriter(output, logCfg.Filter)
}
logger := zerolog.New(output)
if logCfg.StackTrace {
zerolog.ErrorStackMarshaler = func(err error) interface{} {
return pkgerrors.MarshalStack(errors.WithStack(err))
}
logger = logger.With().Stack().Logger()
}
if logCfg.TimeFormat != "" {
logger = logger.With().Timestamp().Logger()
}
if logCfg.Level != zerolog.NoLevel {
logger = logger.Level(logCfg.Level)
}
logger = logger.Hook(logCfg.Hooks...)
return zeroLogWrapper{&logger}
}
// NewCustomLogger returns a new logger with the given zerolog logger.
func NewCustomLogger(logger zerolog.Logger) Logger {
return zeroLogWrapper{&logger}
}
// Info takes a message and a set of key/value pairs and logs with level INFO.
// The key of the tuple must be a string.
func (l zeroLogWrapper) Info(msg string, keyVals ...interface{}) {
l.Logger.Info().Fields(keyVals).Msg(msg)
}
// Warn takes a message and a set of key/value pairs and logs with level WARN.
// The key of the tuple must be a string.
func (l zeroLogWrapper) Warn(msg string, keyVals ...interface{}) {
l.Logger.Warn().Fields(keyVals).Msg(msg)
}
// Error takes a message and a set of key/value pairs and logs with level ERROR.
// The key of the tuple must be a string.
func (l zeroLogWrapper) Error(msg string, keyVals ...interface{}) {
l.Logger.Error().Fields(keyVals).Msg(msg)
}
// Debug takes a message and a set of key/value pairs and logs with level DEBUG.
// The key of the tuple must be a string.
func (l zeroLogWrapper) Debug(msg string, keyVals ...interface{}) {
l.Logger.Debug().Fields(keyVals).Msg(msg)
}
// With returns a new wrapped logger with additional context provided by a set.
func (l zeroLogWrapper) With(keyVals ...interface{}) Logger {
logger := l.Logger.With().Fields(keyVals).Logger()
return zeroLogWrapper{&logger}
}
// WithContext returns a new wrapped logger with additional context provided by a set.
func (l zeroLogWrapper) WithContext(keyVals ...interface{}) any {
logger := l.Logger.With().Fields(keyVals).Logger()
return zeroLogWrapper{&logger}
}
// Impl returns the underlying zerolog logger.
// It can be used to used zerolog structured API directly instead of the wrapper.
func (l zeroLogWrapper) Impl() interface{} {
return l.Logger
}
// NewNopLogger returns a new logger that does nothing.
func NewNopLogger() Logger {
// The custom nopLogger is about 3x faster than a zeroLogWrapper with zerolog.Nop().
return nopLogger{}
}
// nopLogger is a Logger that does nothing when called.
// See the "specialized nop logger" benchmark and compare with the "zerolog nop logger" benchmark.
// The custom implementation is about 3x faster.
type nopLogger struct{}
func (nopLogger) Info(string, ...any) {}
func (nopLogger) Warn(string, ...any) {}
func (nopLogger) Error(string, ...any) {}
func (nopLogger) Debug(string, ...any) {}
func (nopLogger) With(...any) Logger { return nopLogger{} }
func (nopLogger) WithContext(...any) any { return nopLogger{} }
func (nopLogger) Impl() any { return nopLogger{} }
package cache
import (
"fmt"
lru "github.com/hashicorp/golang-lru"
"cosmossdk.io/store/cachekv"
"cosmossdk.io/store/types"
)
var (
_ types.CommitKVStore = (*CommitKVStoreCache)(nil)
_ types.MultiStorePersistentCache = (*CommitKVStoreCacheManager)(nil)
// DefaultCommitKVStoreCacheSize defines the persistent ARC cache size for a
// CommitKVStoreCache.
DefaultCommitKVStoreCacheSize uint = 1000
)
type (
// CommitKVStoreCache implements an inter-block (persistent) cache that wraps a
// CommitKVStore. Reads first hit the internal ARC (Adaptive Replacement Cache).
// During a cache miss, the read is delegated to the underlying CommitKVStore
// and cached. Deletes and writes always happen to both the cache and the
// CommitKVStore in a write-through manner. Caching performed in the
// CommitKVStore and below is completely irrelevant to this layer.
CommitKVStoreCache struct {
types.CommitKVStore
cache *lru.ARCCache
}
// CommitKVStoreCacheManager maintains a mapping from a StoreKey to a
// CommitKVStoreCache. Each CommitKVStore, per StoreKey, is meant to be used
// in an inter-block (persistent) manner and typically provided by a
// CommitMultiStore.
CommitKVStoreCacheManager struct {
cacheSize uint
caches map[string]types.CommitKVStore
}
)
func NewCommitKVStoreCache(store types.CommitKVStore, size uint) *CommitKVStoreCache {
cache, err := lru.NewARC(int(size))
if err != nil {
panic(fmt.Errorf("failed to create KVStore cache: %s", err))
}
return &CommitKVStoreCache{
CommitKVStore: store,
cache: cache,
}
}
func NewCommitKVStoreCacheManager(size uint) *CommitKVStoreCacheManager {
return &CommitKVStoreCacheManager{
cacheSize: size,
caches: make(map[string]types.CommitKVStore),
}
}
// GetStoreCache returns a Cache from the CommitStoreCacheManager for a given
// StoreKey. If no Cache exists for the StoreKey, then one is created and set.
// The returned Cache is meant to be used in a persistent manner.
func (cmgr *CommitKVStoreCacheManager) GetStoreCache(key types.StoreKey, store types.CommitKVStore) types.CommitKVStore {
if cmgr.caches[key.Name()] == nil {
cmgr.caches[key.Name()] = NewCommitKVStoreCache(store, cmgr.cacheSize)
}
return cmgr.caches[key.Name()]
}
// Unwrap returns the underlying CommitKVStore for a given StoreKey.
func (cmgr *CommitKVStoreCacheManager) Unwrap(key types.StoreKey) types.CommitKVStore {
if ckv, ok := cmgr.caches[key.Name()]; ok {
return ckv.(*CommitKVStoreCache).CommitKVStore
}
return nil
}
// Reset resets in the internal caches.
func (cmgr *CommitKVStoreCacheManager) Reset() {
// Clear the map.
// Please note that we are purposefully using the map clearing idiom.
// See https://github.com/cosmos/cosmos-sdk/issues/6681.
for key := range cmgr.caches {
delete(cmgr.caches, key)
}
}
// CacheWrap implements the CacheWrapper interface
func (ckv *CommitKVStoreCache) CacheWrap() types.CacheWrap {
return cachekv.NewStore(ckv)
}
// Get retrieves a value by key. It will first look in the write-through cache.
// If the value doesn't exist in the write-through cache, the query is delegated
// to the underlying CommitKVStore.
func (ckv *CommitKVStoreCache) Get(key []byte) []byte {
types.AssertValidKey(key)
keyStr := string(key)
valueI, ok := ckv.cache.Get(keyStr)
if ok {
// cache hit
return valueI.([]byte)
}
// cache miss; write to cache
value := ckv.CommitKVStore.Get(key)
ckv.cache.Add(keyStr, value)
return value
}
// Set inserts a key/value pair into both the write-through cache and the
// underlying CommitKVStore.
func (ckv *CommitKVStoreCache) Set(key, value []byte) {
types.AssertValidKey(key)
types.AssertValidValue(value)
ckv.cache.Add(string(key), value)
ckv.CommitKVStore.Set(key, value)
}
// Delete removes a key/value pair from both the write-through cache and the
// underlying CommitKVStore.
func (ckv *CommitKVStoreCache) Delete(key []byte) {
ckv.cache.Remove(string(key))
ckv.CommitKVStore.Delete(key)
}
package iavl
import (
"errors"
"fmt"
"io"
cmtprotocrypto "github.com/cometbft/cometbft/proto/tendermint/crypto"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/iavl"
ics23 "github.com/cosmos/ics23/go"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
"cosmossdk.io/store/cachekv"
"cosmossdk.io/store/internal/kv"
"cosmossdk.io/store/metrics"
pruningtypes "cosmossdk.io/store/pruning/types"
"cosmossdk.io/store/tracekv"
"cosmossdk.io/store/types"
"cosmossdk.io/store/wrapper"
)
const (
DefaultIAVLCacheSize = 500000
)
var (
_ types.KVStore = (*Store)(nil)
_ types.CommitStore = (*Store)(nil)
_ types.CommitKVStore = (*Store)(nil)
_ types.Queryable = (*Store)(nil)
_ types.StoreWithInitialVersion = (*Store)(nil)
)
// Store Implements types.KVStore and CommitKVStore.
type Store struct {
tree Tree
logger log.Logger
metrics metrics.StoreMetrics
}
// LoadStore returns an IAVL Store as a CommitKVStore. Internally, it will load the
// store's version (id) from the provided DB. An error is returned if the version
// fails to load, or if called with a positive version on an empty tree.
func LoadStore(db dbm.DB, logger log.Logger, key types.StoreKey, id types.CommitID, cacheSize int, disableFastNode, commitSync bool, metrics metrics.StoreMetrics) (types.CommitKVStore, error) {
return LoadStoreWithInitialVersion(db, logger, key, id, 0, cacheSize, disableFastNode, commitSync, metrics)
}
// LoadStoreWithInitialVersion returns an IAVL Store as a CommitKVStore setting its initialVersion
// to the one given. Internally, it will load the store's version (id) from the
// provided DB. An error is returned if the version fails to load, or if called with a positive
// version on an empty tree.
func LoadStoreWithInitialVersion(db dbm.DB, logger log.Logger, key types.StoreKey, id types.CommitID, initialVersion uint64, cacheSize int, disableFastNode, commitSync bool, metrics metrics.StoreMetrics) (types.CommitKVStore, error) {
tree := iavl.NewMutableTree(wrapper.NewDBWrapper(db), cacheSize, disableFastNode, logger, iavl.InitialVersionOption(initialVersion), iavl.SyncOption(commitSync))
isUpgradeable, err := tree.IsUpgradeable()
if err != nil {
return nil, err
}
if isUpgradeable && logger != nil {
logger.Info(
"Upgrading IAVL storage for faster queries + execution on live state. This may take a while",
"store_key", key.String(),
"version", initialVersion,
"commit", fmt.Sprintf("%X", id),
)
}
_, err = tree.LoadVersion(id.Version)
if err != nil {
return nil, err
}
if logger != nil {
logger.Debug("Finished loading IAVL tree")
}
return &Store{
tree: tree,
logger: logger,
metrics: metrics,
}, nil
}
// UnsafeNewStore returns a reference to a new IAVL Store with a given mutable
// IAVL tree reference. It should only be used for testing purposes.
//
// CONTRACT: The IAVL tree should be fully loaded.
// CONTRACT: PruningOptions passed in as argument must be the same as pruning options
// passed into iavl.MutableTree
func UnsafeNewStore(tree *iavl.MutableTree) *Store {
return &Store{
tree: tree,
metrics: metrics.NewNoOpMetrics(),
}
}
// GetImmutable returns a reference to a new store backed by an immutable IAVL
// tree at a specific version (height) without any pruning options. This should
// be used for querying and iteration only. If the version does not exist or has
// been pruned, an empty immutable IAVL tree will be used.
// Any mutable operations executed will result in a panic.
func (st *Store) GetImmutable(version int64) (*Store, error) {
if !st.VersionExists(version) {
return nil, errors.New("version mismatch on immutable IAVL tree; version does not exist. Version has either been pruned, or is for a future block height")
}
iTree, err := st.tree.GetImmutable(version)
if err != nil {
return nil, err
}
return &Store{
tree: &immutableTree{iTree},
metrics: st.metrics,
}, nil
}
// Commit commits the current store state and returns a CommitID with the new
// version and hash.
func (st *Store) Commit() types.CommitID {
defer st.metrics.MeasureSince("store", "iavl", "commit")
hash, version, err := st.tree.SaveVersion()
if err != nil {
panic(err)
}
return types.CommitID{
Version: version,
Hash: hash,
}
}
// WorkingHash returns the hash of the current working tree.
func (st *Store) WorkingHash() []byte {
return st.tree.WorkingHash()
}
// LastCommitID implements Committer.
func (st *Store) LastCommitID() types.CommitID {
return types.CommitID{
Version: st.tree.Version(),
Hash: st.tree.Hash(),
}
}
// SetPruning panics as pruning options should be provided at initialization
// since IAVl accepts pruning options directly.
func (st *Store) SetPruning(_ pruningtypes.PruningOptions) {
panic("cannot set pruning options on an initialized IAVL store")
}
// SetPruning panics as pruning options should be provided at initialization
// since IAVl accepts pruning options directly.
func (st *Store) GetPruning() pruningtypes.PruningOptions {
panic("cannot get pruning options on an initialized IAVL store")
}
// VersionExists returns whether or not a given version is stored.
func (st *Store) VersionExists(version int64) bool {
return st.tree.VersionExists(version)
}
// GetAllVersions returns all versions in the iavl tree
func (st *Store) GetAllVersions() []int {
return st.tree.AvailableVersions()
}
// Implements Store.
func (st *Store) GetStoreType() types.StoreType {
return types.StoreTypeIAVL
}
// Implements Store.
func (st *Store) CacheWrap() types.CacheWrap {
return cachekv.NewStore(st)
}
// CacheWrapWithTrace implements the Store interface.
func (st *Store) CacheWrapWithTrace(w io.Writer, tc types.TraceContext) types.CacheWrap {
return cachekv.NewStore(tracekv.NewStore(st, w, tc))
}
// Implements types.KVStore.
func (st *Store) Set(key, value []byte) {
types.AssertValidKey(key)
types.AssertValidValue(value)
_, err := st.tree.Set(key, value)
if err != nil && st.logger != nil {
st.logger.Error("iavl set error", "error", err.Error())
}
}
// Implements types.KVStore.
func (st *Store) Get(key []byte) []byte {
defer st.metrics.MeasureSince("store", "iavl", "get")
value, err := st.tree.Get(key)
if err != nil {
panic(err)
}
return value
}
// Implements types.KVStore.
func (st *Store) Has(key []byte) (exists bool) {
defer st.metrics.MeasureSince("store", "iavl", "has")
has, err := st.tree.Has(key)
if err != nil {
panic(err)
}
return has
}
// Implements types.KVStore.
func (st *Store) Delete(key []byte) {
defer st.metrics.MeasureSince("store", "iavl", "delete")
_, _, err := st.tree.Remove(key)
if err != nil {
panic(err)
}
}
// DeleteVersionsTo deletes versions upto the given version from the MutableTree. An error
// is returned if any single version is invalid or the delete fails. All writes
// happen in a single batch with a single commit.
func (st *Store) DeleteVersionsTo(version int64) error {
return st.tree.DeleteVersionsTo(version)
}
// LoadVersionForOverwriting attempts to load a tree at a previously committed
// version. Any versions greater than targetVersion will be deleted.
func (st *Store) LoadVersionForOverwriting(targetVersion int64) error {
return st.tree.LoadVersionForOverwriting(targetVersion)
}
// Implements types.KVStore.
func (st *Store) Iterator(start, end []byte) types.Iterator {
iterator, err := st.tree.Iterator(start, end, true)
if err != nil {
panic(err)
}
return iterator
}
// Implements types.KVStore.
func (st *Store) ReverseIterator(start, end []byte) types.Iterator {
iterator, err := st.tree.Iterator(start, end, false)
if err != nil {
panic(err)
}
return iterator
}
// SetInitialVersion sets the initial version of the IAVL tree. It is used when
// starting a new chain at an arbitrary height.
func (st *Store) SetInitialVersion(version int64) {
st.tree.SetInitialVersion(uint64(version))
}
// Exports the IAVL store at the given version, returning an iavl.Exporter for the tree.
func (st *Store) Export(version int64) (*iavl.Exporter, error) {
istore, err := st.GetImmutable(version)
if err != nil {
return nil, errorsmod.Wrapf(err, "iavl export failed for version %v", version)
}
tree, ok := istore.tree.(*immutableTree)
if !ok || tree == nil {
return nil, fmt.Errorf("iavl export failed: unable to fetch tree for version %v", version)
}
return tree.Export()
}
// Import imports an IAVL tree at the given version, returning an iavl.Importer for importing.
func (st *Store) Import(version int64) (*iavl.Importer, error) {
tree, ok := st.tree.(*iavl.MutableTree)
if !ok {
return nil, errors.New("iavl import failed: unable to find mutable tree")
}
return tree.Import(version)
}
// Handle gatest the latest height, if height is 0
func getHeight(tree Tree, req *types.RequestQuery) int64 {
height := req.Height
if height == 0 {
latest := tree.Version()
if tree.VersionExists(latest - 1) {
height = latest - 1
} else {
height = latest
}
}
return height
}
// Query implements ABCI interface, allows queries
//
// by default we will return from (latest height -1),
// as we will have merkle proofs immediately (header height = data height + 1)
// If latest-1 is not present, use latest (which must be present)
// if you care to have the latest data to see a tx results, you must
// explicitly set the height you want to see
func (st *Store) Query(req *types.RequestQuery) (res *types.ResponseQuery, err error) {
defer st.metrics.MeasureSince("store", "iavl", "query")
if len(req.Data) == 0 {
return &types.ResponseQuery{}, errorsmod.Wrap(types.ErrTxDecode, "query cannot be zero length")
}
tree := st.tree
// store the height we chose in the response, with 0 being changed to the
// latest height
res = &types.ResponseQuery{
Height: getHeight(tree, req),
}
switch req.Path {
case "/key": // get by key
key := req.Data // data holds the key bytes
res.Key = key
if !st.VersionExists(res.Height) {
res.Log = iavl.ErrVersionDoesNotExist.Error()
break
}
value, err := tree.GetVersioned(key, res.Height)
if err != nil {
panic(err)
}
res.Value = value
if !req.Prove {
break
}
// Continue to prove existence/absence of value
// Must convert store.Tree to iavl.MutableTree with given version to use in CreateProof
iTree, err := tree.GetImmutable(res.Height)
if err != nil {
// sanity check: If value for given version was retrieved, immutable tree must also be retrievable
panic(fmt.Sprintf("version exists in store but could not retrieve corresponding versioned tree in store, %s", err.Error()))
}
mtree := &iavl.MutableTree{
ImmutableTree: iTree,
}
// get proof from tree and convert to merkle.Proof before adding to result
res.ProofOps = getProofFromTree(mtree, req.Data, res.Value != nil)
case "/subspace":
pairs := kv.Pairs{
Pairs: make([]kv.Pair, 0),
}
subspace := req.Data
res.Key = subspace
iterator := types.KVStorePrefixIterator(st, subspace)
for ; iterator.Valid(); iterator.Next() {
pairs.Pairs = append(pairs.Pairs, kv.Pair{Key: iterator.Key(), Value: iterator.Value()})
}
if err := iterator.Close(); err != nil {
panic(fmt.Errorf("failed to close iterator: %w", err))
}
bz, err := pairs.Marshal()
if err != nil {
panic(fmt.Errorf("failed to marshal KV pairs: %w", err))
}
res.Value = bz
default:
return &types.ResponseQuery{}, errorsmod.Wrapf(types.ErrUnknownRequest, "unexpected query path: %v", req.Path)
}
return res, err
}
// TraverseStateChanges traverses the state changes between two versions and calls the given function.
func (st *Store) TraverseStateChanges(startVersion, endVersion int64, fn func(version int64, changeSet *iavl.ChangeSet) error) error {
return st.tree.TraverseStateChanges(startVersion, endVersion, fn)
}
// Takes a MutableTree, a key, and a flag for creating existence or absence proof and returns the
// appropriate merkle.Proof. Since this must be called after querying for the value, this function should never error
// Thus, it will panic on error rather than returning it
func getProofFromTree(tree *iavl.MutableTree, key []byte, exists bool) *cmtprotocrypto.ProofOps {
var (
commitmentProof *ics23.CommitmentProof
err error
)
if exists {
// value was found
commitmentProof, err = tree.GetMembershipProof(key)
if err != nil {
// sanity check: If value was found, membership proof must be creatable
panic(fmt.Sprintf("unexpected value for empty proof: %s", err.Error()))
}
} else {
// value wasn't found
commitmentProof, err = tree.GetNonMembershipProof(key)
if err != nil {
// sanity check: If value wasn't found, nonmembership proof must be creatable
panic(fmt.Sprintf("unexpected error for nonexistence proof: %s", err.Error()))
}
}
op := types.NewIavlCommitmentOp(key, commitmentProof)
return &cmtprotocrypto.ProofOps{Ops: []cmtprotocrypto.ProofOp{op.ProofOp()}}
}
package prefix
import (
"bytes"
"errors"
"io"
"cosmossdk.io/store/cachekv"
"cosmossdk.io/store/tracekv"
"cosmossdk.io/store/types"
)
var _ types.KVStore = Store{}
// Store is similar with cometbft/cometbft/libs/db/prefix_db
// both gives access only to the limited subset of the store
// for convinience or safety
type Store struct {
parent types.KVStore
prefix []byte
}
func NewStore(parent types.KVStore, prefix []byte) Store {
return Store{
parent: parent,
prefix: prefix,
}
}
func cloneAppend(bz, tail []byte) (res []byte) {
res = make([]byte, len(bz)+len(tail))
copy(res, bz)
copy(res[len(bz):], tail)
return
}
func (s Store) key(key []byte) (res []byte) {
if key == nil {
panic("nil key on Store")
}
res = cloneAppend(s.prefix, key)
return
}
// Implements Store
func (s Store) GetStoreType() types.StoreType {
return s.parent.GetStoreType()
}
// Implements CacheWrap
func (s Store) CacheWrap() types.CacheWrap {
return cachekv.NewStore(s)
}
// CacheWrapWithTrace implements the KVStore interface.
func (s Store) CacheWrapWithTrace(w io.Writer, tc types.TraceContext) types.CacheWrap {
return cachekv.NewStore(tracekv.NewStore(s, w, tc))
}
// Implements KVStore
func (s Store) Get(key []byte) []byte {
res := s.parent.Get(s.key(key))
return res
}
// Implements KVStore
func (s Store) Has(key []byte) bool {
return s.parent.Has(s.key(key))
}
// Implements KVStore
func (s Store) Set(key, value []byte) {
types.AssertValidKey(key)
types.AssertValidValue(value)
s.parent.Set(s.key(key), value)
}
// Implements KVStore
func (s Store) Delete(key []byte) {
s.parent.Delete(s.key(key))
}
// Implements KVStore
// Check https://github.com/cometbft/cometbft/blob/master/libs/db/prefix_db.go#L106
func (s Store) Iterator(start, end []byte) types.Iterator {
newstart := cloneAppend(s.prefix, start)
var newend []byte
if end == nil {
newend = cpIncr(s.prefix)
} else {
newend = cloneAppend(s.prefix, end)
}
iter := s.parent.Iterator(newstart, newend)
return newPrefixIterator(s.prefix, start, end, iter)
}
// ReverseIterator implements KVStore
// Check https://github.com/cometbft/cometbft/blob/master/libs/db/prefix_db.go#L129
func (s Store) ReverseIterator(start, end []byte) types.Iterator {
newstart := cloneAppend(s.prefix, start)
var newend []byte
if end == nil {
newend = cpIncr(s.prefix)
} else {
newend = cloneAppend(s.prefix, end)
}
iter := s.parent.ReverseIterator(newstart, newend)
return newPrefixIterator(s.prefix, start, end, iter)
}
var _ types.Iterator = (*prefixIterator)(nil)
type prefixIterator struct {
prefix []byte
start []byte
end []byte
iter types.Iterator
valid bool
}
func newPrefixIterator(prefix, start, end []byte, parent types.Iterator) *prefixIterator {
return &prefixIterator{
prefix: prefix,
start: start,
end: end,
iter: parent,
valid: parent.Valid() && bytes.HasPrefix(parent.Key(), prefix),
}
}
// Implements Iterator
func (pi *prefixIterator) Domain() ([]byte, []byte) {
return pi.start, pi.end
}
// Implements Iterator
func (pi *prefixIterator) Valid() bool {
return pi.valid && pi.iter.Valid()
}
// Implements Iterator
func (pi *prefixIterator) Next() {
if !pi.valid {
panic("prefixIterator invalid, cannot call Next()")
}
if pi.iter.Next(); !pi.iter.Valid() || !bytes.HasPrefix(pi.iter.Key(), pi.prefix) {
// TODO: shouldn't pi be set to nil instead?
pi.valid = false
}
}
// Implements Iterator
func (pi *prefixIterator) Key() (key []byte) {
if !pi.valid {
panic("prefixIterator invalid, cannot call Key()")
}
key = pi.iter.Key()
key = stripPrefix(key, pi.prefix)
return
}
// Implements Iterator
func (pi *prefixIterator) Value() []byte {
if !pi.valid {
panic("prefixIterator invalid, cannot call Value()")
}
return pi.iter.Value()
}
// Implements Iterator
func (pi *prefixIterator) Close() error {
return pi.iter.Close()
}
// Error returns an error if the prefixIterator is invalid defined by the Valid
// method.
func (pi *prefixIterator) Error() error {
if !pi.Valid() {
return errors.New("invalid prefixIterator")
}
return nil
}
// copied from github.com/cometbft/cometbft/libs/db/prefix_db.go
func stripPrefix(key, prefix []byte) []byte {
if len(key) < len(prefix) || !bytes.Equal(key[:len(prefix)], prefix) {
panic("should not happen")
}
return key[len(prefix):]
}
// wrapping types.PrefixEndBytes
func cpIncr(bz []byte) []byte {
return types.PrefixEndBytes(bz)
}
package rootmulti
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"math"
"sort"
"strings"
"sync"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
dbm "github.com/cosmos/cosmos-db"
protoio "github.com/cosmos/gogoproto/io"
gogotypes "github.com/cosmos/gogoproto/types"
iavltree "github.com/cosmos/iavl"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
"cosmossdk.io/store/cachemulti"
"cosmossdk.io/store/dbadapter"
"cosmossdk.io/store/iavl"
"cosmossdk.io/store/listenkv"
"cosmossdk.io/store/mem"
"cosmossdk.io/store/metrics"
"cosmossdk.io/store/pruning"
pruningtypes "cosmossdk.io/store/pruning/types"
snapshottypes "cosmossdk.io/store/snapshots/types"
"cosmossdk.io/store/tracekv"
"cosmossdk.io/store/transient"
"cosmossdk.io/store/types"
)
const (
latestVersionKey = "s/latest"
commitInfoKeyFmt = "s/%d" // s/<version>
)
const iavlDisablefastNodeDefault = false
// keysFromStoreKeyMap returns a slice of keys for the provided map lexically sorted by StoreKey.Name()
func keysFromStoreKeyMap[V any](m map[types.StoreKey]V) []types.StoreKey {
keys := make([]types.StoreKey, 0, len(m))
for key := range m {
keys = append(keys, key)
}
sort.Slice(keys, func(i, j int) bool {
ki, kj := keys[i], keys[j]
return ki.Name() < kj.Name()
})
return keys
}
// Store is composed of many CommitStores. Name contrasts with
// cacheMultiStore which is used for branching other MultiStores. It implements
// the CommitMultiStore interface.
type Store struct {
db dbm.DB
logger log.Logger
lastCommitInfo *types.CommitInfo
pruningManager *pruning.Manager
iavlCacheSize int
iavlDisableFastNode bool
storesParams map[types.StoreKey]storeParams
stores map[types.StoreKey]types.CommitKVStore
keysByName map[string]types.StoreKey
initialVersion int64
removalMap map[types.StoreKey]bool
traceWriter io.Writer
traceContext types.TraceContext
traceContextMutex sync.Mutex
interBlockCache types.MultiStorePersistentCache
listeners map[types.StoreKey]*types.MemoryListener
metrics metrics.StoreMetrics
commitHeader cmtproto.Header
commitSync bool
}
var (
_ types.CommitMultiStore = (*Store)(nil)
_ types.Queryable = (*Store)(nil)
)
// NewStore returns a reference to a new Store object with the provided DB. The
// store will be created with a PruneNothing pruning strategy by default. After
// a store is created, KVStores must be mounted and finally LoadLatestVersion or
// LoadVersion must be called.
func NewStore(db dbm.DB, logger log.Logger, metricGatherer metrics.StoreMetrics) *Store {
return &Store{
db: db,
logger: logger,
iavlCacheSize: iavl.DefaultIAVLCacheSize,
iavlDisableFastNode: iavlDisablefastNodeDefault,
storesParams: make(map[types.StoreKey]storeParams),
stores: make(map[types.StoreKey]types.CommitKVStore),
keysByName: make(map[string]types.StoreKey),
listeners: make(map[types.StoreKey]*types.MemoryListener),
removalMap: make(map[types.StoreKey]bool),
pruningManager: pruning.NewManager(db, logger),
metrics: metricGatherer,
}
}
func (rs *Store) GetCommitSync() bool {
return rs.commitSync
}
func (rs *Store) SetCommitSync(sync bool) {
rs.commitSync = sync
}
// GetPruning fetches the pruning strategy from the root store.
func (rs *Store) GetPruning() pruningtypes.PruningOptions {
return rs.pruningManager.GetOptions()
}
// SetPruning sets the pruning strategy on the root store and all the sub-stores.
// Note, calling SetPruning on the root store prior to LoadVersion or
// LoadLatestVersion performs a no-op as the stores aren't mounted yet.
func (rs *Store) SetPruning(pruningOpts pruningtypes.PruningOptions) {
rs.pruningManager.SetOptions(pruningOpts)
}
// SetMetrics sets the metrics gatherer for the store package
func (rs *Store) SetMetrics(metrics metrics.StoreMetrics) {
rs.metrics = metrics
}
// SetSnapshotInterval sets the interval at which the snapshots are taken.
// It is used by the store to determine which heights to retain until after the snapshot is complete.
func (rs *Store) SetSnapshotInterval(snapshotInterval uint64) {
rs.pruningManager.SetSnapshotInterval(snapshotInterval)
}
func (rs *Store) SetIAVLCacheSize(cacheSize int) {
rs.iavlCacheSize = cacheSize
}
func (rs *Store) SetIAVLDisableFastNode(disableFastNode bool) {
rs.iavlDisableFastNode = disableFastNode
}
// GetStoreType implements Store.
func (rs *Store) GetStoreType() types.StoreType {
return types.StoreTypeMulti
}
// MountStoreWithDB implements CommitMultiStore.
func (rs *Store) MountStoreWithDB(key types.StoreKey, typ types.StoreType, db dbm.DB) {
if key == nil {
panic("MountIAVLStore() key cannot be nil")
}
if _, ok := rs.storesParams[key]; ok {
panic(fmt.Sprintf("store duplicate store key %v", key))
}
if _, ok := rs.keysByName[key.Name()]; ok {
panic(fmt.Sprintf("store duplicate store key name %v", key))
}
rs.storesParams[key] = newStoreParams(key, db, typ, 0)
rs.keysByName[key.Name()] = key
}
// GetCommitStore returns a mounted CommitStore for a given StoreKey. If the
// store is wrapped in an inter-block cache, it will be unwrapped before returning.
func (rs *Store) GetCommitStore(key types.StoreKey) types.CommitStore {
return rs.GetCommitKVStore(key)
}
// GetCommitKVStore returns a mounted CommitKVStore for a given StoreKey. If the
// store is wrapped in an inter-block cache, it will be unwrapped before returning.
func (rs *Store) GetCommitKVStore(key types.StoreKey) types.CommitKVStore {
// If the Store has an inter-block cache, first attempt to lookup and unwrap
// the underlying CommitKVStore by StoreKey. If it does not exist, fallback to
// the main mapping of CommitKVStores.
if rs.interBlockCache != nil {
if store := rs.interBlockCache.Unwrap(key); store != nil {
return store
}
}
return rs.stores[key]
}
// StoreKeysByName returns mapping storeNames -> StoreKeys
func (rs *Store) StoreKeysByName() map[string]types.StoreKey {
return rs.keysByName
}
// LoadLatestVersionAndUpgrade implements CommitMultiStore
func (rs *Store) LoadLatestVersionAndUpgrade(upgrades *types.StoreUpgrades) error {
ver := GetLatestVersion(rs.db)
return rs.loadVersion(ver, upgrades)
}
// LoadVersionAndUpgrade allows us to rename substores while loading an older version
func (rs *Store) LoadVersionAndUpgrade(ver int64, upgrades *types.StoreUpgrades) error {
return rs.loadVersion(ver, upgrades)
}
// LoadLatestVersion implements CommitMultiStore.
func (rs *Store) LoadLatestVersion() error {
ver := GetLatestVersion(rs.db)
return rs.loadVersion(ver, nil)
}
// LoadVersion implements CommitMultiStore.
func (rs *Store) LoadVersion(ver int64) error {
return rs.loadVersion(ver, nil)
}
func (rs *Store) loadVersion(ver int64, upgrades *types.StoreUpgrades) error {
infos := make(map[string]types.StoreInfo)
rs.logger.Debug("loadVersion", "ver", ver)
cInfo := &types.CommitInfo{}
// load old data if we are not version 0
if ver != 0 {
var err error
cInfo, err = rs.GetCommitInfo(ver)
if err != nil {
return err
}
// convert StoreInfos slice to map
for _, storeInfo := range cInfo.StoreInfos {
infos[storeInfo.Name] = storeInfo
}
}
// load each Store (note this doesn't panic on unmounted keys now)
newStores := make(map[types.StoreKey]types.CommitKVStore)
storesKeys := make([]types.StoreKey, 0, len(rs.storesParams))
for key := range rs.storesParams {
storesKeys = append(storesKeys, key)
}
if upgrades != nil {
// deterministic iteration order for upgrades
// (as the underlying store may change and
// upgrades make store changes where the execution order may matter)
sort.Slice(storesKeys, func(i, j int) bool {
return storesKeys[i].Name() < storesKeys[j].Name()
})
}
for _, key := range storesKeys {
storeParams := rs.storesParams[key]
commitID := rs.getCommitID(infos, key.Name())
rs.logger.Debug("loadVersion commitID", "key", key, "ver", ver, "hash", fmt.Sprintf("%x", commitID.Hash))
// If it has been added, set the initial version
if upgrades.IsAdded(key.Name()) || upgrades.RenamedFrom(key.Name()) != "" {
storeParams.initialVersion = uint64(ver) + 1
} else if commitID.Version != ver && storeParams.typ == types.StoreTypeIAVL {
return fmt.Errorf("version of store %s mismatch root store's version; expected %d got %d; new stores should be added using StoreUpgrades", key.Name(), ver, commitID.Version)
}
store, err := rs.loadCommitStoreFromParams(key, commitID, storeParams)
if err != nil {
return errorsmod.Wrap(err, "failed to load store")
}
newStores[key] = store
// If it was deleted, remove all data
if upgrades.IsDeleted(key.Name()) {
if err := deleteKVStore(store.(types.KVStore)); err != nil {
return errorsmod.Wrapf(err, "failed to delete store %s", key.Name())
}
rs.removalMap[key] = true
} else if oldName := upgrades.RenamedFrom(key.Name()); oldName != "" {
// handle renames specially
// make an unregistered key to satisfy loadCommitStore params
oldKey := types.NewKVStoreKey(oldName)
oldParams := newStoreParams(oldKey, storeParams.db, storeParams.typ, 0)
// load from the old name
oldStore, err := rs.loadCommitStoreFromParams(oldKey, rs.getCommitID(infos, oldName), oldParams)
if err != nil {
return errorsmod.Wrapf(err, "failed to load old store %s", oldName)
}
// move all data
if err := moveKVStoreData(oldStore.(types.KVStore), store.(types.KVStore)); err != nil {
return errorsmod.Wrapf(err, "failed to move store %s -> %s", oldName, key.Name())
}
// add the old key so its deletion is committed
newStores[oldKey] = oldStore
// this will ensure it's not perpetually stored in commitInfo
rs.removalMap[oldKey] = true
}
}
rs.lastCommitInfo = cInfo
rs.stores = newStores
// load any snapshot heights we missed from disk to be pruned on the next run
if err := rs.pruningManager.LoadSnapshotHeights(rs.db); err != nil {
return err
}
return nil
}
func (rs *Store) getCommitID(infos map[string]types.StoreInfo, name string) types.CommitID {
info, ok := infos[name]
if !ok {
return types.CommitID{}
}
return info.CommitId
}
func deleteKVStore(kv types.KVStore) error {
// Note that we cannot write while iterating, so load all keys here, delete below
var keys [][]byte
itr := kv.Iterator(nil, nil)
for itr.Valid() {
keys = append(keys, itr.Key())
itr.Next()
}
if err := itr.Close(); err != nil {
return err
}
for _, k := range keys {
kv.Delete(k)
}
return nil
}
// we simulate move by a copy and delete
func moveKVStoreData(oldDB, newDB types.KVStore) error {
// we read from one and write to another
itr := oldDB.Iterator(nil, nil)
for itr.Valid() {
newDB.Set(itr.Key(), itr.Value())
itr.Next()
}
if err := itr.Close(); err != nil {
return err
}
// then delete the old store
return deleteKVStore(oldDB)
}
// PruneSnapshotHeight prunes the given height according to the prune strategy.
// If the strategy is PruneNothing, this is a no-op.
// For other strategies, this height is persisted until the snapshot is operated.
func (rs *Store) PruneSnapshotHeight(height int64) {
rs.pruningManager.HandleSnapshotHeight(height)
}
// SetInterBlockCache sets the Store's internal inter-block (persistent) cache.
// When this is defined, all CommitKVStores will be wrapped with their respective
// inter-block cache.
func (rs *Store) SetInterBlockCache(c types.MultiStorePersistentCache) {
rs.interBlockCache = c
}
// SetTracer sets the tracer for the MultiStore that the underlying
// stores will utilize to trace operations. A MultiStore is returned.
func (rs *Store) SetTracer(w io.Writer) types.MultiStore {
rs.traceWriter = w
return rs
}
// SetTracingContext updates the tracing context for the MultiStore by merging
// the given context with the existing context by key. Any existing keys will
// be overwritten. It is implied that the caller should update the context when
// necessary between tracing operations. It returns a modified MultiStore.
func (rs *Store) SetTracingContext(tc types.TraceContext) types.MultiStore {
rs.traceContextMutex.Lock()
defer rs.traceContextMutex.Unlock()
rs.traceContext = rs.traceContext.Merge(tc)
return rs
}
func (rs *Store) getTracingContext() types.TraceContext {
rs.traceContextMutex.Lock()
defer rs.traceContextMutex.Unlock()
if rs.traceContext == nil {
return nil
}
ctx := types.TraceContext{}
for k, v := range rs.traceContext {
ctx[k] = v
}
return ctx
}
// TracingEnabled returns if tracing is enabled for the MultiStore.
func (rs *Store) TracingEnabled() bool {
return rs.traceWriter != nil
}
// AddListeners adds a listener for the KVStore belonging to the provided StoreKey
func (rs *Store) AddListeners(keys []types.StoreKey) {
for i := range keys {
listener := rs.listeners[keys[i]]
if listener == nil {
rs.listeners[keys[i]] = types.NewMemoryListener()
}
}
}
// ListeningEnabled returns if listening is enabled for a specific KVStore
func (rs *Store) ListeningEnabled(key types.StoreKey) bool {
if ls, ok := rs.listeners[key]; ok {
return ls != nil
}
return false
}
// PopStateCache returns the accumulated state change messages from the CommitMultiStore
// Calling PopStateCache destroys only the currently accumulated state in each listener
// not the state in the store itself. This is a mutating and destructive operation.
// This method has been synchronized.
func (rs *Store) PopStateCache() []*types.StoreKVPair {
var cache []*types.StoreKVPair
for key := range rs.listeners {
ls := rs.listeners[key]
if ls != nil {
cache = append(cache, ls.PopStateCache()...)
}
}
sort.SliceStable(cache, func(i, j int) bool {
return cache[i].StoreKey < cache[j].StoreKey
})
return cache
}
// LatestVersion returns the latest version in the store
func (rs *Store) LatestVersion() int64 {
return rs.LastCommitID().Version
}
// LastCommitID implements Committer/CommitStore.
func (rs *Store) LastCommitID() types.CommitID {
if rs.lastCommitInfo == nil {
emptyHash := sha256.Sum256([]byte{})
appHash := emptyHash[:]
return types.CommitID{
Version: GetLatestVersion(rs.db),
Hash: appHash, // set empty apphash to sha256([]byte{}) if info is nil
}
}
if len(rs.lastCommitInfo.CommitID().Hash) == 0 {
emptyHash := sha256.Sum256([]byte{})
appHash := emptyHash[:]
return types.CommitID{
Version: rs.lastCommitInfo.Version,
Hash: appHash, // set empty apphash to sha256([]byte{}) if hash is nil
}
}
return rs.lastCommitInfo.CommitID()
}
// Commit implements Committer/CommitStore.
func (rs *Store) Commit() types.CommitID {
var previousHeight, version int64
if rs.lastCommitInfo.GetVersion() == 0 && rs.initialVersion > 1 {
// This case means that no commit has been made in the store, we
// start from initialVersion.
version = rs.initialVersion
} else {
// This case can means two things:
// - either there was already a previous commit in the store, in which
// case we increment the version from there,
// - or there was no previous commit, and initial version was not set,
// in which case we start at version 1.
previousHeight = rs.lastCommitInfo.GetVersion()
version = previousHeight + 1
}
if rs.commitHeader.Height != version {
rs.logger.Debug("commit header and version mismatch", "header_height", rs.commitHeader.Height, "version", version)
}
rs.lastCommitInfo = commitStores(version, rs.stores, rs.removalMap)
rs.lastCommitInfo.Timestamp = rs.commitHeader.Time
defer rs.flushMetadata(rs.db, version, rs.lastCommitInfo)
// remove remnants of removed stores
for sk := range rs.removalMap {
if _, ok := rs.stores[sk]; ok {
delete(rs.stores, sk)
delete(rs.storesParams, sk)
delete(rs.keysByName, sk.Name())
}
}
// reset the removalMap
rs.removalMap = make(map[types.StoreKey]bool)
if err := rs.handlePruning(version); err != nil {
rs.logger.Error(
"failed to prune store, please check your pruning configuration",
"err", err,
)
}
return types.CommitID{
Version: version,
Hash: rs.lastCommitInfo.Hash(),
}
}
// WorkingHash returns the current hash of the store.
// it will be used to get the current app hash before commit.
func (rs *Store) WorkingHash() []byte {
storeInfos := make([]types.StoreInfo, 0, len(rs.stores))
storeKeys := keysFromStoreKeyMap(rs.stores)
for _, key := range storeKeys {
store := rs.stores[key]
if store.GetStoreType() != types.StoreTypeIAVL {
continue
}
if !rs.removalMap[key] {
si := types.StoreInfo{
Name: key.Name(),
CommitId: types.CommitID{
Hash: store.WorkingHash(),
},
}
storeInfos = append(storeInfos, si)
}
}
sort.SliceStable(storeInfos, func(i, j int) bool {
return storeInfos[i].Name < storeInfos[j].Name
})
return types.CommitInfo{StoreInfos: storeInfos}.Hash()
}
// CacheWrap implements CacheWrapper/Store/CommitStore.
func (rs *Store) CacheWrap() types.CacheWrap {
return rs.CacheMultiStore().(types.CacheWrap)
}
// CacheWrapWithTrace implements the CacheWrapper interface.
func (rs *Store) CacheWrapWithTrace(_ io.Writer, _ types.TraceContext) types.CacheWrap {
return rs.CacheWrap()
}
// CacheMultiStore creates ephemeral branch of the multi-store and returns a CacheMultiStore.
// It implements the MultiStore interface.
func (rs *Store) CacheMultiStore() types.CacheMultiStore {
stores := make(map[types.StoreKey]types.CacheWrapper)
for k, v := range rs.stores {
store := types.KVStore(v)
// Wire the listenkv.Store to allow listeners to observe the writes from the cache store,
// set same listeners on cache store will observe duplicated writes.
if rs.ListeningEnabled(k) {
store = listenkv.NewStore(store, k, rs.listeners[k])
}
stores[k] = store
}
return cachemulti.NewStore(rs.db, stores, rs.keysByName, rs.traceWriter, rs.getTracingContext())
}
// CacheMultiStoreWithVersion is analogous to CacheMultiStore except that it
// attempts to load stores at a given version (height). An error is returned if
// any store cannot be loaded. This should only be used for querying and
// iterating at past heights.
func (rs *Store) CacheMultiStoreWithVersion(version int64) (types.CacheMultiStore, error) {
cachedStores := make(map[types.StoreKey]types.CacheWrapper)
var commitInfo *types.CommitInfo
storeInfos := map[string]bool{}
for key, store := range rs.stores {
var cacheStore types.KVStore
switch store.GetStoreType() {
case types.StoreTypeIAVL:
// If the store is wrapped with an inter-block cache, we must first unwrap
// it to get the underlying IAVL store.
store = rs.GetCommitKVStore(key)
// Attempt to lazy-load an already saved IAVL store version. If the
// version does not exist or is pruned, an error should be returned.
var err error
cacheStore, err = store.(*iavl.Store).GetImmutable(version)
// if we got error from loading a module store
// we fetch commit info of this version
// we use commit info to check if the store existed at this version or not
if err != nil {
if commitInfo == nil {
var errCommitInfo error
commitInfo, errCommitInfo = rs.GetCommitInfo(version)
if errCommitInfo != nil {
return nil, errCommitInfo
}
for _, storeInfo := range commitInfo.StoreInfos {
storeInfos[storeInfo.Name] = true
}
}
// If the store existed at this version, it means there's actually an error
// getting the root store at this version.
if storeInfos[key.Name()] {
return nil, err
}
}
default:
cacheStore = store
}
// Wire the listenkv.Store to allow listeners to observe the writes from the cache store,
// set same listeners on cache store will observe duplicated writes.
if rs.ListeningEnabled(key) {
cacheStore = listenkv.NewStore(cacheStore, key, rs.listeners[key])
}
cachedStores[key] = cacheStore
}
return cachemulti.NewStore(rs.db, cachedStores, rs.keysByName, rs.traceWriter, rs.getTracingContext()), nil
}
// GetStore returns a mounted Store for a given StoreKey. If the StoreKey does
// not exist, it will panic. If the Store is wrapped in an inter-block cache, it
// will be unwrapped prior to being returned.
//
// TODO: This isn't used directly upstream. Consider returning the Store as-is
// instead of unwrapping.
func (rs *Store) GetStore(key types.StoreKey) types.Store {
store := rs.GetCommitKVStore(key)
if store == nil {
panic(fmt.Sprintf("store does not exist for key: %s", key.Name()))
}
return store
}
// GetKVStore returns a mounted KVStore for a given StoreKey. If tracing is
// enabled on the KVStore, a wrapped TraceKVStore will be returned with the root
// store's tracer, otherwise, the original KVStore will be returned.
//
// NOTE: The returned KVStore may be wrapped in an inter-block cache if it is
// set on the root store.
func (rs *Store) GetKVStore(key types.StoreKey) types.KVStore {
s := rs.stores[key]
if s == nil {
panic(fmt.Sprintf("store does not exist for key: %s", key.Name()))
}
store := types.KVStore(s)
if rs.TracingEnabled() {
store = tracekv.NewStore(store, rs.traceWriter, rs.getTracingContext())
}
if rs.ListeningEnabled(key) {
store = listenkv.NewStore(store, key, rs.listeners[key])
}
return store
}
func (rs *Store) handlePruning(version int64) error {
pruneHeight := rs.pruningManager.GetPruningHeight(version)
rs.logger.Debug("prune start", "height", version)
defer rs.logger.Debug("prune end", "height", version)
return rs.PruneStores(pruneHeight)
}
// PruneStores prunes all history upto the specific height of the multi store.
func (rs *Store) PruneStores(pruningHeight int64) (err error) {
if pruningHeight <= 0 {
rs.logger.Debug("pruning skipped, height is less than or equal to 0")
return nil
}
rs.logger.Debug("pruning store", "heights", pruningHeight)
for key, store := range rs.stores {
rs.logger.Debug("pruning store", "key", key) // Also log store.name (a private variable)?
// If the store is wrapped with an inter-block cache, we must first unwrap
// it to get the underlying IAVL store.
if store.GetStoreType() != types.StoreTypeIAVL {
continue
}
store = rs.GetCommitKVStore(key)
err := store.(*iavl.Store).DeleteVersionsTo(pruningHeight)
if err == nil {
continue
}
if errors.Is(err, iavltree.ErrVersionDoesNotExist) {
return err
}
rs.logger.Error("failed to prune store", "key", key, "err", err)
}
return nil
}
// getStoreByName performs a lookup of a StoreKey given a store name typically
// provided in a path. The StoreKey is then used to perform a lookup and return
// a Store. If the Store is wrapped in an inter-block cache, it will be unwrapped
// prior to being returned. If the StoreKey does not exist, nil is returned.
func (rs *Store) GetStoreByName(name string) types.Store {
key := rs.keysByName[name]
if key == nil {
return nil
}
return rs.GetCommitKVStore(key)
}
// Query calls substore.Query with the same `req` where `req.Path` is
// modified to remove the substore prefix.
// Ie. `req.Path` here is `/<substore>/<path>`, and trimmed to `/<path>` for the substore.
// TODO: add proof for `multistore -> substore`.
func (rs *Store) Query(req *types.RequestQuery) (*types.ResponseQuery, error) {
path := req.Path
storeName, subpath, err := parsePath(path)
if err != nil {
return &types.ResponseQuery{}, err
}
store := rs.GetStoreByName(storeName)
if store == nil {
return &types.ResponseQuery{}, errorsmod.Wrapf(types.ErrUnknownRequest, "no such store: %s", storeName)
}
queryable, ok := store.(types.Queryable)
if !ok {
return &types.ResponseQuery{}, errorsmod.Wrapf(types.ErrUnknownRequest, "store %s (type %T) doesn't support queries", storeName, store)
}
// trim the path and make the query
req.Path = subpath
res, err := queryable.Query(req)
if !req.Prove || !RequireProof(subpath) {
return res, err
}
if res.ProofOps == nil || len(res.ProofOps.Ops) == 0 {
return &types.ResponseQuery{}, errorsmod.Wrap(types.ErrInvalidRequest, "proof is unexpectedly empty; ensure height has not been pruned")
}
// If the request's height is the latest height we've committed, then utilize
// the store's lastCommitInfo as this commit info may not be flushed to disk.
// Otherwise, we query for the commit info from disk.
var commitInfo *types.CommitInfo
if res.Height == rs.lastCommitInfo.Version {
commitInfo = rs.lastCommitInfo
} else {
commitInfo, err = rs.GetCommitInfo(res.Height)
if err != nil {
return &types.ResponseQuery{}, err
}
}
// Restore origin path and append proof op.
res.ProofOps.Ops = append(res.ProofOps.Ops, commitInfo.ProofOp(storeName))
return res, nil
}
// SetInitialVersion sets the initial version of the IAVL tree. It is used when
// starting a new chain at an arbitrary height.
func (rs *Store) SetInitialVersion(version int64) error {
rs.initialVersion = version
// Loop through all the stores, if it's an IAVL store, then set initial
// version on it.
for key, store := range rs.stores {
if store.GetStoreType() == types.StoreTypeIAVL {
// If the store is wrapped with an inter-block cache, we must first unwrap
// it to get the underlying IAVL store.
store = rs.GetCommitKVStore(key)
store.(types.StoreWithInitialVersion).SetInitialVersion(version)
}
}
return nil
}
// parsePath expects a format like /<storeName>[/<subpath>]
// Must start with /, subpath may be empty
// Returns error if it doesn't start with /
func parsePath(path string) (storeName, subpath string, err error) {
if !strings.HasPrefix(path, "/") {
return storeName, subpath, errorsmod.Wrapf(types.ErrUnknownRequest, "invalid path: %s", path)
}
paths := strings.SplitN(path[1:], "/", 2)
storeName = paths[0]
if len(paths) == 2 {
subpath = "/" + paths[1]
}
return storeName, subpath, nil
}
//---------------------- Snapshotting ------------------
// Snapshot implements snapshottypes.Snapshotter. The snapshot output for a given format must be
// identical across nodes such that chunks from different sources fit together. If the output for a
// given format changes (at the byte level), the snapshot format must be bumped - see
// TestMultistoreSnapshot_Checksum test.
func (rs *Store) Snapshot(height uint64, protoWriter protoio.Writer) error {
if height == 0 {
return errorsmod.Wrap(types.ErrLogic, "cannot snapshot height 0")
}
if height > uint64(GetLatestVersion(rs.db)) {
return errorsmod.Wrapf(types.ErrLogic, "cannot snapshot future height %v", height)
}
// Collect stores to snapshot (only IAVL stores are supported)
type namedStore struct {
*iavl.Store
name string
}
stores := []namedStore{}
keys := keysFromStoreKeyMap(rs.stores)
for _, key := range keys {
switch store := rs.GetCommitKVStore(key).(type) {
case *iavl.Store:
stores = append(stores, namedStore{name: key.Name(), Store: store})
case *transient.Store, *mem.Store:
// Non-persisted stores shouldn't be snapshotted
continue
default:
return errorsmod.Wrapf(types.ErrLogic,
"don't know how to snapshot store %q of type %T", key.Name(), store)
}
}
sort.Slice(stores, func(i, j int) bool {
return strings.Compare(stores[i].name, stores[j].name) == -1
})
// Export each IAVL store. Stores are serialized as a stream of SnapshotItem Protobuf
// messages. The first item contains a SnapshotStore with store metadata (i.e. name),
// and the following messages contain a SnapshotNode (i.e. an ExportNode). Store changes
// are demarcated by new SnapshotStore items.
for _, store := range stores {
rs.logger.Debug("starting snapshot", "store", store.name, "height", height)
exporter, err := store.Export(int64(height))
if err != nil {
rs.logger.Error("snapshot failed; exporter error", "store", store.name, "err", err)
return err
}
err = func() error {
defer exporter.Close()
err := protoWriter.WriteMsg(&snapshottypes.SnapshotItem{
Item: &snapshottypes.SnapshotItem_Store{
Store: &snapshottypes.SnapshotStoreItem{
Name: store.name,
},
},
})
if err != nil {
rs.logger.Error("snapshot failed; item store write failed", "store", store.name, "err", err)
return err
}
nodeCount := 0
for {
node, err := exporter.Next()
if err == iavltree.ErrorExportDone {
rs.logger.Debug("snapshot Done", "store", store.name, "nodeCount", nodeCount)
break
} else if err != nil {
return err
}
err = protoWriter.WriteMsg(&snapshottypes.SnapshotItem{
Item: &snapshottypes.SnapshotItem_IAVL{
IAVL: &snapshottypes.SnapshotIAVLItem{
Key: node.Key,
Value: node.Value,
Height: int32(node.Height),
Version: node.Version,
},
},
})
if err != nil {
return err
}
nodeCount++
}
return nil
}()
if err != nil {
return err
}
}
return nil
}
// Restore implements snapshottypes.Snapshotter.
// returns next snapshot item and error.
func (rs *Store) Restore(
height uint64, format uint32, protoReader protoio.Reader,
) (snapshottypes.SnapshotItem, error) {
// Import nodes into stores. The first item is expected to be a SnapshotItem containing
// a SnapshotStoreItem, telling us which store to import into. The following items will contain
// SnapshotNodeItem (i.e. ExportNode) until we reach the next SnapshotStoreItem or EOF.
var importer *iavltree.Importer
var snapshotItem snapshottypes.SnapshotItem
loop:
for {
snapshotItem = snapshottypes.SnapshotItem{}
err := protoReader.ReadMsg(&snapshotItem)
if err == io.EOF {
break
} else if err != nil {
return snapshottypes.SnapshotItem{}, errorsmod.Wrap(err, "invalid protobuf message")
}
switch item := snapshotItem.Item.(type) {
case *snapshottypes.SnapshotItem_Store:
if importer != nil {
err = importer.Commit()
if err != nil {
return snapshottypes.SnapshotItem{}, errorsmod.Wrap(err, "IAVL commit failed")
}
importer.Close()
}
store, ok := rs.GetStoreByName(item.Store.Name).(*iavl.Store)
if !ok || store == nil {
return snapshottypes.SnapshotItem{}, errorsmod.Wrapf(types.ErrLogic, "cannot import into non-IAVL store %q", item.Store.Name)
}
importer, err = store.Import(int64(height))
if err != nil {
return snapshottypes.SnapshotItem{}, errorsmod.Wrap(err, "import failed")
}
defer importer.Close()
// Importer height must reflect the node height (which usually matches the block height, but not always)
rs.logger.Debug("restoring snapshot", "store", item.Store.Name)
case *snapshottypes.SnapshotItem_IAVL:
if importer == nil {
rs.logger.Error("failed to restore; received IAVL node item before store item")
return snapshottypes.SnapshotItem{}, errorsmod.Wrap(types.ErrLogic, "received IAVL node item before store item")
}
if item.IAVL.Height > math.MaxInt8 {
return snapshottypes.SnapshotItem{}, errorsmod.Wrapf(types.ErrLogic, "node height %v cannot exceed %v",
item.IAVL.Height, math.MaxInt8)
}
node := &iavltree.ExportNode{
Key: item.IAVL.Key,
Value: item.IAVL.Value,
Height: int8(item.IAVL.Height),
Version: item.IAVL.Version,
}
// Protobuf does not differentiate between []byte{} as nil, but fortunately IAVL does
// not allow nil keys nor nil values for leaf nodes, so we can always set them to empty.
if node.Key == nil {
node.Key = []byte{}
}
if node.Height == 0 && node.Value == nil {
node.Value = []byte{}
}
err := importer.Add(node)
if err != nil {
return snapshottypes.SnapshotItem{}, errorsmod.Wrap(err, "IAVL node import failed")
}
default:
break loop
}
}
if importer != nil {
err := importer.Commit()
if err != nil {
return snapshottypes.SnapshotItem{}, errorsmod.Wrap(err, "IAVL commit failed")
}
importer.Close()
}
rs.flushMetadata(rs.db, int64(height), rs.buildCommitInfo(int64(height)))
return snapshotItem, rs.LoadLatestVersion()
}
func (rs *Store) loadCommitStoreFromParams(key types.StoreKey, id types.CommitID, params storeParams) (types.CommitKVStore, error) {
var db dbm.DB
if params.db != nil {
db = dbm.NewPrefixDB(params.db, []byte("s/_/"))
} else {
prefix := "s/k:" + params.key.Name() + "/"
db = dbm.NewPrefixDB(rs.db, []byte(prefix))
}
switch params.typ {
case types.StoreTypeMulti:
panic("recursive MultiStores not yet supported")
case types.StoreTypeIAVL:
var store types.CommitKVStore
var err error
if params.initialVersion == 0 {
store, err = iavl.LoadStore(db, rs.logger, key, id, rs.iavlCacheSize, rs.iavlDisableFastNode, rs.commitSync, rs.metrics)
} else {
store, err = iavl.LoadStoreWithInitialVersion(db, rs.logger, key, id, params.initialVersion, rs.iavlCacheSize, rs.iavlDisableFastNode, rs.commitSync, rs.metrics)
}
if err != nil {
return nil, err
}
if rs.interBlockCache != nil {
// Wrap and get a CommitKVStore with inter-block caching. Note, this should
// only wrap the primary CommitKVStore, not any store that is already
// branched as that will create unexpected behavior.
store = rs.interBlockCache.GetStoreCache(key, store)
}
return store, err
case types.StoreTypeDB:
return commitDBStoreAdapter{Store: dbadapter.Store{DB: db}}, nil
case types.StoreTypeTransient:
_, ok := key.(*types.TransientStoreKey)
if !ok {
return nil, fmt.Errorf("invalid StoreKey for StoreTypeTransient: %s", key.String())
}
return transient.NewStore(), nil
case types.StoreTypeMemory:
if _, ok := key.(*types.MemoryStoreKey); !ok {
return nil, fmt.Errorf("unexpected key type for a MemoryStoreKey; got: %s", key.String())
}
return mem.NewStore(), nil
default:
panic(fmt.Sprintf("unrecognized store type %v", params.typ))
}
}
func (rs *Store) buildCommitInfo(version int64) *types.CommitInfo {
keys := keysFromStoreKeyMap(rs.stores)
storeInfos := []types.StoreInfo{}
for _, key := range keys {
store := rs.stores[key]
storeType := store.GetStoreType()
if storeType == types.StoreTypeTransient || storeType == types.StoreTypeMemory {
continue
}
storeInfos = append(storeInfos, types.StoreInfo{
Name: key.Name(),
CommitId: store.LastCommitID(),
})
}
return &types.CommitInfo{
Version: version,
StoreInfos: storeInfos,
}
}
// RollbackToVersion delete the versions after `target` and update the latest version.
func (rs *Store) RollbackToVersion(target int64) error {
if target <= 0 {
return fmt.Errorf("invalid rollback height target: %d", target)
}
for key, store := range rs.stores {
if store.GetStoreType() == types.StoreTypeIAVL {
// If the store is wrapped with an inter-block cache, we must first unwrap
// it to get the underlying IAVL store.
store = rs.GetCommitKVStore(key)
err := store.(*iavl.Store).LoadVersionForOverwriting(target)
if err != nil {
return err
}
}
}
rs.flushMetadata(rs.db, target, rs.buildCommitInfo(target))
return rs.LoadLatestVersion()
}
// SetCommitHeader sets the commit block header of the store.
func (rs *Store) SetCommitHeader(h cmtproto.Header) {
rs.commitHeader = h
}
// GetCommitInfo attempts to retrieve CommitInfo for a given version/height. It
// will return an error if no CommitInfo exists, we fail to unmarshal the record
// or if we cannot retrieve the object from the DB.
func (rs *Store) GetCommitInfo(ver int64) (*types.CommitInfo, error) {
cInfoKey := fmt.Sprintf(commitInfoKeyFmt, ver)
bz, err := rs.db.Get([]byte(cInfoKey))
if err != nil {
return nil, errorsmod.Wrap(err, "failed to get commit info")
} else if bz == nil {
return nil, errors.New("no commit info found")
}
cInfo := &types.CommitInfo{}
if err = cInfo.Unmarshal(bz); err != nil {
return nil, errorsmod.Wrap(err, "failed unmarshal commit info")
}
return cInfo, nil
}
func (rs *Store) flushMetadata(db dbm.DB, version int64, cInfo *types.CommitInfo) {
rs.logger.Debug("flushing metadata", "height", version)
batch := db.NewBatch()
defer func() {
_ = batch.Close()
}()
if cInfo != nil {
flushCommitInfo(batch, version, cInfo)
} else {
rs.logger.Debug("commitInfo is nil, not flushed", "height", version)
}
flushLatestVersion(batch, version)
if err := batch.WriteSync(); err != nil {
panic(fmt.Errorf("error on batch write %w", err))
}
rs.logger.Debug("flushing metadata finished", "height", version)
}
type storeParams struct {
key types.StoreKey
db dbm.DB
typ types.StoreType
initialVersion uint64
}
func newStoreParams(key types.StoreKey, db dbm.DB, typ types.StoreType, initialVersion uint64) storeParams {
return storeParams{
key: key,
db: db,
typ: typ,
initialVersion: initialVersion,
}
}
func GetLatestVersion(db dbm.DB) int64 {
bz, err := db.Get([]byte(latestVersionKey))
if err != nil {
panic(err)
} else if bz == nil {
return 0
}
var latestVersion int64
if err := gogotypes.StdInt64Unmarshal(&latestVersion, bz); err != nil {
panic(err)
}
return latestVersion
}
// Commits each store and returns a new commitInfo.
func commitStores(version int64, storeMap map[types.StoreKey]types.CommitKVStore, removalMap map[types.StoreKey]bool) *types.CommitInfo {
storeInfos := make([]types.StoreInfo, 0, len(storeMap))
storeKeys := keysFromStoreKeyMap(storeMap)
for _, key := range storeKeys {
store := storeMap[key]
last := store.LastCommitID()
// If a commit event execution is interrupted, a new iavl store's version
// will be larger than the RMS's metadata, when the block is replayed, we
// should avoid committing that iavl store again.
var commitID types.CommitID
if last.Version >= version {
last.Version = version
commitID = last
} else {
commitID = store.Commit()
}
storeType := store.GetStoreType()
if storeType == types.StoreTypeTransient || storeType == types.StoreTypeMemory {
continue
}
if !removalMap[key] {
si := types.StoreInfo{}
si.Name = key.Name()
si.CommitId = commitID
storeInfos = append(storeInfos, si)
}
}
sort.SliceStable(storeInfos, func(i, j int) bool {
return strings.Compare(storeInfos[i].Name, storeInfos[j].Name) < 0
})
return &types.CommitInfo{
Version: version,
StoreInfos: storeInfos,
}
}
func flushCommitInfo(batch dbm.Batch, version int64, cInfo *types.CommitInfo) {
bz, err := cInfo.Marshal()
if err != nil {
panic(err)
}
cInfoKey := fmt.Sprintf(commitInfoKeyFmt, version)
err = batch.Set([]byte(cInfoKey), bz)
if err != nil {
panic(err)
}
}
func flushLatestVersion(batch dbm.Batch, version int64) {
bz, err := gogotypes.StdInt64Marshal(version)
if err != nil {
panic(err)
}
err = batch.Set([]byte(latestVersionKey), bz)
if err != nil {
panic(err)
}
}
package keeper
import (
"encoding/binary"
corestoretypes "cosmossdk.io/core/store"
errorsmod "cosmossdk.io/errors"
storetypes "cosmossdk.io/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
// CountTXDecorator ante handler to count the tx position in a block.
type CountTXDecorator struct {
storeService corestoretypes.KVStoreService
}
// NewCountTXDecorator constructor
func NewCountTXDecorator(s corestoretypes.KVStoreService) *CountTXDecorator {
return &CountTXDecorator{storeService: s}
}
// AnteHandle handler stores a tx counter with current height encoded in the store to let the app handle
// global rollback behavior instead of keeping state in the handler itself.
// The ante handler passes the counter value via sdk.Context upstream. See `types.TXCounter(ctx)` to read the value.
// Simulations don't get a tx counter value assigned.
func (a CountTXDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
if simulate {
return next(ctx, tx, simulate)
}
store := a.storeService.OpenKVStore(ctx)
currentHeight := ctx.BlockHeight()
var txCounter uint32 // start with 0
// load counter when exists
bz, err := store.Get(types.TXCounterPrefix)
if err != nil {
return ctx, errorsmod.Wrap(err, "read tx counter")
}
if bz != nil {
lastHeight, val := decodeHeightCounter(bz)
if currentHeight == lastHeight {
// then use stored counter
txCounter = val
} // else use `0` from above to start with
}
// store next counter value for current height
err = store.Set(types.TXCounterPrefix, encodeHeightCounter(currentHeight, txCounter+1))
if err != nil {
return ctx, errorsmod.Wrap(err, "store tx counter")
}
return next(types.WithTXCounter(ctx, txCounter), tx, simulate)
}
func encodeHeightCounter(height int64, counter uint32) []byte {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, counter)
return append(sdk.Uint64ToBigEndian(uint64(height)), b...)
}
func decodeHeightCounter(bz []byte) (int64, uint32) {
return int64(sdk.BigEndianToUint64(bz[0:8])), binary.BigEndian.Uint32(bz[8:])
}
// LimitSimulationGasDecorator ante decorator to limit gas in simulation calls
type LimitSimulationGasDecorator struct {
gasLimit *storetypes.Gas
}
// NewLimitSimulationGasDecorator constructor accepts nil value to fallback to block gas limit.
func NewLimitSimulationGasDecorator(gasLimit *storetypes.Gas) *LimitSimulationGasDecorator {
if gasLimit != nil && *gasLimit == 0 {
panic("gas limit must not be zero")
}
return &LimitSimulationGasDecorator{gasLimit: gasLimit}
}
// AnteHandle that limits the maximum gas available in simulations only.
// A custom max value can be configured and will be applied when set. The value should not
// exceed the max block gas limit.
// Different values on nodes are not consensus breaking as they affect only
// simulations but may have effect on client user experience.
//
// When no custom value is set then the max block gas is used as default limit.
func (d LimitSimulationGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
if !simulate {
// Wasm code is not executed in checkTX so that we don't need to limit it further.
// Tendermint rejects the TX afterwards when the tx.gas > max block gas.
// On deliverTX we rely on the tendermint/sdk mechanics that ensure
// tx has gas set and gas < max block gas
return next(ctx, tx, simulate)
}
// apply custom node gas limit
if d.gasLimit != nil {
return next(ctx.WithGasMeter(storetypes.NewGasMeter(*d.gasLimit)), tx, simulate)
}
// default to max block gas when set, to be on the safe side
params := ctx.ConsensusParams()
if maxGas := params.GetBlock().MaxGas; maxGas > 0 {
return next(ctx.WithGasMeter(storetypes.NewGasMeter(storetypes.Gas(maxGas))), tx, simulate)
}
return next(ctx, tx, simulate)
}
// GasRegisterDecorator ante decorator to store gas register in the context
type GasRegisterDecorator struct {
gasRegister types.GasRegister
}
// NewGasRegisterDecorator constructor.
func NewGasRegisterDecorator(gr types.GasRegister) *GasRegisterDecorator {
return &GasRegisterDecorator{gasRegister: gr}
}
// AnteHandle adds the gas register to the context.
func (g GasRegisterDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
return next(types.WithGasRegister(ctx, g.gasRegister), tx, simulate)
}
package keeper
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"math"
"reflect"
"strconv"
"strings"
"time"
wasmvm "github.com/CosmWasm/wasmvm/v2"
wasmvmtypes "github.com/CosmWasm/wasmvm/v2/types"
channeltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types"
"cosmossdk.io/collections"
corestoretypes "cosmossdk.io/core/store"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
"cosmossdk.io/store/prefix"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
vestingexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported"
"github.com/CosmWasm/wasmd/x/wasm/ioutils"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
// contractMemoryLimit is the memory limit of each contract execution (in MiB)
// constant value so all nodes run with the same limit.
const contractMemoryLimit = 32
// Option is an extension point to instantiate keeper with non default values
type Option interface {
apply(*Keeper)
}
// WasmVMQueryHandler is an extension point for custom query handler implementations
type WasmVMQueryHandler interface {
// HandleQuery executes the requested query
HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error)
}
type CoinTransferrer interface {
// TransferCoins sends the coin amounts from the source to the destination with rules applied.
TransferCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error
}
// AccountPruner handles the balances and data cleanup for accounts that are pruned on contract instantiate.
// This is an extension point to attach custom logic
type AccountPruner interface {
// CleanupExistingAccount handles the cleanup process for balances and data of the given account. The persisted account
// type is already reset to base account at this stage.
// The method returns true when the account address can be reused. Unsupported account types are rejected by returning false
CleanupExistingAccount(ctx sdk.Context, existingAccount sdk.AccountI) (handled bool, err error)
}
// WasmVMResponseHandler is an extension point to handles the response data returned by a contract call.
type WasmVMResponseHandler interface {
// Handle processes the data returned by a contract invocation.
Handle(
ctx sdk.Context,
contractAddr sdk.AccAddress,
ibcPort string,
messages []wasmvmtypes.SubMsg,
origRspData []byte,
) ([]byte, error)
}
// list of account types that are accepted for wasm contracts. Chains importing wasmd
// can overwrite this list with the WithAcceptedAccountTypesOnContractInstantiation option.
var defaultAcceptedAccountTypes = map[reflect.Type]struct{}{
reflect.TypeOf(&authtypes.BaseAccount{}): {},
}
// Keeper will have a reference to Wasm Engine with it's own data directory.
type Keeper struct {
// The (unexposed) keys used to access the stores from the Context.
storeService corestoretypes.KVStoreService
cdc codec.Codec
accountKeeper types.AccountKeeper
bank CoinTransferrer
portKeeper types.PortKeeper
capabilityKeeper types.CapabilityKeeper
wasmVM types.WasmEngine
wasmVMQueryHandler WasmVMQueryHandler
wasmVMResponseHandler WasmVMResponseHandler
messenger Messenger
// queryGasLimit is the max wasmvm gas that can be spent on executing a query with a contract
queryGasLimit uint64
gasRegister types.GasRegister
maxQueryStackSize uint32
maxCallDepth uint32
acceptedAccountTypes map[reflect.Type]struct{}
accountPruner AccountPruner
params collections.Item[types.Params]
// propagate gov authZ to sub-messages
propagateGovAuthorization map[types.AuthorizationPolicyAction]struct{}
// the address capable of executing a MsgUpdateParams message. Typically, this
// should be the x/gov module account.
authority string
}
func (k Keeper) getUploadAccessConfig(ctx context.Context) types.AccessConfig {
return k.GetParams(ctx).CodeUploadAccess
}
func (k Keeper) getInstantiateAccessConfig(ctx context.Context) types.AccessType {
return k.GetParams(ctx).InstantiateDefaultPermission
}
// GetParams returns the total set of wasm parameters.
func (k Keeper) GetParams(ctx context.Context) types.Params {
p, err := k.params.Get(ctx)
if err != nil {
panic(err)
}
return p
}
// SetParams sets all wasm parameters.
func (k Keeper) SetParams(ctx context.Context, ps types.Params) error {
return k.params.Set(ctx, ps)
}
// GetAuthority returns the x/wasm module's authority.
func (k Keeper) GetAuthority() string {
return k.authority
}
// GetGasRegister returns the x/wasm module's gas register.
func (k Keeper) GetGasRegister() types.GasRegister {
return k.gasRegister
}
// Cleanup is used to release cache lock of VM instance
func (k Keeper) Cleanup() {
k.wasmVM.Cleanup()
}
func (k Keeper) create(ctx context.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig, authZ types.AuthorizationPolicy) (codeID uint64, checksum []byte, err error) {
if creator == nil {
return 0, checksum, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "cannot be nil")
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
// figure out proper instantiate access
defaultAccessConfig := k.getInstantiateAccessConfig(sdkCtx).With(creator)
if instantiateAccess == nil {
instantiateAccess = &defaultAccessConfig
}
chainConfigs := types.ChainAccessConfigs{
Instantiate: defaultAccessConfig,
Upload: k.getUploadAccessConfig(sdkCtx),
}
if !authZ.CanCreateCode(chainConfigs, creator, *instantiateAccess) {
return 0, checksum, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not create code")
}
if ioutils.IsGzip(wasmCode) {
sdkCtx.GasMeter().ConsumeGas(k.gasRegister.UncompressCosts(len(wasmCode)), "Uncompress gzip bytecode")
wasmCode, err = ioutils.Uncompress(wasmCode, int64(types.MaxWasmSize))
if err != nil {
return 0, checksum, types.ErrCreateFailed.Wrap(errorsmod.Wrap(err, "uncompress wasm archive").Error())
}
}
gasLeft := k.runtimeGasForContract(sdkCtx)
var gasUsed uint64
isSimulation := sdkCtx.ExecMode() == sdk.ExecModeSimulate
if isSimulation {
// only simulate storing the code, no files are written
checksum, gasUsed, err = k.wasmVM.SimulateStoreCode(wasmCode, gasLeft)
} else {
checksum, gasUsed, err = k.wasmVM.StoreCode(wasmCode, gasLeft)
}
k.consumeRuntimeGas(sdkCtx, gasUsed)
if err != nil {
return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error())
}
// simulation gets default value for capabilities
var requiredCapabilities string
if !isSimulation {
report, err := k.wasmVM.AnalyzeCode(checksum)
if err != nil {
return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error())
}
requiredCapabilities = report.RequiredCapabilities
}
codeID = k.mustAutoIncrementID(sdkCtx, types.KeySequenceCodeID)
k.Logger(sdkCtx).Debug("storing new contract", "capabilities", requiredCapabilities, "code_id", codeID)
codeInfo := types.NewCodeInfo(checksum, creator, *instantiateAccess)
k.mustStoreCodeInfo(sdkCtx, codeID, codeInfo)
evt := sdk.NewEvent(
types.EventTypeStoreCode,
sdk.NewAttribute(types.AttributeKeyChecksum, hex.EncodeToString(checksum)),
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), // last element to be compatible with scripts
)
for _, f := range strings.Split(requiredCapabilities, ",") {
evt.AppendAttributes(sdk.NewAttribute(types.AttributeKeyRequiredCapability, strings.TrimSpace(f)))
}
sdkCtx.EventManager().EmitEvent(evt)
sdkCtx.EventManager().EmitTypedEvent(&types.EventCodeStored{
CodeID: codeID,
Creator: creator.String(),
AccessConfig: instantiateAccess,
Checksum: checksum,
})
return codeID, checksum, nil
}
func (k Keeper) mustStoreCodeInfo(ctx context.Context, codeID uint64, codeInfo types.CodeInfo) {
store := k.storeService.OpenKVStore(ctx)
// 0x01 | codeID (uint64) -> ContractInfo
err := store.Set(types.GetCodeKey(codeID), k.cdc.MustMarshal(&codeInfo))
if err != nil {
panic(err)
}
}
func (k Keeper) importCode(ctx context.Context, codeID uint64, codeInfo types.CodeInfo, wasmCode []byte) error {
if ioutils.IsGzip(wasmCode) {
var err error
wasmCode, err = ioutils.Uncompress(wasmCode, math.MaxInt64)
if err != nil {
return types.ErrCreateFailed.Wrap(errorsmod.Wrap(err, "uncompress wasm archive").Error())
}
}
newCodeHash, err := k.wasmVM.StoreCodeUnchecked(wasmCode)
if err != nil {
return errorsmod.Wrap(types.ErrCreateFailed, err.Error())
}
if !bytes.Equal(codeInfo.CodeHash, newCodeHash) {
return errorsmod.Wrap(types.ErrInvalid, "code hashes not same")
}
store := k.storeService.OpenKVStore(ctx)
key := types.GetCodeKey(codeID)
ok, err := store.Has(key)
if err != nil {
return errorsmod.Wrap(err, "has code-id key")
}
if ok {
return errorsmod.Wrapf(types.ErrDuplicate, "duplicate code: %d", codeID)
}
// 0x01 | codeID (uint64) -> ContractInfo
return store.Set(key, k.cdc.MustMarshal(&codeInfo))
}
func (k Keeper) instantiate(
ctx context.Context,
codeID uint64,
creator, admin sdk.AccAddress,
initMsg []byte,
label string,
deposit sdk.Coins,
addressGenerator AddressGenerator,
authPolicy types.AuthorizationPolicy,
) (sdk.AccAddress, []byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "instantiate")
if creator == nil {
return nil, nil, types.ErrEmpty.Wrap("creator")
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
setupCost := k.gasRegister.SetupContractCost(k.IsPinnedCode(sdkCtx, codeID), len(initMsg))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: instantiate")
codeInfo := k.GetCodeInfo(ctx, codeID)
if codeInfo == nil {
return nil, nil, types.ErrNoSuchCodeFn(codeID).Wrapf("code id %d", codeID)
}
if !authPolicy.CanInstantiateContract(codeInfo.InstantiateConfig, creator) {
return nil, nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate")
}
contractAddress := addressGenerator(ctx, codeID, codeInfo.CodeHash)
if k.HasContractInfo(ctx, contractAddress) {
// This case must only happen for instantiate2 because instantiate is based on a counter in state.
// So we create an instantiate2 specific error message here even though technically this function
// is used for both cases.
return nil, nil, types.ErrDuplicate.Wrap("contract address already exists, try a different combination of creator, checksum and salt")
}
// check account
// every cosmos module can define custom account types when needed. The cosmos-sdk comes with extension points
// to support this and a set of base and vesting account types that we integrated in our default lists.
// But not all account types of other modules are known or may make sense for contracts, therefore we kept this
// decision logic also very flexible and extendable. We provide new options to overwrite the default settings via WithAcceptedAccountTypesOnContractInstantiation and
// WithPruneAccountTypesOnContractInstantiation as constructor arguments
existingAcct := k.accountKeeper.GetAccount(sdkCtx, contractAddress)
if existingAcct != nil {
if existingAcct.GetSequence() != 0 || existingAcct.GetPubKey() != nil {
return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account")
}
if _, accept := k.acceptedAccountTypes[reflect.TypeOf(existingAcct)]; accept {
// keep account and balance as it is
k.Logger(sdkCtx).Info("instantiate contract with existing account", "address", contractAddress.String())
} else {
// consider an account in the wasmd namespace spam and overwrite it.
k.Logger(sdkCtx).Info("pruning existing account for contract instantiation", "address", contractAddress.String())
contractAccount := k.accountKeeper.NewAccountWithAddress(sdkCtx, contractAddress)
k.accountKeeper.SetAccount(sdkCtx, contractAccount)
// also handle balance to not open cases where these accounts are abused and become liquid
switch handled, err := k.accountPruner.CleanupExistingAccount(sdkCtx, existingAcct); {
case err != nil:
return nil, nil, errorsmod.Wrap(err, "prune balance")
case !handled:
return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account")
}
}
} else {
// create an empty account (so we don't have issues later)
contractAccount := k.accountKeeper.NewAccountWithAddress(sdkCtx, contractAddress)
k.accountKeeper.SetAccount(sdkCtx, contractAccount)
}
// deposit initial contract funds
if !deposit.IsZero() {
if err := k.bank.TransferCoins(sdkCtx, creator, contractAddress, deposit); err != nil {
return nil, nil, err
}
}
// prepare params for contract instantiate call
env := types.NewEnv(sdkCtx, contractAddress)
info := types.NewInfo(creator, deposit)
// create prefixed data store
// 0x03 | BuildContractAddressClassic (sdk.AccAddress)
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
vmStore := types.NewStoreAdapter(prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(sdkCtx)), prefixStoreKey))
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddress)
// instantiate wasm contract
gasLeft := k.runtimeGasForContract(sdkCtx)
res, gasUsed, err := k.wasmVM.Instantiate(codeInfo.CodeHash, env, info, initMsg, vmStore, cosmwasmAPI, querier, k.gasMeter(sdkCtx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if err != nil {
return nil, nil, errorsmod.Wrap(types.ErrVMError, err.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrInstantiateFailed, res.Err))
}
// persist instance first
createdAt := types.NewAbsoluteTxPosition(sdkCtx)
contractInfo := types.NewContractInfo(codeID, creator, admin, label, createdAt)
// check for IBC flag
report, err := k.wasmVM.AnalyzeCode(codeInfo.CodeHash)
if err != nil {
return nil, nil, errorsmod.Wrap(types.ErrVMError, err.Error())
}
if report.HasIBCEntryPoints {
// register IBC port
ibcPort, err := k.ensureIbcPort(sdkCtx, contractAddress)
if err != nil {
return nil, nil, err
}
contractInfo.IBCPortID = ibcPort
}
// store contract before dispatch so that contract could be called back
historyEntry := contractInfo.InitialHistory(initMsg)
err = k.addToContractCodeSecondaryIndex(sdkCtx, contractAddress, historyEntry)
if err != nil {
return nil, nil, err
}
err = k.addToContractCreatorSecondaryIndex(sdkCtx, creator, historyEntry.Updated, contractAddress)
if err != nil {
return nil, nil, err
}
err = k.appendToContractHistory(sdkCtx, contractAddress, historyEntry)
if err != nil {
return nil, nil, err
}
k.mustStoreContractInfo(sdkCtx, contractAddress, &contractInfo)
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeInstantiate,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)),
))
sdkCtx = types.WithSubMsgAuthzPolicy(sdkCtx, authPolicy.SubMessageAuthorizationPolicy(types.AuthZActionInstantiate))
data, err := k.handleContractResponse(sdkCtx, contractAddress, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Data, res.Ok.Events)
if err != nil {
return nil, nil, errorsmod.Wrap(err, "dispatch")
}
sdkCtx.EventManager().EmitTypedEvent(&types.EventContractInstantiated{
ContractAddress: contractAddress.String(),
Admin: contractInfo.Admin,
CodeID: contractInfo.CodeID,
Funds: deposit,
Msg: initMsg,
Label: label,
Creator: contractInfo.Creator,
})
return contractAddress, data, nil
}
// Execute executes the contract instance
func (k Keeper) execute(ctx context.Context, contractAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "execute")
sdkCtx := sdk.UnwrapSDKContext(ctx)
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress)
if err != nil {
return nil, err
}
setupCost := k.gasRegister.SetupContractCost(k.IsPinnedCode(ctx, contractInfo.CodeID), len(msg))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: execute")
// add more funds
if !coins.IsZero() {
if err := k.bank.TransferCoins(sdkCtx, caller, contractAddress, coins); err != nil {
return nil, err
}
}
env := types.NewEnv(sdkCtx, contractAddress)
info := types.NewInfo(caller, coins)
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddress)
gasLeft := k.runtimeGasForContract(sdkCtx)
res, gasUsed, execErr := k.wasmVM.Execute(codeInfo.CodeHash, env, info, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(sdkCtx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if execErr != nil {
return nil, errorsmod.Wrap(types.ErrVMError, execErr.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrExecuteFailed, res.Err))
}
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeExecute,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
data, err := k.handleContractResponse(sdkCtx, contractAddress, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Data, res.Ok.Events)
if err != nil {
return nil, errorsmod.Wrap(err, "dispatch")
}
return data, nil
}
func (k Keeper) migrate(
ctx context.Context,
contractAddress sdk.AccAddress,
caller sdk.AccAddress,
newCodeID uint64,
msg []byte,
authZ types.AuthorizationPolicy,
) ([]byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "migrate")
sdkCtx := sdk.UnwrapSDKContext(ctx)
contractInfo := k.GetContractInfo(ctx, contractAddress)
if contractInfo == nil {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract")
}
if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) {
return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not migrate")
}
newCodeInfo := k.GetCodeInfo(ctx, newCodeID)
if newCodeInfo == nil {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown code")
}
if !authZ.CanInstantiateContract(newCodeInfo.InstantiateConfig, caller) {
return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "to use new code")
}
// check for IBC flag
report, err := k.wasmVM.AnalyzeCode(newCodeInfo.CodeHash)
switch {
case err != nil:
return nil, errorsmod.Wrap(types.ErrVMError, err.Error())
case !report.HasIBCEntryPoints && contractInfo.IBCPortID != "":
// prevent update to non ibc contract
return nil, errorsmod.Wrap(types.ErrMigrationFailed, "requires ibc callbacks")
case report.HasIBCEntryPoints && contractInfo.IBCPortID == "":
// add ibc port
ibcPort, err := k.ensureIbcPort(sdkCtx, contractAddress)
if err != nil {
return nil, err
}
contractInfo.IBCPortID = ibcPort
}
var response *wasmvmtypes.Response
// check for migrate version
oldCodeInfo := k.GetCodeInfo(ctx, contractInfo.CodeID)
oldReport, err := k.wasmVM.AnalyzeCode(oldCodeInfo.CodeHash)
if err != nil {
return nil, errorsmod.Wrap(types.ErrVMError, err.Error())
}
// call migrate entrypoint, except if both migrate versions are set and the same value
if report.ContractMigrateVersion == nil ||
oldReport.ContractMigrateVersion == nil ||
*report.ContractMigrateVersion != *oldReport.ContractMigrateVersion {
response, err = k.callMigrateEntrypoint(sdkCtx, contractAddress, wasmvmtypes.Checksum(newCodeInfo.CodeHash), msg, newCodeID)
if err != nil {
return nil, err
}
}
// delete old secondary index entry
err = k.removeFromContractCodeSecondaryIndex(ctx, contractAddress, k.mustGetLastContractHistoryEntry(sdkCtx, contractAddress))
if err != nil {
return nil, err
}
// persist migration updates
historyEntry := contractInfo.AddMigration(sdkCtx, newCodeID, msg)
err = k.appendToContractHistory(ctx, contractAddress, historyEntry)
if err != nil {
return nil, err
}
err = k.addToContractCodeSecondaryIndex(ctx, contractAddress, historyEntry)
if err != nil {
return nil, err
}
k.mustStoreContractInfo(ctx, contractAddress, contractInfo)
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeMigrate,
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(newCodeID, 10)),
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
var data []byte
// if migrate entry point was called
if response != nil {
sdkCtx = types.WithSubMsgAuthzPolicy(sdkCtx, authZ.SubMessageAuthorizationPolicy(types.AuthZActionMigrateContract))
data, err = k.handleContractResponse(
sdkCtx,
contractAddress,
contractInfo.IBCPortID,
response.Messages,
response.Attributes,
response.Data,
response.Events,
)
if err != nil {
return nil, errorsmod.Wrap(err, "dispatch")
}
return data, nil
}
sdkCtx.EventManager().EmitTypedEvent(&types.EventContractMigrated{
CodeID: newCodeID,
ContractAddress: contractAddress.String(),
Msg: msg,
})
return data, nil
}
func (k Keeper) callMigrateEntrypoint(
sdkCtx sdk.Context,
contractAddress sdk.AccAddress,
newChecksum wasmvmtypes.Checksum,
msg []byte,
newCodeID uint64,
) (*wasmvmtypes.Response, error) {
setupCost := k.gasRegister.SetupContractCost(k.IsPinnedCode(sdkCtx, newCodeID), len(msg))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: migrate")
env := types.NewEnv(sdkCtx, contractAddress)
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddress)
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
vmStore := types.NewStoreAdapter(prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(sdkCtx)), prefixStoreKey))
gasLeft := k.runtimeGasForContract(sdkCtx)
res, gasUsed, err := k.wasmVM.Migrate(newChecksum, env, msg, vmStore, cosmwasmAPI, &querier, k.gasMeter(sdkCtx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if err != nil {
return nil, errorsmod.Wrap(types.ErrVMError, err.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrMigrationFailed, res.Err))
}
return res.Ok, nil
}
// Sudo allows privileged access to a contract. This can never be called by an external tx, but only by
// another native Go module directly, or on-chain governance (if sudo proposals are enabled). Thus, the keeper doesn't
// place any access controls on it, that is the responsibility or the app developer (who passes the wasm.Keeper in app.go)
//
// Sub-messages returned from the sudo call to the contract are executed with the default authorization policy. This can be
// customized though by passing a new policy with the context. See types.WithSubMsgAuthzPolicy.
// The policy will be read in msgServer.selectAuthorizationPolicy and used for sub-message executions.
// This is an extension point for some very advanced scenarios only. Use with care!
func (k Keeper) Sudo(ctx context.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "sudo")
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress)
if err != nil {
return nil, err
}
setupCost := k.gasRegister.SetupContractCost(k.IsPinnedCode(ctx, contractInfo.CodeID), len(msg))
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: sudo")
env := types.NewEnv(sdkCtx, contractAddress)
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddress)
gasLeft := k.runtimeGasForContract(sdkCtx)
res, gasUsed, execErr := k.wasmVM.Sudo(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(sdkCtx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if execErr != nil {
return nil, errorsmod.Wrap(types.ErrVMError, execErr.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrExecuteFailed, res.Err))
}
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeSudo,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
// sudo submessages are executed with the default authorization policy
data, err := k.handleContractResponse(sdkCtx, contractAddress, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Data, res.Ok.Events)
if err != nil {
return nil, errorsmod.Wrap(err, "dispatch")
}
return data, nil
}
// reply is only called from keeper internal functions (dispatchSubmessages) after processing the submessage
func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) {
contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress)
if err != nil {
return nil, err
}
// always consider this pinned
replyCosts := k.gasRegister.ReplyCosts(true, reply)
ctx.GasMeter().ConsumeGas(replyCosts, "Loading CosmWasm module: reply")
env := types.NewEnv(ctx, contractAddress)
// prepare querier
querier := k.newQueryHandler(ctx, contractAddress)
gasLeft := k.runtimeGasForContract(ctx)
res, gasUsed, execErr := k.wasmVM.Reply(codeInfo.CodeHash, env, reply, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gasLeft, costJSONDeserialization)
k.consumeRuntimeGas(ctx, gasUsed)
if execErr != nil {
return nil, errorsmod.Wrap(types.ErrVMError, execErr.Error())
}
if res == nil {
// If this gets executed, that's a bug in wasmvm
return nil, errorsmod.Wrap(types.ErrVMError, "internal wasmvm error")
}
if res.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrExecuteFailed, res.Err))
}
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeReply,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
))
data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Data, res.Ok.Events)
if err != nil {
return nil, errorsmod.Wrap(err, "dispatch")
}
return data, nil
}
// addToContractCodeSecondaryIndex adds element to the index for contracts-by-codeid queries
func (k Keeper) addToContractCodeSecondaryIndex(ctx context.Context, contractAddress sdk.AccAddress, entry types.ContractCodeHistoryEntry) error {
store := k.storeService.OpenKVStore(ctx)
return store.Set(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry), []byte{})
}
// removeFromContractCodeSecondaryIndex removes element to the index for contracts-by-codeid queries
func (k Keeper) removeFromContractCodeSecondaryIndex(ctx context.Context, contractAddress sdk.AccAddress, entry types.ContractCodeHistoryEntry) error {
return k.storeService.OpenKVStore(ctx).Delete(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry))
}
// addToContractCreatorSecondaryIndex adds element to the index for contracts-by-creator queries
func (k Keeper) addToContractCreatorSecondaryIndex(ctx context.Context, creatorAddress sdk.AccAddress, position *types.AbsoluteTxPosition, contractAddress sdk.AccAddress) error {
store := k.storeService.OpenKVStore(ctx)
return store.Set(types.GetContractByCreatorSecondaryIndexKey(creatorAddress, position.Bytes(), contractAddress), []byte{})
}
// IterateContractsByCreator iterates over all contracts with given creator address in order of creation time asc.
func (k Keeper) IterateContractsByCreator(ctx context.Context, creator sdk.AccAddress, cb func(address sdk.AccAddress) bool) {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.GetContractsByCreatorPrefix(creator))
for iter := prefixStore.Iterator(nil, nil); iter.Valid(); iter.Next() {
key := iter.Key()
if cb(key[types.AbsoluteTxPositionLen:]) {
return
}
}
}
// IterateContractsByCode iterates over all contracts with given codeID ASC on code update time.
func (k Keeper) IterateContractsByCode(ctx context.Context, codeID uint64, cb func(address sdk.AccAddress) bool) {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.GetContractByCodeIDSecondaryIndexPrefix(codeID))
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
key := iter.Key()
if cb(key[types.AbsoluteTxPositionLen:]) {
return
}
}
}
func (k Keeper) setContractAdmin(ctx context.Context, contractAddress, caller, newAdmin sdk.AccAddress, authZ types.AuthorizationPolicy) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
contractInfo := k.GetContractInfo(sdkCtx, contractAddress)
if contractInfo == nil {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract")
}
if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) {
return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract")
}
newAdminStr := newAdmin.String()
contractInfo.Admin = newAdminStr
k.mustStoreContractInfo(sdkCtx, contractAddress, contractInfo)
sdkCtx.EventManager().EmitTypedEvent(&types.EventContractAdminSet{
ContractAddress: contractAddress.String(),
NewAdmin: newAdmin.String(),
})
return nil
}
func (k Keeper) setContractLabel(ctx context.Context, contractAddress, caller sdk.AccAddress, newLabel string, authZ types.AuthorizationPolicy) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
contractInfo := k.GetContractInfo(sdkCtx, contractAddress)
if contractInfo == nil {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract")
}
if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) {
return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract")
}
contractInfo.Label = newLabel
k.mustStoreContractInfo(sdkCtx, contractAddress, contractInfo)
sdkCtx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeUpdateContractLabel,
sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()),
sdk.NewAttribute(types.AttributeKeyNewLabel, newLabel),
))
return nil
}
func (k Keeper) appendToContractHistory(ctx context.Context, contractAddr sdk.AccAddress, newEntries ...types.ContractCodeHistoryEntry) error {
store := k.storeService.OpenKVStore(ctx)
// find last element position
var pos uint64
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(store), types.GetContractCodeHistoryElementPrefix(contractAddr))
iter := prefixStore.ReverseIterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
if len(iter.Key()) == 8 { // add extra safety in a mixed contract length environment
pos = sdk.BigEndianToUint64(iter.Key())
break
}
}
// then store with incrementing position
for _, e := range newEntries {
pos++
key := types.GetContractCodeHistoryElementKey(contractAddr, pos)
if err := store.Set(key, k.cdc.MustMarshal(&e)); err != nil { //nolint:gosec
return err
}
}
return nil
}
func (k Keeper) GetContractHistory(ctx context.Context, contractAddr sdk.AccAddress) []types.ContractCodeHistoryEntry {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.GetContractCodeHistoryElementPrefix(contractAddr))
r := make([]types.ContractCodeHistoryEntry, 0)
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
if len(iter.Key()) != 8 { // add extra safety in a mixed contract length environment
continue
}
var e types.ContractCodeHistoryEntry
k.cdc.MustUnmarshal(iter.Value(), &e)
r = append(r, e)
}
return r
}
// mustGetLastContractHistoryEntry returns the last element from history. To be used internally only as it panics when none exists
func (k Keeper) mustGetLastContractHistoryEntry(ctx context.Context, contractAddr sdk.AccAddress) types.ContractCodeHistoryEntry {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.GetContractCodeHistoryElementPrefix(contractAddr))
iter := prefixStore.ReverseIterator(nil, nil)
defer iter.Close()
var r types.ContractCodeHistoryEntry
for ; iter.Valid(); iter.Next() {
if len(iter.Key()) == 8 { // add extra safety in a mixed contract length environment
k.cdc.MustUnmarshal(iter.Value(), &r)
return r
}
}
// all contracts have a history
panic(fmt.Sprintf("no history for %s", contractAddr.String()))
}
// QuerySmart queries the smart contract itself.
func (k Keeper) QuerySmart(ctx context.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-smart")
// checks and increase query stack size
sdkCtx, err := checkAndIncreaseQueryStackSize(sdk.UnwrapSDKContext(ctx), k.maxQueryStackSize)
if err != nil {
return nil, err
}
contractInfo, codeInfo, prefixStore, err := k.contractInstance(sdkCtx, contractAddr)
if err != nil {
return nil, err
}
setupCost := k.gasRegister.SetupContractCost(k.IsPinnedCode(sdkCtx, contractInfo.CodeID), len(req))
sdkCtx.GasMeter().ConsumeGas(setupCost, "Loading CosmWasm module: query")
// prepare querier
querier := k.newQueryHandler(sdkCtx, contractAddr)
env := types.NewEnv(sdkCtx, contractAddr)
queryResult, gasUsed, qErr := k.wasmVM.Query(codeInfo.CodeHash, env, req, prefixStore, cosmwasmAPI, querier, k.gasMeter(sdkCtx), k.runtimeGasForContract(sdkCtx), costJSONDeserialization)
k.consumeRuntimeGas(sdkCtx, gasUsed)
if qErr != nil {
return nil, errorsmod.Wrap(types.ErrVMError, qErr.Error())
}
if queryResult.Err != "" {
return nil, types.MarkErrorDeterministic(errorsmod.Wrap(types.ErrQueryFailed, queryResult.Err))
}
return queryResult.Ok, nil
}
func checkAndIncreaseQueryStackSize(ctx context.Context, maxQueryStackSize uint32) (sdk.Context, error) {
var queryStackSize uint32 = 0
if size, ok := types.QueryStackSize(ctx); ok {
queryStackSize = size
}
// increase
queryStackSize++
// did we go too far?
if queryStackSize > maxQueryStackSize {
return sdk.Context{}, types.ErrExceedMaxQueryStackSize
}
// set updated stack size
return types.WithQueryStackSize(sdk.UnwrapSDKContext(ctx), queryStackSize), nil
}
func checkAndIncreaseCallDepth(ctx context.Context, maxCallDepth uint32) (sdk.Context, error) {
var callDepth uint32 = 0
if size, ok := types.CallDepth(ctx); ok {
callDepth = size
}
// increase
callDepth++
// did we go too far?
if callDepth > maxCallDepth {
return sdk.Context{}, types.ErrExceedMaxCallDepth
}
// set updated stack size
return types.WithCallDepth(sdk.UnwrapSDKContext(ctx), callDepth), nil
}
// QueryRaw returns the contract's state for give key. Returns `nil` when key is `nil`.
func (k Keeper) QueryRaw(ctx context.Context, contractAddress sdk.AccAddress, key []byte) []byte {
defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-raw")
if key == nil {
return nil
}
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), prefixStoreKey)
return prefixStore.Get(key)
}
// internal helper function
func (k Keeper) contractInstance(ctx context.Context, contractAddress sdk.AccAddress) (types.ContractInfo, types.CodeInfo, wasmvm.KVStore, error) {
store := k.storeService.OpenKVStore(ctx)
contractBz, err := store.Get(types.GetContractAddressKey(contractAddress))
if err != nil {
return types.ContractInfo{}, types.CodeInfo{}, nil, err
}
if contractBz == nil {
return types.ContractInfo{}, types.CodeInfo{}, nil, types.ErrNoSuchContractFn(contractAddress.String()).
Wrapf("address %s", contractAddress.String())
}
var contractInfo types.ContractInfo
k.cdc.MustUnmarshal(contractBz, &contractInfo)
codeInfoBz, err := store.Get(types.GetCodeKey(contractInfo.CodeID))
if err != nil {
return types.ContractInfo{}, types.CodeInfo{}, nil, err
}
if codeInfoBz == nil {
return contractInfo, types.CodeInfo{}, nil, types.ErrNoSuchCodeFn(contractInfo.CodeID).
Wrapf("code id %d", contractInfo.CodeID)
}
var codeInfo types.CodeInfo
k.cdc.MustUnmarshal(codeInfoBz, &codeInfo)
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), prefixStoreKey)
return contractInfo, codeInfo, types.NewStoreAdapter(prefixStore), nil
}
func (k Keeper) LoadAsyncAckPacket(ctx context.Context, portID, channelID string, sequence uint64) (channeltypes.Packet, error) {
prefixStore, key := k.getAsyncAckStoreAndKey(ctx, portID, channelID, sequence)
packetBz := prefixStore.Get(key)
if len(packetBz) == 0 {
return channeltypes.Packet{}, types.ErrNotFound.Wrap("packet")
}
var packet channeltypes.Packet
// unmarshal packet
if err := k.cdc.Unmarshal(packetBz, &packet); err != nil {
return channeltypes.Packet{}, err
}
return packet, nil
}
func (k Keeper) StoreAsyncAckPacket(ctx context.Context, packet channeltypes.Packet) error {
prefixStore, key := k.getAsyncAckStoreAndKey(ctx, packet.DestinationPort, packet.DestinationChannel, packet.Sequence)
packetBz, err := k.cdc.Marshal(&packet)
if err != nil {
return err
}
prefixStore.Set(key, packetBz)
return nil
}
func (k Keeper) DeleteAsyncAckPacket(ctx context.Context, portID, channelID string, sequence uint64) {
prefixStore, key := k.getAsyncAckStoreAndKey(ctx, portID, channelID, sequence)
prefixStore.Delete(key)
}
func (k Keeper) getAsyncAckStoreAndKey(ctx context.Context, portID, channelID string, sequence uint64) (prefix.Store, []byte) {
// packets are stored under the destination port
prefixStoreKey := types.GetAsyncAckStorePrefix(portID)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), prefixStoreKey)
key := types.GetAsyncPacketKey(channelID, sequence)
return prefixStore, key
}
func (k Keeper) GetContractInfo(ctx context.Context, contractAddress sdk.AccAddress) *types.ContractInfo {
store := k.storeService.OpenKVStore(ctx)
var contract types.ContractInfo
contractBz, err := store.Get(types.GetContractAddressKey(contractAddress))
if err != nil {
panic(err)
}
if contractBz == nil {
return nil
}
k.cdc.MustUnmarshal(contractBz, &contract)
return &contract
}
func (k Keeper) HasContractInfo(ctx context.Context, contractAddress sdk.AccAddress) bool {
store := k.storeService.OpenKVStore(ctx)
ok, err := store.Has(types.GetContractAddressKey(contractAddress))
if err != nil {
panic(err)
}
return ok
}
// mustStoreContractInfo persists the ContractInfo. No secondary index updated here.
func (k Keeper) mustStoreContractInfo(ctx context.Context, contractAddress sdk.AccAddress, contract *types.ContractInfo) {
store := k.storeService.OpenKVStore(ctx)
err := store.Set(types.GetContractAddressKey(contractAddress), k.cdc.MustMarshal(contract))
if err != nil {
panic(err)
}
}
func (k Keeper) IterateContractInfo(ctx context.Context, cb func(sdk.AccAddress, types.ContractInfo) bool) {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.ContractKeyPrefix)
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var contract types.ContractInfo
k.cdc.MustUnmarshal(iter.Value(), &contract)
// cb returns true to stop early
if cb(iter.Key(), contract) {
break
}
}
}
// IterateContractState iterates through all elements of the key value store for the given contract address and passes
// them to the provided callback function. The callback method can return true to abort early.
func (k Keeper) IterateContractState(ctx context.Context, contractAddress sdk.AccAddress, cb func(key, value []byte) bool) {
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), prefixStoreKey)
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
if cb(iter.Key(), iter.Value()) {
break
}
}
}
func (k Keeper) importContractState(ctx context.Context, contractAddress sdk.AccAddress, models []types.Model) error {
prefixStoreKey := types.GetContractStorePrefix(contractAddress)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), prefixStoreKey)
for _, model := range models {
if model.Value == nil {
model.Value = []byte{}
}
if prefixStore.Has(model.Key) {
return errorsmod.Wrapf(types.ErrDuplicate, "duplicate key: %x", model.Key)
}
prefixStore.Set(model.Key, model.Value)
}
return nil
}
func (k Keeper) GetCodeInfo(ctx context.Context, codeID uint64) *types.CodeInfo {
store := k.storeService.OpenKVStore(ctx)
var codeInfo types.CodeInfo
codeInfoBz, err := store.Get(types.GetCodeKey(codeID))
if err != nil {
panic(err)
}
if codeInfoBz == nil {
return nil
}
k.cdc.MustUnmarshal(codeInfoBz, &codeInfo)
return &codeInfo
}
func (k Keeper) containsCodeInfo(ctx context.Context, codeID uint64) bool {
store := k.storeService.OpenKVStore(ctx)
ok, err := store.Has(types.GetCodeKey(codeID))
if err != nil {
panic(err)
}
return ok
}
func (k Keeper) IterateCodeInfos(ctx context.Context, cb func(uint64, types.CodeInfo) bool) {
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.CodeKeyPrefix)
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var c types.CodeInfo
k.cdc.MustUnmarshal(iter.Value(), &c)
// cb returns true to stop early
if cb(binary.BigEndian.Uint64(iter.Key()), c) {
return
}
}
}
func (k Keeper) GetByteCode(ctx context.Context, codeID uint64) ([]byte, error) {
store := k.storeService.OpenKVStore(ctx)
var codeInfo types.CodeInfo
codeInfoBz, err := store.Get(types.GetCodeKey(codeID))
if err != nil {
return nil, err
}
if codeInfoBz == nil {
return nil, nil
}
k.cdc.MustUnmarshal(codeInfoBz, &codeInfo)
return k.wasmVM.GetCode(codeInfo.CodeHash)
}
// PinCode pins the wasm contract in wasmvm cache
func (k Keeper) pinCode(ctx context.Context, codeID uint64) error {
codeInfo := k.GetCodeInfo(ctx, codeID)
if codeInfo == nil {
return types.ErrNoSuchCodeFn(codeID).Wrapf("code id %d", codeID)
}
if err := k.wasmVM.Pin(codeInfo.CodeHash); err != nil {
return errorsmod.Wrap(types.ErrPinContractFailed, err.Error())
}
store := k.storeService.OpenKVStore(ctx)
// store 1 byte to not run into `nil` debugging issues
err := store.Set(types.GetPinnedCodeIndexPrefix(codeID), []byte{1})
if err != nil {
return err
}
sdk.UnwrapSDKContext(ctx).EventManager().EmitEvent(sdk.NewEvent(
types.EventTypePinCode,
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)),
))
return nil
}
// UnpinCode removes the wasm contract from wasmvm cache
func (k Keeper) unpinCode(ctx context.Context, codeID uint64) error {
codeInfo := k.GetCodeInfo(ctx, codeID)
if codeInfo == nil {
return types.ErrNoSuchCodeFn(codeID).Wrapf("code id %d", codeID)
}
if err := k.wasmVM.Unpin(codeInfo.CodeHash); err != nil {
return errorsmod.Wrap(types.ErrUnpinContractFailed, err.Error())
}
store := k.storeService.OpenKVStore(ctx)
err := store.Delete(types.GetPinnedCodeIndexPrefix(codeID))
if err != nil {
return err
}
sdk.UnwrapSDKContext(ctx).EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeUnpinCode,
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)),
))
return nil
}
// IsPinnedCode returns true when codeID is pinned in wasmvm cache
func (k Keeper) IsPinnedCode(ctx context.Context, codeID uint64) bool {
store := k.storeService.OpenKVStore(ctx)
ok, err := store.Has(types.GetPinnedCodeIndexPrefix(codeID))
if err != nil {
panic(err)
}
return ok
}
// InitializePinnedCodes updates wasmvm to pin to cache all contracts marked as pinned
func (k Keeper) InitializePinnedCodes(ctx context.Context) error {
store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), types.PinnedCodeIndexPrefix)
iter := store.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
codeID := types.ParsePinnedCodeIndex(iter.Key())
codeInfo := k.GetCodeInfo(ctx, codeID)
if codeInfo == nil {
return types.ErrNoSuchCodeFn(codeID).Wrapf("code id %d", codeID)
}
if err := k.wasmVM.Pin(codeInfo.CodeHash); err != nil {
return errorsmod.Wrap(types.ErrPinContractFailed, err.Error())
}
}
return nil
}
// setContractInfoExtension updates the extension point data that is stored with the contract info
func (k Keeper) setContractInfoExtension(ctx context.Context, contractAddr sdk.AccAddress, ext types.ContractInfoExtension) error {
info := k.GetContractInfo(ctx, contractAddr)
if info == nil {
return types.ErrNoSuchContractFn(contractAddr.String()).
Wrapf("address %s", contractAddr.String())
}
if err := info.SetExtension(ext); err != nil {
return err
}
k.mustStoreContractInfo(ctx, contractAddr, info)
return nil
}
// setAccessConfig updates the access config of a code id.
func (k Keeper) setAccessConfig(ctx context.Context, codeID uint64, caller sdk.AccAddress, newConfig types.AccessConfig, authz types.AuthorizationPolicy) error {
info := k.GetCodeInfo(ctx, codeID)
if info == nil {
return types.ErrNoSuchCodeFn(codeID).Wrapf("code id %d", codeID)
}
isSubset := newConfig.Permission.IsSubset(k.getInstantiateAccessConfig(ctx))
if !authz.CanModifyCodeAccessConfig(sdk.MustAccAddressFromBech32(info.Creator), caller, isSubset) {
return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify code access config")
}
info.InstantiateConfig = newConfig
k.mustStoreCodeInfo(ctx, codeID, *info)
evt := sdk.NewEvent(
types.EventTypeUpdateCodeAccessConfig,
sdk.NewAttribute(types.AttributeKeyCodePermission, newConfig.Permission.String()),
sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)),
)
if addrs := newConfig.AllAuthorizedAddresses(); len(addrs) != 0 {
attr := sdk.NewAttribute(types.AttributeKeyAuthorizedAddresses, strings.Join(addrs, ","))
evt.Attributes = append(evt.Attributes, attr.ToKVPair())
}
sdk.UnwrapSDKContext(ctx).EventManager().EmitEvent(evt)
return nil
}
// handleContractResponse processes the contract response data by emitting events and sending sub-/messages.
func (k *Keeper) handleContractResponse(
ctx sdk.Context,
contractAddr sdk.AccAddress,
ibcPort string,
msgs []wasmvmtypes.SubMsg,
attrs []wasmvmtypes.EventAttribute,
data []byte,
evts wasmvmtypes.Array[wasmvmtypes.Event],
) ([]byte, error) {
attributeGasCost := k.gasRegister.EventCosts(attrs, evts)
ctx.GasMeter().ConsumeGas(attributeGasCost, "Custom contract event attributes")
// emit all events from this contract itself
if len(attrs) != 0 {
wasmEvents, err := newWasmModuleEvent(attrs, contractAddr)
if err != nil {
return nil, err
}
ctx.EventManager().EmitEvents(wasmEvents)
}
if len(evts) > 0 {
customEvents, err := newCustomEvents(evts, contractAddr)
if err != nil {
return nil, err
}
ctx.EventManager().EmitEvents(customEvents)
}
return k.wasmVMResponseHandler.Handle(ctx, contractAddr, ibcPort, msgs, data)
}
func (k Keeper) runtimeGasForContract(ctx sdk.Context) uint64 {
meter := ctx.GasMeter()
if meter.IsOutOfGas() {
return 0
}
if meter.Limit() == math.MaxUint64 { // infinite gas meter and not out of gas
return math.MaxUint64
}
return k.gasRegister.ToWasmVMGas(meter.Limit() - meter.GasConsumedToLimit())
}
func (k Keeper) consumeRuntimeGas(ctx sdk.Context, gas uint64) {
consumed := k.gasRegister.FromWasmVMGas(gas)
ctx.GasMeter().ConsumeGas(consumed, "wasm contract")
// throw OutOfGas error if we ran out (got exactly to zero due to better limit enforcing)
if ctx.GasMeter().IsOutOfGas() {
panic(storetypes.ErrorOutOfGas{Descriptor: "Wasm engine function execution"})
}
}
func (k Keeper) mustAutoIncrementID(ctx context.Context, sequenceKey []byte) uint64 {
store := k.storeService.OpenKVStore(ctx)
bz, err := store.Get(sequenceKey)
if err != nil {
panic(err)
}
id := uint64(1)
if bz != nil {
id = binary.BigEndian.Uint64(bz)
}
bz = sdk.Uint64ToBigEndian(id + 1)
err = store.Set(sequenceKey, bz)
if err != nil {
panic(err)
}
return id
}
// PeekAutoIncrementID reads the current value without incrementing it.
func (k Keeper) PeekAutoIncrementID(ctx context.Context, sequenceKey []byte) (uint64, error) {
store := k.storeService.OpenKVStore(ctx)
bz, err := store.Get(sequenceKey)
if err != nil {
return 0, errorsmod.Wrap(err, "sequence key")
}
id := uint64(1)
if bz != nil {
id = binary.BigEndian.Uint64(bz)
}
return id, nil
}
func (k Keeper) importAutoIncrementID(ctx context.Context, sequenceKey []byte, val uint64) error {
store := k.storeService.OpenKVStore(ctx)
ok, err := store.Has(sequenceKey)
if err != nil {
return errorsmod.Wrap(err, "sequence key")
}
if ok {
return errorsmod.Wrapf(types.ErrDuplicate, "autoincrement id: %s", string(sequenceKey))
}
bz := sdk.Uint64ToBigEndian(val)
return store.Set(sequenceKey, bz)
}
func (k Keeper) importContract(ctx context.Context, contractAddr sdk.AccAddress, c *types.ContractInfo, state []types.Model, historyEntries []types.ContractCodeHistoryEntry) error {
if !k.containsCodeInfo(ctx, c.CodeID) {
return types.ErrNoSuchCodeFn(c.CodeID).Wrapf("code id %d", c.CodeID)
}
if k.HasContractInfo(ctx, contractAddr) {
return errorsmod.Wrapf(types.ErrDuplicate, "contract: %s", contractAddr)
}
if len(historyEntries) == 0 {
return types.ErrEmpty.Wrap("contract history")
}
creatorAddress, err := sdk.AccAddressFromBech32(c.Creator)
if err != nil {
return err
}
err = k.appendToContractHistory(ctx, contractAddr, historyEntries...)
if err != nil {
return err
}
k.mustStoreContractInfo(ctx, contractAddr, c)
err = k.addToContractCodeSecondaryIndex(ctx, contractAddr, historyEntries[len(historyEntries)-1])
if err != nil {
return err
}
err = k.addToContractCreatorSecondaryIndex(ctx, creatorAddress, historyEntries[0].Updated, contractAddr)
if err != nil {
return err
}
return k.importContractState(ctx, contractAddr, state)
}
func (k Keeper) newQueryHandler(ctx sdk.Context, contractAddress sdk.AccAddress) QueryHandler {
return NewQueryHandler(ctx, k.wasmVMQueryHandler, contractAddress, k.gasRegister)
}
// MultipliedGasMeter wraps the GasMeter from context and multiplies all reads by out defined multiplier
type MultipliedGasMeter struct {
originalMeter storetypes.GasMeter
GasRegister types.GasRegister
}
func NewMultipliedGasMeter(originalMeter storetypes.GasMeter, gr types.GasRegister) MultipliedGasMeter {
return MultipliedGasMeter{originalMeter: originalMeter, GasRegister: gr}
}
var _ wasmvm.GasMeter = MultipliedGasMeter{}
func (m MultipliedGasMeter) GasConsumed() storetypes.Gas {
return m.GasRegister.ToWasmVMGas(m.originalMeter.GasConsumed())
}
func (k Keeper) gasMeter(ctx sdk.Context) MultipliedGasMeter {
return NewMultipliedGasMeter(ctx.GasMeter(), k.gasRegister)
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return moduleLogger(ctx)
}
func moduleLogger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName))
}
// Querier creates a new grpc querier instance
func Querier(k *Keeper) *GrpcQuerier {
return NewGrpcQuerier(k.cdc, k.storeService, k, k.queryGasLimit)
}
// QueryGasLimit returns the gas limit for smart queries.
func (k Keeper) QueryGasLimit() storetypes.Gas {
return k.queryGasLimit
}
// BankCoinTransferrer replicates the cosmos-sdk behavior as in
// https://github.com/cosmos/cosmos-sdk/blob/v0.41.4/x/bank/keeper/msg_server.go#L26
type BankCoinTransferrer struct {
keeper types.BankKeeper
}
func NewBankCoinTransferrer(keeper types.BankKeeper) BankCoinTransferrer {
return BankCoinTransferrer{
keeper: keeper,
}
}
// TransferCoins transfers coins from source to destination account when coin send was enabled for them and the recipient
// is not in the blocked address list.
func (c BankCoinTransferrer) TransferCoins(parentCtx sdk.Context, fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) error {
em := sdk.NewEventManager()
ctx := parentCtx.WithEventManager(em)
if err := c.keeper.IsSendEnabledCoins(ctx, amount...); err != nil {
return err
}
if c.keeper.BlockedAddr(toAddr) {
return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", toAddr.String())
}
sdkerr := c.keeper.SendCoins(ctx, fromAddr, toAddr, amount)
if sdkerr != nil {
return sdkerr
}
for _, e := range em.Events() {
if e.Type == sdk.EventTypeMessage { // skip messages as we talk to the keeper directly
continue
}
parentCtx.EventManager().EmitEvent(e)
}
return nil
}
var _ AccountPruner = VestingCoinBurner{}
// VestingCoinBurner default implementation for AccountPruner to burn the coins
type VestingCoinBurner struct {
bank types.BankKeeper
}
// NewVestingCoinBurner constructor
func NewVestingCoinBurner(bank types.BankKeeper) VestingCoinBurner {
if bank == nil {
panic("bank keeper must not be nil")
}
return VestingCoinBurner{bank: bank}
}
// CleanupExistingAccount accepts only vesting account types to burns all their original vesting coin balances.
// Other account types will be rejected and returned as unhandled.
func (b VestingCoinBurner) CleanupExistingAccount(ctx sdk.Context, existingAcc sdk.AccountI) (handled bool, err error) {
v, ok := existingAcc.(vestingexported.VestingAccount)
if !ok {
return false, nil
}
ctx = ctx.WithGasMeter(storetypes.NewInfiniteGasMeter())
coinsToBurn := sdk.NewCoins()
for _, orig := range v.GetOriginalVesting() { // focus on the coin denoms that were setup originally; getAllBalances has some issues
coinsToBurn = append(coinsToBurn, b.bank.GetBalance(ctx, existingAcc.GetAddress(), orig.Denom))
}
if err := b.bank.SendCoinsFromAccountToModule(ctx, existingAcc.GetAddress(), types.ModuleName, coinsToBurn); err != nil {
return false, errorsmod.Wrap(err, "prune account balance")
}
if err := b.bank.BurnCoins(ctx, types.ModuleName, coinsToBurn); err != nil {
return false, errorsmod.Wrap(err, "burn account balance")
}
return true, nil
}
type msgDispatcher interface {
DispatchSubmessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error)
}
// DefaultWasmVMContractResponseHandler default implementation that first dispatches submessage then normal messages.
// The Submessage execution may include an success/failure response handling by the contract that can overwrite the
// original
type DefaultWasmVMContractResponseHandler struct {
md msgDispatcher
}
func NewDefaultWasmVMContractResponseHandler(md msgDispatcher) *DefaultWasmVMContractResponseHandler {
return &DefaultWasmVMContractResponseHandler{md: md}
}
// Handle processes the data returned by a contract invocation.
func (h DefaultWasmVMContractResponseHandler) Handle(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, messages []wasmvmtypes.SubMsg, origRspData []byte) ([]byte, error) {
result := origRspData
switch rsp, err := h.md.DispatchSubmessages(ctx, contractAddr, ibcPort, messages); {
case err != nil:
return nil, errorsmod.Wrap(err, "submessages")
case rsp != nil:
result = rsp
}
return result, nil
}
package keeper
import (
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"runtime/debug"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
corestoretypes "cosmossdk.io/core/store"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/store/prefix"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
// DefaultGasCostBuildAddress is the SDK gas cost to build a contract address
const DefaultGasCostBuildAddress = 10
var _ types.QueryServer = &GrpcQuerier{}
type GrpcQuerier struct {
cdc codec.Codec
storeService corestoretypes.KVStoreService
keeper types.ViewKeeper
queryGasLimit storetypes.Gas
}
// NewGrpcQuerier constructor
func NewGrpcQuerier(cdc codec.Codec, storeService corestoretypes.KVStoreService, keeper types.ViewKeeper, queryGasLimit storetypes.Gas) *GrpcQuerier {
return &GrpcQuerier{cdc: cdc, storeService: storeService, keeper: keeper, queryGasLimit: queryGasLimit}
}
func (q GrpcQuerier) ContractInfo(c context.Context, req *types.QueryContractInfoRequest) (*types.QueryContractInfoResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
contractAddr, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, err
}
rsp, err := queryContractInfo(sdk.UnwrapSDKContext(c), contractAddr, q.keeper)
switch {
case err != nil:
return nil, err
case rsp == nil:
return nil, types.ErrNoSuchContractFn(contractAddr.String()).
Wrapf("address %s", contractAddr.String())
}
return rsp, nil
}
func (q GrpcQuerier) ContractHistory(c context.Context, req *types.QueryContractHistoryRequest) (*types.QueryContractHistoryResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
contractAddr, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, err
}
paginationParams, err := ensurePaginationParams(req.Pagination)
if err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
r := make([]types.ContractCodeHistoryEntry, 0)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), types.GetContractCodeHistoryElementPrefix(contractAddr))
pageRes, err := query.FilteredPaginate(prefixStore, paginationParams, func(key, value []byte, accumulate bool) (bool, error) {
if accumulate {
var e types.ContractCodeHistoryEntry
if err := q.cdc.Unmarshal(value, &e); err != nil {
return false, err
}
r = append(r, e)
}
return true, nil
})
if err != nil {
return nil, err
}
return &types.QueryContractHistoryResponse{
Entries: r,
Pagination: pageRes,
}, nil
}
// ContractsByCode lists all smart contracts for a code id
func (q GrpcQuerier) ContractsByCode(c context.Context, req *types.QueryContractsByCodeRequest) (*types.QueryContractsByCodeResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if req.CodeId == 0 {
return nil, errorsmod.Wrap(types.ErrInvalid, "code id")
}
paginationParams, err := ensurePaginationParams(req.Pagination)
if err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
r := make([]string, 0)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), types.GetContractByCodeIDSecondaryIndexPrefix(req.CodeId))
pageRes, err := query.FilteredPaginate(prefixStore, paginationParams, func(key, value []byte, accumulate bool) (bool, error) {
if accumulate {
var contractAddr sdk.AccAddress = key[types.AbsoluteTxPositionLen:]
r = append(r, contractAddr.String())
}
return true, nil
})
if err != nil {
return nil, err
}
return &types.QueryContractsByCodeResponse{
Contracts: r,
Pagination: pageRes,
}, nil
}
func (q GrpcQuerier) AllContractState(c context.Context, req *types.QueryAllContractStateRequest) (*types.QueryAllContractStateResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
contractAddr, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, err
}
paginationParams, err := ensurePaginationParams(req.Pagination)
if err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
if !q.keeper.HasContractInfo(ctx, contractAddr) {
return nil, types.ErrNoSuchContractFn(contractAddr.String()).
Wrapf("address %s", contractAddr.String())
}
r := make([]types.Model, 0)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), types.GetContractStorePrefix(contractAddr))
pageRes, err := query.FilteredPaginate(prefixStore, paginationParams, func(key, value []byte, accumulate bool) (bool, error) {
if accumulate {
r = append(r, types.Model{
Key: key,
Value: value,
})
}
return true, nil
})
if err != nil {
return nil, err
}
return &types.QueryAllContractStateResponse{
Models: r,
Pagination: pageRes,
}, nil
}
func (q GrpcQuerier) RawContractState(c context.Context, req *types.QueryRawContractStateRequest) (*types.QueryRawContractStateResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
contractAddr, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, err
}
if !q.keeper.HasContractInfo(ctx, contractAddr) {
return nil, types.ErrNoSuchContractFn(contractAddr.String()).
Wrapf("address %s", contractAddr.String())
}
rsp := q.keeper.QueryRaw(ctx, contractAddr, req.QueryData)
return &types.QueryRawContractStateResponse{Data: rsp}, nil
}
func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmartContractStateRequest) (rsp *types.QuerySmartContractStateResponse, err error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := req.QueryData.ValidateBasic(); err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid query data")
}
contractAddr, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c).WithGasMeter(storetypes.NewGasMeter(q.queryGasLimit))
// recover from out-of-gas panic
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
case storetypes.ErrorOutOfGas:
err = errorsmod.Wrapf(sdkerrors.ErrOutOfGas,
"out of gas in location: %v; gasWanted: %d, gasUsed: %d",
rType.Descriptor, ctx.GasMeter().Limit(), ctx.GasMeter().GasConsumed(),
)
default:
err = sdkerrors.ErrPanic
}
rsp = nil
moduleLogger(ctx).
Debug("smart query contract",
"error", "recovering panic",
"contract-address", req.Address,
"stacktrace", string(debug.Stack()))
}
}()
bz, err := q.keeper.QuerySmart(ctx, contractAddr, req.QueryData)
switch {
case err != nil:
return nil, err
case bz == nil:
return nil, types.ErrNoSuchContractFn(contractAddr.String()).
Wrapf("address %s", contractAddr.String())
}
return &types.QuerySmartContractStateResponse{Data: bz}, nil
}
func (q GrpcQuerier) Code(c context.Context, req *types.QueryCodeRequest) (*types.QueryCodeResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if req.CodeId == 0 {
return nil, errorsmod.Wrap(types.ErrInvalid, "code id")
}
rsp, err := queryCode(sdk.UnwrapSDKContext(c), req.CodeId, q.keeper)
switch {
case err != nil:
return nil, err
case rsp == nil:
return nil, types.ErrNoSuchCodeFn(req.CodeId).Wrapf("code id %d", req.CodeId)
}
return &types.QueryCodeResponse{
CodeInfoResponse: rsp.CodeInfoResponse,
Data: rsp.Data,
}, nil
}
func (q GrpcQuerier) Codes(c context.Context, req *types.QueryCodesRequest) (*types.QueryCodesResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
paginationParams, err := ensurePaginationParams(req.Pagination)
if err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
r := make([]types.CodeInfoResponse, 0)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), types.CodeKeyPrefix)
pageRes, err := query.FilteredPaginate(prefixStore, paginationParams, func(key, value []byte, accumulate bool) (bool, error) {
if accumulate {
var c types.CodeInfo
if err := q.cdc.Unmarshal(value, &c); err != nil {
return false, err
}
r = append(r, types.CodeInfoResponse{
CodeID: binary.BigEndian.Uint64(key),
Creator: c.Creator,
DataHash: c.CodeHash,
InstantiatePermission: c.InstantiateConfig,
})
}
return true, nil
})
if err != nil {
return nil, err
}
return &types.QueryCodesResponse{CodeInfos: r, Pagination: pageRes}, nil
}
func queryContractInfo(ctx sdk.Context, addr sdk.AccAddress, keeper types.ViewKeeper) (*types.QueryContractInfoResponse, error) {
info := keeper.GetContractInfo(ctx, addr)
if info == nil {
return nil, types.ErrNoSuchContractFn(addr.String()).
Wrapf("address %s", addr.String())
}
return &types.QueryContractInfoResponse{
Address: addr.String(),
ContractInfo: *info,
}, nil
}
func queryCode(ctx sdk.Context, codeID uint64, keeper types.ViewKeeper) (*types.QueryCodeResponse, error) {
if codeID == 0 {
return nil, nil
}
res := keeper.GetCodeInfo(ctx, codeID)
if res == nil {
// nil, nil leads to 404 in rest handler
return nil, nil
}
info := types.CodeInfoResponse{
CodeID: codeID,
Creator: res.Creator,
DataHash: res.CodeHash,
InstantiatePermission: res.InstantiateConfig,
}
code, err := keeper.GetByteCode(ctx, codeID)
if err != nil {
return nil, errorsmod.Wrap(err, "loading wasm code")
}
return &types.QueryCodeResponse{CodeInfoResponse: &info, Data: code}, nil
}
func (q GrpcQuerier) PinnedCodes(c context.Context, req *types.QueryPinnedCodesRequest) (*types.QueryPinnedCodesResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
paginationParams, err := ensurePaginationParams(req.Pagination)
if err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
r := make([]uint64, 0)
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), types.PinnedCodeIndexPrefix)
pageRes, err := query.FilteredPaginate(prefixStore, paginationParams, func(key, _ []byte, accumulate bool) (bool, error) {
if accumulate {
r = append(r, sdk.BigEndianToUint64(key))
}
return true, nil
})
if err != nil {
return nil, err
}
return &types.QueryPinnedCodesResponse{
CodeIDs: r,
Pagination: pageRes,
}, nil
}
// Params returns params of the module.
func (q GrpcQuerier) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
params := q.keeper.GetParams(ctx)
return &types.QueryParamsResponse{Params: params}, nil
}
func (q GrpcQuerier) ContractsByCreator(c context.Context, req *types.QueryContractsByCreatorRequest) (*types.QueryContractsByCreatorResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
paginationParams, err := ensurePaginationParams(req.Pagination)
if err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
contracts := make([]string, 0)
creatorAddress, err := sdk.AccAddressFromBech32(req.CreatorAddress)
if err != nil {
return nil, err
}
prefixStore := prefix.NewStore(runtime.KVStoreAdapter(q.storeService.OpenKVStore(ctx)), types.GetContractsByCreatorPrefix(creatorAddress))
pageRes, err := query.FilteredPaginate(prefixStore, paginationParams, func(key, _ []byte, accumulate bool) (bool, error) {
if accumulate {
accAddres := sdk.AccAddress(key[types.AbsoluteTxPositionLen:])
contracts = append(contracts, accAddres.String())
}
return true, nil
})
if err != nil {
return nil, err
}
return &types.QueryContractsByCreatorResponse{
ContractAddresses: contracts,
Pagination: pageRes,
}, nil
}
// max limit to pagination queries
const maxResultEntries = 100
var errLegacyPaginationUnsupported = status.Error(codes.InvalidArgument, "offset and count queries not supported")
// ensure that pagination is done via key iterator with reasonable limit
func ensurePaginationParams(req *query.PageRequest) (*query.PageRequest, error) {
if req == nil {
return &query.PageRequest{
Key: nil,
Limit: query.DefaultLimit,
}, nil
}
if req.Offset != 0 || req.CountTotal {
return nil, errLegacyPaginationUnsupported
}
if req.Limit > maxResultEntries || req.Limit <= 0 {
req.Limit = maxResultEntries
}
return req, nil
}
func (q GrpcQuerier) BuildAddress(c context.Context, req *types.QueryBuildAddressRequest) (*types.QueryBuildAddressResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
codeHash, err := hex.DecodeString(req.CodeHash)
if err != nil {
return nil, fmt.Errorf("invalid code hash: %w", err)
}
creator, err := sdk.AccAddressFromBech32(req.CreatorAddress)
if err != nil {
return nil, fmt.Errorf("invalid creator address: %w", err)
}
salt, err := hex.DecodeString(req.Salt)
if err != nil {
return nil, fmt.Errorf("invalid salt: %w", err)
}
if len(salt) == 0 {
return nil, status.Error(codes.InvalidArgument, "empty salt")
}
ctx := sdk.UnwrapSDKContext(c)
defer ctx.GasMeter().ConsumeGas(DefaultGasCostBuildAddress, "build address")
if req.InitArgs == nil {
return &types.QueryBuildAddressResponse{
Address: BuildContractAddressPredictable(codeHash, creator, salt, []byte{}).String(),
}, nil
}
initMsg := types.RawContractMessage(req.InitArgs)
if err := initMsg.ValidateBasic(); err != nil {
return nil, err
}
return &types.QueryBuildAddressResponse{
Address: BuildContractAddressPredictable(codeHash, creator, salt, initMsg).String(),
}, nil
}
package types
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// private type creates an interface key for Context that cannot be accessed by any other package
type contextKey int
const (
// position counter of the TX in the block
contextKeyTXCount contextKey = iota
// smart query stack counter to abort query loops
contextKeyQueryStackSize contextKey = iota
// authorization policy for sub-messages
contextKeySubMsgAuthzPolicy = iota
// gas register
contextKeyGasRegister = iota
contextKeyCallDepth contextKey = iota
)
// WithTXCounter stores a transaction counter value in the context
func WithTXCounter(ctx sdk.Context, counter uint32) sdk.Context {
return ctx.WithValue(contextKeyTXCount, counter)
}
// TXCounter returns the tx counter value and found bool from the context.
// The result will be (0, false) for external queries or simulations where no counter available.
func TXCounter(ctx context.Context) (uint32, bool) {
val, ok := ctx.Value(contextKeyTXCount).(uint32)
return val, ok
}
// WithQueryStackSize stores the stack position for smart queries in the context returned
func WithQueryStackSize(ctx sdk.Context, counter uint32) sdk.Context {
return ctx.WithValue(contextKeyQueryStackSize, counter)
}
// QueryStackSize reads the stack position for smart queries from the context
func QueryStackSize(ctx context.Context) (uint32, bool) {
val, ok := ctx.Value(contextKeyQueryStackSize).(uint32)
return val, ok
}
func WithCallDepth(ctx sdk.Context, counter uint32) sdk.Context {
return ctx.WithValue(contextKeyCallDepth, counter)
}
func CallDepth(ctx context.Context) (uint32, bool) {
val, ok := ctx.Value(contextKeyCallDepth).(uint32)
return val, ok
}
// WithSubMsgAuthzPolicy stores the authorization policy for submessages into the context returned
func WithSubMsgAuthzPolicy(ctx sdk.Context, policy AuthorizationPolicy) sdk.Context {
if policy == nil {
panic("policy must not be nil")
}
return ctx.WithValue(contextKeySubMsgAuthzPolicy, policy)
}
// SubMsgAuthzPolicy reads the authorization policy for submessages from the context
func SubMsgAuthzPolicy(ctx context.Context) (AuthorizationPolicy, bool) {
val, ok := ctx.Value(contextKeySubMsgAuthzPolicy).(AuthorizationPolicy)
return val, ok
}
// WithGasRegister stores the gas register into the context returned
func WithGasRegister(ctx sdk.Context, gr GasRegister) sdk.Context {
if gr == nil {
panic("gas register must not be nil")
}
return ctx.WithValue(contextKeyGasRegister, gr)
}
// GasRegisterFromContext reads the gas register from the context
func GasRegisterFromContext(ctx context.Context) (GasRegister, bool) {
val, ok := ctx.Value(contextKeyGasRegister).(GasRegister)
return val, ok
}
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmwasm/wasm/v1/query.proto
package types
import (
bytes "bytes"
context "context"
fmt "fmt"
github_com_cometbft_cometbft_libs_bytes "github.com/cometbft/cometbft/libs/bytes"
_ "github.com/cosmos/cosmos-proto"
query "github.com/cosmos/cosmos-sdk/types/query"
_ "github.com/cosmos/cosmos-sdk/types/tx/amino"
_ "github.com/cosmos/gogoproto/gogoproto"
grpc1 "github.com/cosmos/gogoproto/grpc"
proto "github.com/cosmos/gogoproto/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// QueryContractInfoRequest is the request type for the Query/ContractInfo RPC
// method
type QueryContractInfoRequest struct {
// address is the address of the contract to query
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
}
func (m *QueryContractInfoRequest) Reset() { *m = QueryContractInfoRequest{} }
func (m *QueryContractInfoRequest) String() string { return proto.CompactTextString(m) }
func (*QueryContractInfoRequest) ProtoMessage() {}
func (*QueryContractInfoRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{0}
}
func (m *QueryContractInfoRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryContractInfoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryContractInfoRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryContractInfoRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryContractInfoRequest.Merge(m, src)
}
func (m *QueryContractInfoRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryContractInfoRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryContractInfoRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryContractInfoRequest proto.InternalMessageInfo
// QueryContractInfoResponse is the response type for the Query/ContractInfo RPC
// method
type QueryContractInfoResponse struct {
// address is the address of the contract
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
ContractInfo `protobuf:"bytes,2,opt,name=contract_info,json=contractInfo,proto3,embedded=contract_info" json:""`
}
func (m *QueryContractInfoResponse) Reset() { *m = QueryContractInfoResponse{} }
func (m *QueryContractInfoResponse) String() string { return proto.CompactTextString(m) }
func (*QueryContractInfoResponse) ProtoMessage() {}
func (*QueryContractInfoResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{1}
}
func (m *QueryContractInfoResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryContractInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryContractInfoResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryContractInfoResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryContractInfoResponse.Merge(m, src)
}
func (m *QueryContractInfoResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryContractInfoResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryContractInfoResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryContractInfoResponse proto.InternalMessageInfo
// QueryContractHistoryRequest is the request type for the Query/ContractHistory
// RPC method
type QueryContractHistoryRequest struct {
// address is the address of the contract to query
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
// pagination defines an optional pagination for the request.
Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryContractHistoryRequest) Reset() { *m = QueryContractHistoryRequest{} }
func (m *QueryContractHistoryRequest) String() string { return proto.CompactTextString(m) }
func (*QueryContractHistoryRequest) ProtoMessage() {}
func (*QueryContractHistoryRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{2}
}
func (m *QueryContractHistoryRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryContractHistoryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryContractHistoryRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryContractHistoryRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryContractHistoryRequest.Merge(m, src)
}
func (m *QueryContractHistoryRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryContractHistoryRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryContractHistoryRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryContractHistoryRequest proto.InternalMessageInfo
// QueryContractHistoryResponse is the response type for the
// Query/ContractHistory RPC method
type QueryContractHistoryResponse struct {
Entries []ContractCodeHistoryEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries"`
// pagination defines the pagination in the response.
Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryContractHistoryResponse) Reset() { *m = QueryContractHistoryResponse{} }
func (m *QueryContractHistoryResponse) String() string { return proto.CompactTextString(m) }
func (*QueryContractHistoryResponse) ProtoMessage() {}
func (*QueryContractHistoryResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{3}
}
func (m *QueryContractHistoryResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryContractHistoryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryContractHistoryResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryContractHistoryResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryContractHistoryResponse.Merge(m, src)
}
func (m *QueryContractHistoryResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryContractHistoryResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryContractHistoryResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryContractHistoryResponse proto.InternalMessageInfo
// QueryContractsByCodeRequest is the request type for the Query/ContractsByCode
// RPC method
type QueryContractsByCodeRequest struct {
CodeId uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"`
// pagination defines an optional pagination for the request.
Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryContractsByCodeRequest) Reset() { *m = QueryContractsByCodeRequest{} }
func (m *QueryContractsByCodeRequest) String() string { return proto.CompactTextString(m) }
func (*QueryContractsByCodeRequest) ProtoMessage() {}
func (*QueryContractsByCodeRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{4}
}
func (m *QueryContractsByCodeRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryContractsByCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryContractsByCodeRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryContractsByCodeRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryContractsByCodeRequest.Merge(m, src)
}
func (m *QueryContractsByCodeRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryContractsByCodeRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryContractsByCodeRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryContractsByCodeRequest proto.InternalMessageInfo
// QueryContractsByCodeResponse is the response type for the
// Query/ContractsByCode RPC method
type QueryContractsByCodeResponse struct {
// contracts are a set of contract addresses
Contracts []string `protobuf:"bytes,1,rep,name=contracts,proto3" json:"contracts,omitempty"`
// pagination defines the pagination in the response.
Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryContractsByCodeResponse) Reset() { *m = QueryContractsByCodeResponse{} }
func (m *QueryContractsByCodeResponse) String() string { return proto.CompactTextString(m) }
func (*QueryContractsByCodeResponse) ProtoMessage() {}
func (*QueryContractsByCodeResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{5}
}
func (m *QueryContractsByCodeResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryContractsByCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryContractsByCodeResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryContractsByCodeResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryContractsByCodeResponse.Merge(m, src)
}
func (m *QueryContractsByCodeResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryContractsByCodeResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryContractsByCodeResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryContractsByCodeResponse proto.InternalMessageInfo
// QueryAllContractStateRequest is the request type for the
// Query/AllContractState RPC method
type QueryAllContractStateRequest struct {
// address is the address of the contract
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
// pagination defines an optional pagination for the request.
Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryAllContractStateRequest) Reset() { *m = QueryAllContractStateRequest{} }
func (m *QueryAllContractStateRequest) String() string { return proto.CompactTextString(m) }
func (*QueryAllContractStateRequest) ProtoMessage() {}
func (*QueryAllContractStateRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{6}
}
func (m *QueryAllContractStateRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAllContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAllContractStateRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAllContractStateRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAllContractStateRequest.Merge(m, src)
}
func (m *QueryAllContractStateRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryAllContractStateRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAllContractStateRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAllContractStateRequest proto.InternalMessageInfo
// QueryAllContractStateResponse is the response type for the
// Query/AllContractState RPC method
type QueryAllContractStateResponse struct {
Models []Model `protobuf:"bytes,1,rep,name=models,proto3" json:"models"`
// pagination defines the pagination in the response.
Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryAllContractStateResponse) Reset() { *m = QueryAllContractStateResponse{} }
func (m *QueryAllContractStateResponse) String() string { return proto.CompactTextString(m) }
func (*QueryAllContractStateResponse) ProtoMessage() {}
func (*QueryAllContractStateResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{7}
}
func (m *QueryAllContractStateResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAllContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAllContractStateResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAllContractStateResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAllContractStateResponse.Merge(m, src)
}
func (m *QueryAllContractStateResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryAllContractStateResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAllContractStateResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAllContractStateResponse proto.InternalMessageInfo
// QueryRawContractStateRequest is the request type for the
// Query/RawContractState RPC method
type QueryRawContractStateRequest struct {
// address is the address of the contract
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
QueryData []byte `protobuf:"bytes,2,opt,name=query_data,json=queryData,proto3" json:"query_data,omitempty"`
}
func (m *QueryRawContractStateRequest) Reset() { *m = QueryRawContractStateRequest{} }
func (m *QueryRawContractStateRequest) String() string { return proto.CompactTextString(m) }
func (*QueryRawContractStateRequest) ProtoMessage() {}
func (*QueryRawContractStateRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{8}
}
func (m *QueryRawContractStateRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryRawContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryRawContractStateRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryRawContractStateRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryRawContractStateRequest.Merge(m, src)
}
func (m *QueryRawContractStateRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryRawContractStateRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryRawContractStateRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryRawContractStateRequest proto.InternalMessageInfo
// QueryRawContractStateResponse is the response type for the
// Query/RawContractState RPC method
type QueryRawContractStateResponse struct {
// Data contains the raw store data
Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}
func (m *QueryRawContractStateResponse) Reset() { *m = QueryRawContractStateResponse{} }
func (m *QueryRawContractStateResponse) String() string { return proto.CompactTextString(m) }
func (*QueryRawContractStateResponse) ProtoMessage() {}
func (*QueryRawContractStateResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{9}
}
func (m *QueryRawContractStateResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryRawContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryRawContractStateResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryRawContractStateResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryRawContractStateResponse.Merge(m, src)
}
func (m *QueryRawContractStateResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryRawContractStateResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryRawContractStateResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryRawContractStateResponse proto.InternalMessageInfo
// QuerySmartContractStateRequest is the request type for the
// Query/SmartContractState RPC method
type QuerySmartContractStateRequest struct {
// address is the address of the contract
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
// QueryData contains the query data passed to the contract
QueryData RawContractMessage `protobuf:"bytes,2,opt,name=query_data,json=queryData,proto3,casttype=RawContractMessage" json:"query_data,omitempty"`
}
func (m *QuerySmartContractStateRequest) Reset() { *m = QuerySmartContractStateRequest{} }
func (m *QuerySmartContractStateRequest) String() string { return proto.CompactTextString(m) }
func (*QuerySmartContractStateRequest) ProtoMessage() {}
func (*QuerySmartContractStateRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{10}
}
func (m *QuerySmartContractStateRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QuerySmartContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QuerySmartContractStateRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QuerySmartContractStateRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QuerySmartContractStateRequest.Merge(m, src)
}
func (m *QuerySmartContractStateRequest) XXX_Size() int {
return m.Size()
}
func (m *QuerySmartContractStateRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QuerySmartContractStateRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QuerySmartContractStateRequest proto.InternalMessageInfo
// QuerySmartContractStateResponse is the response type for the
// Query/SmartContractState RPC method
type QuerySmartContractStateResponse struct {
// Data contains the json data returned from the smart contract
Data RawContractMessage `protobuf:"bytes,1,opt,name=data,proto3,casttype=RawContractMessage" json:"data,omitempty"`
}
func (m *QuerySmartContractStateResponse) Reset() { *m = QuerySmartContractStateResponse{} }
func (m *QuerySmartContractStateResponse) String() string { return proto.CompactTextString(m) }
func (*QuerySmartContractStateResponse) ProtoMessage() {}
func (*QuerySmartContractStateResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{11}
}
func (m *QuerySmartContractStateResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QuerySmartContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QuerySmartContractStateResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QuerySmartContractStateResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QuerySmartContractStateResponse.Merge(m, src)
}
func (m *QuerySmartContractStateResponse) XXX_Size() int {
return m.Size()
}
func (m *QuerySmartContractStateResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QuerySmartContractStateResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QuerySmartContractStateResponse proto.InternalMessageInfo
// QueryCodeRequest is the request type for the Query/Code RPC method
type QueryCodeRequest struct {
CodeId uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"`
}
func (m *QueryCodeRequest) Reset() { *m = QueryCodeRequest{} }
func (m *QueryCodeRequest) String() string { return proto.CompactTextString(m) }
func (*QueryCodeRequest) ProtoMessage() {}
func (*QueryCodeRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{12}
}
func (m *QueryCodeRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryCodeRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryCodeRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryCodeRequest.Merge(m, src)
}
func (m *QueryCodeRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryCodeRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryCodeRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryCodeRequest proto.InternalMessageInfo
// CodeInfoResponse contains code meta data from CodeInfo
type CodeInfoResponse struct {
CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"id"`
Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"`
DataHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,3,opt,name=data_hash,json=dataHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"data_hash,omitempty"`
InstantiatePermission AccessConfig `protobuf:"bytes,6,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission"`
}
func (m *CodeInfoResponse) Reset() { *m = CodeInfoResponse{} }
func (m *CodeInfoResponse) String() string { return proto.CompactTextString(m) }
func (*CodeInfoResponse) ProtoMessage() {}
func (*CodeInfoResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{13}
}
func (m *CodeInfoResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *CodeInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_CodeInfoResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *CodeInfoResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_CodeInfoResponse.Merge(m, src)
}
func (m *CodeInfoResponse) XXX_Size() int {
return m.Size()
}
func (m *CodeInfoResponse) XXX_DiscardUnknown() {
xxx_messageInfo_CodeInfoResponse.DiscardUnknown(m)
}
var xxx_messageInfo_CodeInfoResponse proto.InternalMessageInfo
// QueryCodeResponse is the response type for the Query/Code RPC method
type QueryCodeResponse struct {
*CodeInfoResponse `protobuf:"bytes,1,opt,name=code_info,json=codeInfo,proto3,embedded=code_info" json:""`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data"`
}
func (m *QueryCodeResponse) Reset() { *m = QueryCodeResponse{} }
func (m *QueryCodeResponse) String() string { return proto.CompactTextString(m) }
func (*QueryCodeResponse) ProtoMessage() {}
func (*QueryCodeResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{14}
}
func (m *QueryCodeResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryCodeResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryCodeResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryCodeResponse.Merge(m, src)
}
func (m *QueryCodeResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryCodeResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryCodeResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryCodeResponse proto.InternalMessageInfo
// QueryCodesRequest is the request type for the Query/Codes RPC method
type QueryCodesRequest struct {
// pagination defines an optional pagination for the request.
Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryCodesRequest) Reset() { *m = QueryCodesRequest{} }
func (m *QueryCodesRequest) String() string { return proto.CompactTextString(m) }
func (*QueryCodesRequest) ProtoMessage() {}
func (*QueryCodesRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{15}
}
func (m *QueryCodesRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryCodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryCodesRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryCodesRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryCodesRequest.Merge(m, src)
}
func (m *QueryCodesRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryCodesRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryCodesRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryCodesRequest proto.InternalMessageInfo
// QueryCodesResponse is the response type for the Query/Codes RPC method
type QueryCodesResponse struct {
CodeInfos []CodeInfoResponse `protobuf:"bytes,1,rep,name=code_infos,json=codeInfos,proto3" json:"code_infos"`
// pagination defines the pagination in the response.
Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryCodesResponse) Reset() { *m = QueryCodesResponse{} }
func (m *QueryCodesResponse) String() string { return proto.CompactTextString(m) }
func (*QueryCodesResponse) ProtoMessage() {}
func (*QueryCodesResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{16}
}
func (m *QueryCodesResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryCodesResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryCodesResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryCodesResponse.Merge(m, src)
}
func (m *QueryCodesResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryCodesResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryCodesResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryCodesResponse proto.InternalMessageInfo
// QueryPinnedCodesRequest is the request type for the Query/PinnedCodes
// RPC method
type QueryPinnedCodesRequest struct {
// pagination defines an optional pagination for the request.
Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryPinnedCodesRequest) Reset() { *m = QueryPinnedCodesRequest{} }
func (m *QueryPinnedCodesRequest) String() string { return proto.CompactTextString(m) }
func (*QueryPinnedCodesRequest) ProtoMessage() {}
func (*QueryPinnedCodesRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{17}
}
func (m *QueryPinnedCodesRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryPinnedCodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryPinnedCodesRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryPinnedCodesRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryPinnedCodesRequest.Merge(m, src)
}
func (m *QueryPinnedCodesRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryPinnedCodesRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryPinnedCodesRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryPinnedCodesRequest proto.InternalMessageInfo
// QueryPinnedCodesResponse is the response type for the
// Query/PinnedCodes RPC method
type QueryPinnedCodesResponse struct {
CodeIDs []uint64 `protobuf:"varint,1,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty"`
// pagination defines the pagination in the response.
Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryPinnedCodesResponse) Reset() { *m = QueryPinnedCodesResponse{} }
func (m *QueryPinnedCodesResponse) String() string { return proto.CompactTextString(m) }
func (*QueryPinnedCodesResponse) ProtoMessage() {}
func (*QueryPinnedCodesResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{18}
}
func (m *QueryPinnedCodesResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryPinnedCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryPinnedCodesResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryPinnedCodesResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryPinnedCodesResponse.Merge(m, src)
}
func (m *QueryPinnedCodesResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryPinnedCodesResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryPinnedCodesResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryPinnedCodesResponse proto.InternalMessageInfo
// QueryParamsRequest is the request type for the Query/Params RPC method.
type QueryParamsRequest struct {
}
func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} }
func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) }
func (*QueryParamsRequest) ProtoMessage() {}
func (*QueryParamsRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{19}
}
func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryParamsRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryParamsRequest.Merge(m, src)
}
func (m *QueryParamsRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryParamsRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo
// QueryParamsResponse is the response type for the Query/Params RPC method.
type QueryParamsResponse struct {
// params defines the parameters of the module.
Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"`
}
func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} }
func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) }
func (*QueryParamsResponse) ProtoMessage() {}
func (*QueryParamsResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{20}
}
func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryParamsResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryParamsResponse.Merge(m, src)
}
func (m *QueryParamsResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryParamsResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo
// QueryContractsByCreatorRequest is the request type for the
// Query/ContractsByCreator RPC method.
type QueryContractsByCreatorRequest struct {
// CreatorAddress is the address of contract creator
CreatorAddress string `protobuf:"bytes,1,opt,name=creator_address,json=creatorAddress,proto3" json:"creator_address,omitempty"`
// Pagination defines an optional pagination for the request.
Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryContractsByCreatorRequest) Reset() { *m = QueryContractsByCreatorRequest{} }
func (m *QueryContractsByCreatorRequest) String() string { return proto.CompactTextString(m) }
func (*QueryContractsByCreatorRequest) ProtoMessage() {}
func (*QueryContractsByCreatorRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{21}
}
func (m *QueryContractsByCreatorRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryContractsByCreatorRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryContractsByCreatorRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryContractsByCreatorRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryContractsByCreatorRequest.Merge(m, src)
}
func (m *QueryContractsByCreatorRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryContractsByCreatorRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryContractsByCreatorRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryContractsByCreatorRequest proto.InternalMessageInfo
// QueryContractsByCreatorResponse is the response type for the
// Query/ContractsByCreator RPC method.
type QueryContractsByCreatorResponse struct {
// ContractAddresses result set
ContractAddresses []string `protobuf:"bytes,1,rep,name=contract_addresses,json=contractAddresses,proto3" json:"contract_addresses,omitempty"`
// Pagination defines the pagination in the response.
Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryContractsByCreatorResponse) Reset() { *m = QueryContractsByCreatorResponse{} }
func (m *QueryContractsByCreatorResponse) String() string { return proto.CompactTextString(m) }
func (*QueryContractsByCreatorResponse) ProtoMessage() {}
func (*QueryContractsByCreatorResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{22}
}
func (m *QueryContractsByCreatorResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryContractsByCreatorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryContractsByCreatorResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryContractsByCreatorResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryContractsByCreatorResponse.Merge(m, src)
}
func (m *QueryContractsByCreatorResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryContractsByCreatorResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryContractsByCreatorResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryContractsByCreatorResponse proto.InternalMessageInfo
// QueryBuildAddressRequest is the request type for the Query/BuildAddress RPC
// method.
type QueryBuildAddressRequest struct {
// CodeHash is the hash of the code
CodeHash string `protobuf:"bytes,1,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"`
// CreatorAddress is the address of the contract instantiator
CreatorAddress string `protobuf:"bytes,2,opt,name=creator_address,json=creatorAddress,proto3" json:"creator_address,omitempty"`
// Salt is a hex encoded salt
Salt string `protobuf:"bytes,3,opt,name=salt,proto3" json:"salt,omitempty"`
// InitArgs are optional json encoded init args to be used in contract address
// building if provided
InitArgs []byte `protobuf:"bytes,4,opt,name=init_args,json=initArgs,proto3" json:"init_args,omitempty"`
}
func (m *QueryBuildAddressRequest) Reset() { *m = QueryBuildAddressRequest{} }
func (m *QueryBuildAddressRequest) String() string { return proto.CompactTextString(m) }
func (*QueryBuildAddressRequest) ProtoMessage() {}
func (*QueryBuildAddressRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{23}
}
func (m *QueryBuildAddressRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryBuildAddressRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryBuildAddressRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryBuildAddressRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryBuildAddressRequest.Merge(m, src)
}
func (m *QueryBuildAddressRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryBuildAddressRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryBuildAddressRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryBuildAddressRequest proto.InternalMessageInfo
// QueryBuildAddressResponse is the response type for the Query/BuildAddress RPC
// method.
type QueryBuildAddressResponse struct {
// Address is the contract address
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
}
func (m *QueryBuildAddressResponse) Reset() { *m = QueryBuildAddressResponse{} }
func (m *QueryBuildAddressResponse) String() string { return proto.CompactTextString(m) }
func (*QueryBuildAddressResponse) ProtoMessage() {}
func (*QueryBuildAddressResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_9677c207036b9f2b, []int{24}
}
func (m *QueryBuildAddressResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryBuildAddressResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryBuildAddressResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryBuildAddressResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryBuildAddressResponse.Merge(m, src)
}
func (m *QueryBuildAddressResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryBuildAddressResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryBuildAddressResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryBuildAddressResponse proto.InternalMessageInfo
func init() {
proto.RegisterType((*QueryContractInfoRequest)(nil), "cosmwasm.wasm.v1.QueryContractInfoRequest")
proto.RegisterType((*QueryContractInfoResponse)(nil), "cosmwasm.wasm.v1.QueryContractInfoResponse")
proto.RegisterType((*QueryContractHistoryRequest)(nil), "cosmwasm.wasm.v1.QueryContractHistoryRequest")
proto.RegisterType((*QueryContractHistoryResponse)(nil), "cosmwasm.wasm.v1.QueryContractHistoryResponse")
proto.RegisterType((*QueryContractsByCodeRequest)(nil), "cosmwasm.wasm.v1.QueryContractsByCodeRequest")
proto.RegisterType((*QueryContractsByCodeResponse)(nil), "cosmwasm.wasm.v1.QueryContractsByCodeResponse")
proto.RegisterType((*QueryAllContractStateRequest)(nil), "cosmwasm.wasm.v1.QueryAllContractStateRequest")
proto.RegisterType((*QueryAllContractStateResponse)(nil), "cosmwasm.wasm.v1.QueryAllContractStateResponse")
proto.RegisterType((*QueryRawContractStateRequest)(nil), "cosmwasm.wasm.v1.QueryRawContractStateRequest")
proto.RegisterType((*QueryRawContractStateResponse)(nil), "cosmwasm.wasm.v1.QueryRawContractStateResponse")
proto.RegisterType((*QuerySmartContractStateRequest)(nil), "cosmwasm.wasm.v1.QuerySmartContractStateRequest")
proto.RegisterType((*QuerySmartContractStateResponse)(nil), "cosmwasm.wasm.v1.QuerySmartContractStateResponse")
proto.RegisterType((*QueryCodeRequest)(nil), "cosmwasm.wasm.v1.QueryCodeRequest")
proto.RegisterType((*CodeInfoResponse)(nil), "cosmwasm.wasm.v1.CodeInfoResponse")
proto.RegisterType((*QueryCodeResponse)(nil), "cosmwasm.wasm.v1.QueryCodeResponse")
proto.RegisterType((*QueryCodesRequest)(nil), "cosmwasm.wasm.v1.QueryCodesRequest")
proto.RegisterType((*QueryCodesResponse)(nil), "cosmwasm.wasm.v1.QueryCodesResponse")
proto.RegisterType((*QueryPinnedCodesRequest)(nil), "cosmwasm.wasm.v1.QueryPinnedCodesRequest")
proto.RegisterType((*QueryPinnedCodesResponse)(nil), "cosmwasm.wasm.v1.QueryPinnedCodesResponse")
proto.RegisterType((*QueryParamsRequest)(nil), "cosmwasm.wasm.v1.QueryParamsRequest")
proto.RegisterType((*QueryParamsResponse)(nil), "cosmwasm.wasm.v1.QueryParamsResponse")
proto.RegisterType((*QueryContractsByCreatorRequest)(nil), "cosmwasm.wasm.v1.QueryContractsByCreatorRequest")
proto.RegisterType((*QueryContractsByCreatorResponse)(nil), "cosmwasm.wasm.v1.QueryContractsByCreatorResponse")
proto.RegisterType((*QueryBuildAddressRequest)(nil), "cosmwasm.wasm.v1.QueryBuildAddressRequest")
proto.RegisterType((*QueryBuildAddressResponse)(nil), "cosmwasm.wasm.v1.QueryBuildAddressResponse")
}
func init() { proto.RegisterFile("cosmwasm/wasm/v1/query.proto", fileDescriptor_9677c207036b9f2b) }
var fileDescriptor_9677c207036b9f2b = []byte{
// 1508 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x98, 0xcf, 0x6f, 0x1b, 0x45,
0x14, 0xc7, 0x3d, 0xa9, 0xe3, 0xd8, 0x93, 0x40, 0x9d, 0xa1, 0xb4, 0xae, 0xdb, 0xda, 0xd1, 0xb6,
0x84, 0xd4, 0x6d, 0xbd, 0x4d, 0x4a, 0xa9, 0x5a, 0x0e, 0xc8, 0x4e, 0x4b, 0xd3, 0x8a, 0xd2, 0xd4,
0x95, 0x40, 0x02, 0x21, 0x33, 0xb6, 0x27, 0xce, 0x22, 0x7b, 0xd7, 0xdd, 0x99, 0x34, 0x8d, 0xa2,
0xf4, 0xd0, 0x13, 0x12, 0x17, 0x10, 0x07, 0x44, 0x91, 0x80, 0x03, 0x87, 0xa2, 0x82, 0x54, 0x09,
0x24, 0x2a, 0x24, 0xee, 0x39, 0x56, 0x70, 0xe1, 0x64, 0x41, 0x8a, 0x54, 0xd4, 0x3f, 0xa1, 0x27,
0xb4, 0xf3, 0xc3, 0xbb, 0x6b, 0x7b, 0x6d, 0x27, 0xf8, 0xc0, 0x25, 0x5a, 0xef, 0xbe, 0x37, 0xf3,
0x99, 0xef, 0xbc, 0x79, 0xef, 0x4d, 0xe0, 0xc1, 0xb2, 0x45, 0xeb, 0xab, 0x98, 0xd6, 0x75, 0xfe,
0xe7, 0xe6, 0xac, 0x7e, 0x63, 0x85, 0xd8, 0x6b, 0xd9, 0x86, 0x6d, 0x31, 0x0b, 0xc5, 0xd5, 0xd7,
0x2c, 0xff, 0x73, 0x73, 0x36, 0xb9, 0xa7, 0x6a, 0x55, 0x2d, 0xfe, 0x51, 0x77, 0x9e, 0x84, 0x5d,
0xb2, 0x73, 0x14, 0xb6, 0xd6, 0x20, 0x54, 0x7d, 0xad, 0x5a, 0x56, 0xb5, 0x46, 0x74, 0xdc, 0x30,
0x74, 0x6c, 0x9a, 0x16, 0xc3, 0xcc, 0xb0, 0x4c, 0xf5, 0x35, 0xe3, 0xf8, 0x5a, 0x54, 0x2f, 0x61,
0x4a, 0xc4, 0xe4, 0xfa, 0xcd, 0xd9, 0x12, 0x61, 0x78, 0x56, 0x6f, 0xe0, 0xaa, 0x61, 0x72, 0x63,
0x69, 0x7b, 0x40, 0xda, 0x2a, 0x33, 0x2f, 0x6c, 0x72, 0x12, 0xd7, 0x0d, 0xd3, 0xd2, 0xf9, 0x5f,
0xf9, 0x6a, 0xbf, 0xb0, 0x2f, 0x0a, 0x60, 0xf1, 0x43, 0x7c, 0xd2, 0xde, 0x82, 0x89, 0x6b, 0x8e,
0xf3, 0xbc, 0x65, 0x32, 0x1b, 0x97, 0xd9, 0x25, 0x73, 0xc9, 0x2a, 0x90, 0x1b, 0x2b, 0x84, 0x32,
0x34, 0x07, 0xc7, 0x70, 0xa5, 0x62, 0x13, 0x4a, 0x13, 0x60, 0x0a, 0xcc, 0xc4, 0xf2, 0x89, 0xdf,
0x7e, 0x3a, 0xb1, 0x47, 0xba, 0xe7, 0xc4, 0x97, 0xeb, 0xcc, 0x36, 0xcc, 0x6a, 0x41, 0x19, 0x6a,
0x3f, 0x00, 0xb8, 0xbf, 0xcb, 0x80, 0xb4, 0x61, 0x99, 0x94, 0xec, 0x64, 0x44, 0xf4, 0x36, 0x7c,
0xae, 0x2c, 0xc7, 0x2a, 0x1a, 0xe6, 0x92, 0x95, 0x18, 0x99, 0x02, 0x33, 0xe3, 0x73, 0xa9, 0x6c,
0xfb, 0xa6, 0x64, 0xbd, 0x53, 0xe6, 0x27, 0x37, 0x9b, 0xe9, 0xd0, 0xa3, 0x66, 0x1a, 0x3c, 0x6d,
0xa6, 0x43, 0xf7, 0x9e, 0x3c, 0xc8, 0x80, 0xc2, 0x44, 0xd9, 0x63, 0x70, 0x2e, 0xfc, 0xcf, 0x37,
0x69, 0xa0, 0x7d, 0x01, 0xe0, 0x01, 0x1f, 0xef, 0x82, 0x41, 0x99, 0x65, 0xaf, 0xfd, 0x07, 0x0d,
0xd0, 0x1b, 0x10, 0xba, 0x5b, 0x26, 0x71, 0xa7, 0xb3, 0xd2, 0xc7, 0xd9, 0xdf, 0xac, 0xd8, 0x2f,
0xb9, 0xbf, 0xd9, 0x45, 0x5c, 0x25, 0x72, 0xbe, 0x82, 0xc7, 0x53, 0x7b, 0x08, 0xe0, 0xc1, 0xee,
0x6c, 0x52, 0xce, 0xab, 0x70, 0x8c, 0x98, 0xcc, 0x36, 0x88, 0x03, 0xb7, 0x6b, 0x66, 0x7c, 0x2e,
0x13, 0x2c, 0xca, 0xbc, 0x55, 0x21, 0xd2, 0xff, 0x82, 0xc9, 0xec, 0xb5, 0x7c, 0x6c, 0xb3, 0x25,
0x8c, 0x1a, 0x05, 0x5d, 0xec, 0x42, 0xfe, 0x72, 0x5f, 0x72, 0x41, 0xe3, 0x43, 0xbf, 0xdd, 0xa6,
0x2a, 0xcd, 0xaf, 0x39, 0x00, 0x4a, 0xd5, 0x7d, 0x70, 0xac, 0x6c, 0x55, 0x48, 0xd1, 0xa8, 0x70,
0x55, 0xc3, 0x85, 0x88, 0xf3, 0xf3, 0x52, 0x65, 0x68, 0xd2, 0x7d, 0xdd, 0x2e, 0x5d, 0x0b, 0x40,
0x4a, 0xf7, 0x2a, 0x8c, 0xa9, 0x68, 0x10, 0xe2, 0xf5, 0xda, 0x59, 0xd7, 0x74, 0x78, 0x0a, 0xdd,
0x55, 0x84, 0xb9, 0x5a, 0x4d, 0x41, 0x5e, 0x67, 0x98, 0x91, 0xff, 0x43, 0xe4, 0x7d, 0x0b, 0xe0,
0xa1, 0x00, 0x38, 0xa9, 0xdf, 0x39, 0x18, 0xa9, 0x5b, 0x15, 0x52, 0x53, 0x91, 0xb7, 0xaf, 0x33,
0xf2, 0xae, 0x38, 0xdf, 0xbd, 0x61, 0x26, 0x3d, 0x86, 0xa7, 0xe1, 0x0d, 0x29, 0x61, 0x01, 0xaf,
0x0e, 0x4d, 0xc2, 0x43, 0x10, 0xf2, 0xd9, 0x8b, 0x15, 0xcc, 0x30, 0x87, 0x9b, 0x28, 0xc4, 0xf8,
0x9b, 0xf3, 0x98, 0x61, 0xed, 0x94, 0x14, 0xa6, 0x73, 0x4a, 0x29, 0x0c, 0x82, 0x61, 0xee, 0x09,
0xb8, 0x27, 0x7f, 0xd6, 0xbe, 0x04, 0x30, 0xc5, 0xbd, 0xae, 0xd7, 0xb1, 0xcd, 0x86, 0x86, 0x7a,
0xa1, 0x13, 0x35, 0x3f, 0xfd, 0xac, 0x99, 0x46, 0x1e, 0xb8, 0x2b, 0x84, 0x52, 0x5c, 0x25, 0x77,
0x9f, 0x3c, 0xc8, 0x8c, 0x1b, 0x66, 0xcd, 0x30, 0x49, 0xf1, 0x43, 0x6a, 0x99, 0xde, 0x25, 0xbd,
0x0f, 0xd3, 0x81, 0x70, 0xad, 0xdd, 0xf6, 0x2c, 0x6a, 0xe0, 0x39, 0xc4, 0xe2, 0x8f, 0xc1, 0xb8,
0x3c, 0x89, 0xfd, 0xcf, 0xbf, 0xf6, 0x70, 0x04, 0xc6, 0x1d, 0x43, 0x5f, 0xd5, 0x38, 0xda, 0x66,
0x9d, 0x8f, 0x6f, 0x35, 0xd3, 0x11, 0x6e, 0x76, 0xfe, 0x69, 0x33, 0x3d, 0x62, 0x54, 0x5a, 0xf9,
0x63, 0x0e, 0x8e, 0x95, 0x6d, 0x82, 0x99, 0x65, 0x73, 0x3d, 0x7a, 0xca, 0x28, 0x0d, 0xd1, 0x35,
0x18, 0x73, 0x40, 0x8b, 0xcb, 0x98, 0x2e, 0x27, 0x76, 0xf1, 0x15, 0xbe, 0xf2, 0xac, 0x99, 0x3e,
0x59, 0x35, 0xd8, 0xf2, 0x4a, 0x29, 0x5b, 0xb6, 0xea, 0x7a, 0xd9, 0xaa, 0x13, 0x56, 0x5a, 0x62,
0xee, 0x43, 0xcd, 0x28, 0x51, 0xbd, 0xb4, 0xc6, 0x08, 0xcd, 0x2e, 0x90, 0x5b, 0x79, 0xe7, 0xa1,
0x10, 0x75, 0x86, 0x59, 0xc0, 0x74, 0x19, 0x7d, 0x00, 0xf7, 0x1a, 0x26, 0x65, 0xd8, 0x64, 0x06,
0x66, 0xa4, 0xd8, 0x20, 0x76, 0xdd, 0xa0, 0xd4, 0x89, 0xf6, 0x48, 0x50, 0xf1, 0xca, 0x95, 0xcb,
0x84, 0xd2, 0x79, 0xcb, 0x5c, 0x32, 0xaa, 0xde, 0x43, 0xf3, 0xa2, 0x67, 0xa0, 0xc5, 0xd6, 0x38,
0xa2, 0x7a, 0x5d, 0x0e, 0x47, 0xc3, 0xf1, 0xd1, 0xcb, 0xe1, 0xe8, 0x68, 0x3c, 0xa2, 0xdd, 0x01,
0x70, 0xd2, 0x23, 0xb4, 0xd4, 0xee, 0x92, 0x93, 0xe7, 0x1c, 0xed, 0x9c, 0xca, 0x09, 0xf8, 0xe4,
0x5a, 0xb7, 0x22, 0xe1, 0x97, 0x3c, 0x1f, 0x55, 0x95, 0xb3, 0x10, 0x2d, 0xcb, 0x6f, 0xe8, 0xa0,
0x0c, 0x02, 0x11, 0x68, 0xd1, 0xa7, 0xcd, 0x34, 0xff, 0x2d, 0xb6, 0x59, 0x96, 0xd3, 0xf7, 0x3c,
0x0c, 0x54, 0xed, 0xb6, 0x3f, 0x2b, 0x81, 0x1d, 0x67, 0xa5, 0xfb, 0x00, 0x22, 0xef, 0xe8, 0x72,
0x89, 0x6f, 0x42, 0xd8, 0x5a, 0xa2, 0x4a, 0x47, 0x83, 0xac, 0xd1, 0x23, 0x72, 0x4c, 0x2d, 0x72,
0x88, 0xc9, 0x09, 0xc3, 0x7d, 0x1c, 0x76, 0xd1, 0x30, 0x4d, 0x52, 0xe9, 0x21, 0xc8, 0xce, 0xd3,
0xf4, 0xc7, 0x40, 0x76, 0x6f, 0xbe, 0x39, 0xa4, 0x2c, 0xd3, 0x30, 0x2a, 0x4f, 0x8d, 0x10, 0x25,
0x9c, 0x1f, 0xdf, 0x6a, 0xa6, 0xc7, 0xc4, 0xb1, 0xa1, 0x85, 0x31, 0x71, 0x62, 0x86, 0xb8, 0xe0,
0x3d, 0x72, 0x77, 0x16, 0xb1, 0x8d, 0xeb, 0x6a, 0xad, 0x5a, 0x01, 0xbe, 0xe0, 0x7b, 0x2b, 0xe9,
0x5e, 0x83, 0x91, 0x06, 0x7f, 0x23, 0xe3, 0x21, 0xd1, 0xb9, 0x61, 0xc2, 0xc3, 0x57, 0x40, 0x84,
0x8b, 0x13, 0x08, 0xa9, 0x8e, 0xea, 0x2e, 0x4e, 0xb3, 0x92, 0x38, 0x07, 0x77, 0xcb, 0xf3, 0x5d,
0x1c, 0x34, 0xaf, 0x3e, 0x2f, 0x1d, 0x72, 0x43, 0x2e, 0xa6, 0x3f, 0x02, 0x99, 0x60, 0xbb, 0xd1,
0x4a, 0x39, 0x2e, 0x42, 0xd4, 0x6a, 0x72, 0x25, 0x2f, 0xe9, 0xdf, 0x97, 0x4c, 0x2a, 0x9f, 0x9c,
0x72, 0x19, 0xde, 0x6e, 0xde, 0x57, 0xb1, 0x95, 0x5f, 0x31, 0x6a, 0x15, 0x39, 0x81, 0x52, 0xf7,
0x80, 0xcc, 0x2a, 0x3c, 0x65, 0x72, 0x5d, 0x45, 0x9e, 0xe0, 0xc9, 0xaf, 0x8b, 0xf4, 0x23, 0xdb,
0x94, 0x1e, 0xc1, 0x30, 0xc5, 0x35, 0xc6, 0xb3, 0x71, 0xac, 0xc0, 0x9f, 0x9d, 0x39, 0x0d, 0xd3,
0x60, 0x45, 0x6c, 0x57, 0x69, 0x22, 0xcc, 0xab, 0x6b, 0xd4, 0x79, 0x91, 0xb3, 0xab, 0x54, 0xbb,
0x2a, 0x6f, 0x1d, 0x7e, 0xd8, 0x9d, 0xdf, 0x3a, 0xe6, 0x3e, 0xdf, 0x0d, 0x47, 0xf9, 0x88, 0xe8,
0x2e, 0x80, 0x13, 0xde, 0x9b, 0x05, 0xea, 0xd2, 0x64, 0x07, 0x5d, 0xa1, 0x92, 0xc7, 0x06, 0xb2,
0x15, 0x9c, 0xda, 0xec, 0x47, 0x4e, 0x94, 0xdf, 0xf9, 0xfd, 0xef, 0xcf, 0x46, 0xa6, 0xd1, 0x11,
0xbd, 0xe3, 0x32, 0xa9, 0x76, 0x5b, 0x5f, 0x97, 0x94, 0x1b, 0xe8, 0x3e, 0x80, 0xbb, 0xdb, 0x6e,
0x07, 0xe8, 0x44, 0x9f, 0x39, 0xfd, 0x37, 0x9c, 0x64, 0x76, 0x50, 0x73, 0x49, 0x79, 0xd6, 0xa5,
0xcc, 0xa2, 0xe3, 0x83, 0x50, 0xea, 0xcb, 0x92, 0xec, 0x3b, 0x0f, 0xad, 0x6c, 0xc8, 0xfb, 0xd2,
0xfa, 0x6f, 0x0e, 0x7d, 0x69, 0xdb, 0xfa, 0x7c, 0xed, 0x8c, 0x4b, 0x7b, 0x1c, 0x65, 0xba, 0xd1,
0x56, 0x88, 0xbe, 0x2e, 0x13, 0xe5, 0x86, 0xee, 0x36, 0xfa, 0xdf, 0x03, 0x18, 0x6f, 0xef, 0x7e,
0x51, 0xd0, 0xec, 0x01, 0x3d, 0x7c, 0x52, 0x1f, 0xd8, 0x7e, 0x60, 0xdc, 0x0e, 0x71, 0x29, 0x27,
0xfb, 0x19, 0xc0, 0x78, 0x7b, 0x4f, 0x1a, 0x88, 0x1b, 0xd0, 0x2f, 0x07, 0xe2, 0x06, 0x35, 0xbb,
0x5a, 0xde, 0xc5, 0x3d, 0x83, 0x4e, 0x0f, 0x84, 0x6b, 0xe3, 0x55, 0x7d, 0xdd, 0x6d, 0x5b, 0x37,
0xd0, 0x2f, 0x00, 0xa2, 0xce, 0xd6, 0x13, 0x9d, 0x0c, 0x60, 0x09, 0x6c, 0xa1, 0x93, 0xb3, 0xdb,
0xf0, 0x90, 0xfc, 0xaf, 0x73, 0xf4, 0xb3, 0xe8, 0xcc, 0x60, 0x4a, 0x3b, 0x03, 0xf9, 0xe1, 0x6f,
0xc3, 0x30, 0x8f, 0x62, 0x2d, 0x30, 0x2c, 0xdd, 0xd0, 0x3d, 0xdc, 0xd3, 0x46, 0x12, 0x9d, 0x70,
0x15, 0xd5, 0xd0, 0x54, 0xbf, 0x78, 0x45, 0xab, 0x70, 0x94, 0x57, 0x7d, 0xd4, 0x6b, 0x70, 0x95,
0xb6, 0x93, 0x47, 0x7a, 0x1b, 0x49, 0x84, 0xc3, 0x2e, 0x42, 0x02, 0xed, 0xed, 0x8e, 0x80, 0x3e,
0x05, 0x70, 0xdc, 0xd3, 0x75, 0xa0, 0xa3, 0x01, 0x43, 0x77, 0x76, 0x3f, 0xc9, 0xcc, 0x20, 0xa6,
0x92, 0xe5, 0x98, 0xcb, 0x32, 0x85, 0x52, 0xdd, 0x59, 0xa8, 0xde, 0xe0, 0x9e, 0xe8, 0x0e, 0x80,
0x11, 0xd1, 0x34, 0xa0, 0xa0, 0x95, 0xfa, 0x7a, 0x93, 0xe4, 0x4b, 0x7d, 0xac, 0xb6, 0x07, 0x21,
0x66, 0xfe, 0x15, 0x40, 0xd4, 0x59, 0xe8, 0x03, 0xc3, 0x39, 0xb0, 0x83, 0x09, 0x0c, 0xe7, 0xe0,
0x2e, 0x62, 0xe0, 0xe3, 0x48, 0x75, 0x59, 0x6f, 0xf5, 0xf5, 0xb6, 0x4a, 0xbd, 0x81, 0xbe, 0x02,
0x70, 0xc2, 0x5b, 0x45, 0x03, 0xcb, 0x5d, 0x97, 0xbe, 0x20, 0xb0, 0xdc, 0x75, 0x2b, 0xcb, 0xda,
0x69, 0x97, 0x36, 0x83, 0x66, 0x7a, 0x9c, 0xc0, 0x92, 0xe3, 0xad, 0x08, 0xf3, 0x0b, 0x9b, 0x7f,
0xa5, 0x42, 0xf7, 0xb6, 0x52, 0xa1, 0xcd, 0xad, 0x14, 0x78, 0xb4, 0x95, 0x02, 0x7f, 0x6e, 0xa5,
0xc0, 0x27, 0x8f, 0x53, 0xa1, 0x47, 0x8f, 0x53, 0xa1, 0x3f, 0x1e, 0xa7, 0x42, 0xef, 0x4e, 0x7b,
0x6e, 0x6e, 0xf3, 0x16, 0xad, 0xbf, 0xa3, 0x46, 0xad, 0xe8, 0xb7, 0xc4, 0xe8, 0xfc, 0xdf, 0xb2,
0xa5, 0x08, 0xff, 0x17, 0xe8, 0xa9, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x4c, 0xae, 0x50, 0x98,
0xfd, 0x15, 0x00, 0x00,
}
func (this *QueryContractInfoResponse) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*QueryContractInfoResponse)
if !ok {
that2, ok := that.(QueryContractInfoResponse)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.Address != that1.Address {
return false
}
if !this.ContractInfo.Equal(&that1.ContractInfo) {
return false
}
return true
}
func (this *CodeInfoResponse) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*CodeInfoResponse)
if !ok {
that2, ok := that.(CodeInfoResponse)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.CodeID != that1.CodeID {
return false
}
if this.Creator != that1.Creator {
return false
}
if !bytes.Equal(this.DataHash, that1.DataHash) {
return false
}
if !this.InstantiatePermission.Equal(&that1.InstantiatePermission) {
return false
}
return true
}
func (this *QueryCodeResponse) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*QueryCodeResponse)
if !ok {
that2, ok := that.(QueryCodeResponse)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !this.CodeInfoResponse.Equal(that1.CodeInfoResponse) {
return false
}
if !bytes.Equal(this.Data, that1.Data) {
return false
}
return true
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// QueryClient is the client API for Query service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type QueryClient interface {
// ContractInfo gets the contract meta data
ContractInfo(ctx context.Context, in *QueryContractInfoRequest, opts ...grpc.CallOption) (*QueryContractInfoResponse, error)
// ContractHistory gets the contract code history
ContractHistory(ctx context.Context, in *QueryContractHistoryRequest, opts ...grpc.CallOption) (*QueryContractHistoryResponse, error)
// ContractsByCode lists all smart contracts for a code id
ContractsByCode(ctx context.Context, in *QueryContractsByCodeRequest, opts ...grpc.CallOption) (*QueryContractsByCodeResponse, error)
// AllContractState gets all raw store data for a single contract
AllContractState(ctx context.Context, in *QueryAllContractStateRequest, opts ...grpc.CallOption) (*QueryAllContractStateResponse, error)
// RawContractState gets single key from the raw store data of a contract
RawContractState(ctx context.Context, in *QueryRawContractStateRequest, opts ...grpc.CallOption) (*QueryRawContractStateResponse, error)
// SmartContractState get smart query result from the contract
SmartContractState(ctx context.Context, in *QuerySmartContractStateRequest, opts ...grpc.CallOption) (*QuerySmartContractStateResponse, error)
// Code gets the binary code and metadata for a singe wasm code
Code(ctx context.Context, in *QueryCodeRequest, opts ...grpc.CallOption) (*QueryCodeResponse, error)
// Codes gets the metadata for all stored wasm codes
Codes(ctx context.Context, in *QueryCodesRequest, opts ...grpc.CallOption) (*QueryCodesResponse, error)
// PinnedCodes gets the pinned code ids
PinnedCodes(ctx context.Context, in *QueryPinnedCodesRequest, opts ...grpc.CallOption) (*QueryPinnedCodesResponse, error)
// Params gets the module params
Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error)
// ContractsByCreator gets the contracts by creator
ContractsByCreator(ctx context.Context, in *QueryContractsByCreatorRequest, opts ...grpc.CallOption) (*QueryContractsByCreatorResponse, error)
// BuildAddress builds a contract address
BuildAddress(ctx context.Context, in *QueryBuildAddressRequest, opts ...grpc.CallOption) (*QueryBuildAddressResponse, error)
}
type queryClient struct {
cc grpc1.ClientConn
}
func NewQueryClient(cc grpc1.ClientConn) QueryClient {
return &queryClient{cc}
}
func (c *queryClient) ContractInfo(ctx context.Context, in *QueryContractInfoRequest, opts ...grpc.CallOption) (*QueryContractInfoResponse, error) {
out := new(QueryContractInfoResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractInfo", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) ContractHistory(ctx context.Context, in *QueryContractHistoryRequest, opts ...grpc.CallOption) (*QueryContractHistoryResponse, error) {
out := new(QueryContractHistoryResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractHistory", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) ContractsByCode(ctx context.Context, in *QueryContractsByCodeRequest, opts ...grpc.CallOption) (*QueryContractsByCodeResponse, error) {
out := new(QueryContractsByCodeResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractsByCode", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) AllContractState(ctx context.Context, in *QueryAllContractStateRequest, opts ...grpc.CallOption) (*QueryAllContractStateResponse, error) {
out := new(QueryAllContractStateResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/AllContractState", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) RawContractState(ctx context.Context, in *QueryRawContractStateRequest, opts ...grpc.CallOption) (*QueryRawContractStateResponse, error) {
out := new(QueryRawContractStateResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/RawContractState", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) SmartContractState(ctx context.Context, in *QuerySmartContractStateRequest, opts ...grpc.CallOption) (*QuerySmartContractStateResponse, error) {
out := new(QuerySmartContractStateResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/SmartContractState", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) Code(ctx context.Context, in *QueryCodeRequest, opts ...grpc.CallOption) (*QueryCodeResponse, error) {
out := new(QueryCodeResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Code", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) Codes(ctx context.Context, in *QueryCodesRequest, opts ...grpc.CallOption) (*QueryCodesResponse, error) {
out := new(QueryCodesResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Codes", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) PinnedCodes(ctx context.Context, in *QueryPinnedCodesRequest, opts ...grpc.CallOption) (*QueryPinnedCodesResponse, error) {
out := new(QueryPinnedCodesResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/PinnedCodes", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) {
out := new(QueryParamsResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Params", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) ContractsByCreator(ctx context.Context, in *QueryContractsByCreatorRequest, opts ...grpc.CallOption) (*QueryContractsByCreatorResponse, error) {
out := new(QueryContractsByCreatorResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractsByCreator", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) BuildAddress(ctx context.Context, in *QueryBuildAddressRequest, opts ...grpc.CallOption) (*QueryBuildAddressResponse, error) {
out := new(QueryBuildAddressResponse)
err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/BuildAddress", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// QueryServer is the server API for Query service.
type QueryServer interface {
// ContractInfo gets the contract meta data
ContractInfo(context.Context, *QueryContractInfoRequest) (*QueryContractInfoResponse, error)
// ContractHistory gets the contract code history
ContractHistory(context.Context, *QueryContractHistoryRequest) (*QueryContractHistoryResponse, error)
// ContractsByCode lists all smart contracts for a code id
ContractsByCode(context.Context, *QueryContractsByCodeRequest) (*QueryContractsByCodeResponse, error)
// AllContractState gets all raw store data for a single contract
AllContractState(context.Context, *QueryAllContractStateRequest) (*QueryAllContractStateResponse, error)
// RawContractState gets single key from the raw store data of a contract
RawContractState(context.Context, *QueryRawContractStateRequest) (*QueryRawContractStateResponse, error)
// SmartContractState get smart query result from the contract
SmartContractState(context.Context, *QuerySmartContractStateRequest) (*QuerySmartContractStateResponse, error)
// Code gets the binary code and metadata for a singe wasm code
Code(context.Context, *QueryCodeRequest) (*QueryCodeResponse, error)
// Codes gets the metadata for all stored wasm codes
Codes(context.Context, *QueryCodesRequest) (*QueryCodesResponse, error)
// PinnedCodes gets the pinned code ids
PinnedCodes(context.Context, *QueryPinnedCodesRequest) (*QueryPinnedCodesResponse, error)
// Params gets the module params
Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error)
// ContractsByCreator gets the contracts by creator
ContractsByCreator(context.Context, *QueryContractsByCreatorRequest) (*QueryContractsByCreatorResponse, error)
// BuildAddress builds a contract address
BuildAddress(context.Context, *QueryBuildAddressRequest) (*QueryBuildAddressResponse, error)
}
// UnimplementedQueryServer can be embedded to have forward compatible implementations.
type UnimplementedQueryServer struct {
}
func (*UnimplementedQueryServer) ContractInfo(ctx context.Context, req *QueryContractInfoRequest) (*QueryContractInfoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ContractInfo not implemented")
}
func (*UnimplementedQueryServer) ContractHistory(ctx context.Context, req *QueryContractHistoryRequest) (*QueryContractHistoryResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ContractHistory not implemented")
}
func (*UnimplementedQueryServer) ContractsByCode(ctx context.Context, req *QueryContractsByCodeRequest) (*QueryContractsByCodeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ContractsByCode not implemented")
}
func (*UnimplementedQueryServer) AllContractState(ctx context.Context, req *QueryAllContractStateRequest) (*QueryAllContractStateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method AllContractState not implemented")
}
func (*UnimplementedQueryServer) RawContractState(ctx context.Context, req *QueryRawContractStateRequest) (*QueryRawContractStateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RawContractState not implemented")
}
func (*UnimplementedQueryServer) SmartContractState(ctx context.Context, req *QuerySmartContractStateRequest) (*QuerySmartContractStateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method SmartContractState not implemented")
}
func (*UnimplementedQueryServer) Code(ctx context.Context, req *QueryCodeRequest) (*QueryCodeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Code not implemented")
}
func (*UnimplementedQueryServer) Codes(ctx context.Context, req *QueryCodesRequest) (*QueryCodesResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Codes not implemented")
}
func (*UnimplementedQueryServer) PinnedCodes(ctx context.Context, req *QueryPinnedCodesRequest) (*QueryPinnedCodesResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method PinnedCodes not implemented")
}
func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Params not implemented")
}
func (*UnimplementedQueryServer) ContractsByCreator(ctx context.Context, req *QueryContractsByCreatorRequest) (*QueryContractsByCreatorResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ContractsByCreator not implemented")
}
func (*UnimplementedQueryServer) BuildAddress(ctx context.Context, req *QueryBuildAddressRequest) (*QueryBuildAddressResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BuildAddress not implemented")
}
func RegisterQueryServer(s grpc1.Server, srv QueryServer) {
s.RegisterService(&_Query_serviceDesc, srv)
}
func _Query_ContractInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryContractInfoRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).ContractInfo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/ContractInfo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).ContractInfo(ctx, req.(*QueryContractInfoRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_ContractHistory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryContractHistoryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).ContractHistory(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/ContractHistory",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).ContractHistory(ctx, req.(*QueryContractHistoryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_ContractsByCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryContractsByCodeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).ContractsByCode(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/ContractsByCode",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).ContractsByCode(ctx, req.(*QueryContractsByCodeRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_AllContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryAllContractStateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).AllContractState(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/AllContractState",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).AllContractState(ctx, req.(*QueryAllContractStateRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_RawContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryRawContractStateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).RawContractState(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/RawContractState",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).RawContractState(ctx, req.(*QueryRawContractStateRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_SmartContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QuerySmartContractStateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).SmartContractState(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/SmartContractState",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).SmartContractState(ctx, req.(*QuerySmartContractStateRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_Code_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryCodeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).Code(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/Code",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).Code(ctx, req.(*QueryCodeRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_Codes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryCodesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).Codes(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/Codes",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).Codes(ctx, req.(*QueryCodesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_PinnedCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryPinnedCodesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).PinnedCodes(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/PinnedCodes",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).PinnedCodes(ctx, req.(*QueryPinnedCodesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryParamsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).Params(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/Params",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_ContractsByCreator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryContractsByCreatorRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).ContractsByCreator(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/ContractsByCreator",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).ContractsByCreator(ctx, req.(*QueryContractsByCreatorRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_BuildAddress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryBuildAddressRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).BuildAddress(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmwasm.wasm.v1.Query/BuildAddress",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).BuildAddress(ctx, req.(*QueryBuildAddressRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Query_serviceDesc = grpc.ServiceDesc{
ServiceName: "cosmwasm.wasm.v1.Query",
HandlerType: (*QueryServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ContractInfo",
Handler: _Query_ContractInfo_Handler,
},
{
MethodName: "ContractHistory",
Handler: _Query_ContractHistory_Handler,
},
{
MethodName: "ContractsByCode",
Handler: _Query_ContractsByCode_Handler,
},
{
MethodName: "AllContractState",
Handler: _Query_AllContractState_Handler,
},
{
MethodName: "RawContractState",
Handler: _Query_RawContractState_Handler,
},
{
MethodName: "SmartContractState",
Handler: _Query_SmartContractState_Handler,
},
{
MethodName: "Code",
Handler: _Query_Code_Handler,
},
{
MethodName: "Codes",
Handler: _Query_Codes_Handler,
},
{
MethodName: "PinnedCodes",
Handler: _Query_PinnedCodes_Handler,
},
{
MethodName: "Params",
Handler: _Query_Params_Handler,
},
{
MethodName: "ContractsByCreator",
Handler: _Query_ContractsByCreator_Handler,
},
{
MethodName: "BuildAddress",
Handler: _Query_BuildAddress_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "cosmwasm/wasm/v1/query.proto",
}
func (m *QueryContractInfoRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryContractInfoRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryContractInfoRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryContractInfoResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryContractInfoResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryContractInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.ContractInfo.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryContractHistoryRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryContractHistoryRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryContractHistoryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryContractHistoryResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryContractHistoryResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryContractHistoryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.Entries) > 0 {
for iNdEx := len(m.Entries) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Entries[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *QueryContractsByCodeRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryContractsByCodeRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryContractsByCodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if m.CodeId != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.CodeId))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *QueryContractsByCodeResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryContractsByCodeResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryContractsByCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.Contracts) > 0 {
for iNdEx := len(m.Contracts) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Contracts[iNdEx])
copy(dAtA[i:], m.Contracts[iNdEx])
i = encodeVarintQuery(dAtA, i, uint64(len(m.Contracts[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *QueryAllContractStateRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAllContractStateRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAllContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryAllContractStateResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAllContractStateResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAllContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.Models) > 0 {
for iNdEx := len(m.Models) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Models[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *QueryRawContractStateRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryRawContractStateRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryRawContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.QueryData) > 0 {
i -= len(m.QueryData)
copy(dAtA[i:], m.QueryData)
i = encodeVarintQuery(dAtA, i, uint64(len(m.QueryData)))
i--
dAtA[i] = 0x12
}
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryRawContractStateResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryRawContractStateResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryRawContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QuerySmartContractStateRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QuerySmartContractStateRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QuerySmartContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.QueryData) > 0 {
i -= len(m.QueryData)
copy(dAtA[i:], m.QueryData)
i = encodeVarintQuery(dAtA, i, uint64(len(m.QueryData)))
i--
dAtA[i] = 0x12
}
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QuerySmartContractStateResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QuerySmartContractStateResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QuerySmartContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryCodeRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryCodeRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryCodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.CodeId != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.CodeId))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *CodeInfoResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *CodeInfoResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *CodeInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x32
if len(m.DataHash) > 0 {
i -= len(m.DataHash)
copy(dAtA[i:], m.DataHash)
i = encodeVarintQuery(dAtA, i, uint64(len(m.DataHash)))
i--
dAtA[i] = 0x1a
}
if len(m.Creator) > 0 {
i -= len(m.Creator)
copy(dAtA[i:], m.Creator)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Creator)))
i--
dAtA[i] = 0x12
}
if m.CodeID != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.CodeID))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *QueryCodeResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryCodeResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0x12
}
if m.CodeInfoResponse != nil {
{
size, err := m.CodeInfoResponse.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryCodesRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryCodesRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryCodesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryCodesResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryCodesResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.CodeInfos) > 0 {
for iNdEx := len(m.CodeInfos) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.CodeInfos[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *QueryPinnedCodesRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryPinnedCodesRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryPinnedCodesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
return len(dAtA) - i, nil
}
func (m *QueryPinnedCodesResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryPinnedCodesResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryPinnedCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.CodeIDs) > 0 {
dAtA15 := make([]byte, len(m.CodeIDs)*10)
var j14 int
for _, num := range m.CodeIDs {
for num >= 1<<7 {
dAtA15[j14] = uint8(uint64(num)&0x7f | 0x80)
num >>= 7
j14++
}
dAtA15[j14] = uint8(num)
j14++
}
i -= j14
copy(dAtA[i:], dAtA15[:j14])
i = encodeVarintQuery(dAtA, i, uint64(j14))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.Params.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *QueryContractsByCreatorRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryContractsByCreatorRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryContractsByCreatorRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.CreatorAddress) > 0 {
i -= len(m.CreatorAddress)
copy(dAtA[i:], m.CreatorAddress)
i = encodeVarintQuery(dAtA, i, uint64(len(m.CreatorAddress)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryContractsByCreatorResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryContractsByCreatorResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryContractsByCreatorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.ContractAddresses) > 0 {
for iNdEx := len(m.ContractAddresses) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.ContractAddresses[iNdEx])
copy(dAtA[i:], m.ContractAddresses[iNdEx])
i = encodeVarintQuery(dAtA, i, uint64(len(m.ContractAddresses[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *QueryBuildAddressRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryBuildAddressRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryBuildAddressRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.InitArgs) > 0 {
i -= len(m.InitArgs)
copy(dAtA[i:], m.InitArgs)
i = encodeVarintQuery(dAtA, i, uint64(len(m.InitArgs)))
i--
dAtA[i] = 0x22
}
if len(m.Salt) > 0 {
i -= len(m.Salt)
copy(dAtA[i:], m.Salt)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Salt)))
i--
dAtA[i] = 0x1a
}
if len(m.CreatorAddress) > 0 {
i -= len(m.CreatorAddress)
copy(dAtA[i:], m.CreatorAddress)
i = encodeVarintQuery(dAtA, i, uint64(len(m.CreatorAddress)))
i--
dAtA[i] = 0x12
}
if len(m.CodeHash) > 0 {
i -= len(m.CodeHash)
copy(dAtA[i:], m.CodeHash)
i = encodeVarintQuery(dAtA, i, uint64(len(m.CodeHash)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryBuildAddressResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryBuildAddressResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryBuildAddressResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintQuery(dAtA []byte, offset int, v uint64) int {
offset -= sovQuery(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *QueryContractInfoRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryContractInfoResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
l = m.ContractInfo.Size()
n += 1 + l + sovQuery(uint64(l))
return n
}
func (m *QueryContractHistoryRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryContractHistoryResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Entries) > 0 {
for _, e := range m.Entries {
l = e.Size()
n += 1 + l + sovQuery(uint64(l))
}
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryContractsByCodeRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.CodeId != 0 {
n += 1 + sovQuery(uint64(m.CodeId))
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryContractsByCodeResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Contracts) > 0 {
for _, s := range m.Contracts {
l = len(s)
n += 1 + l + sovQuery(uint64(l))
}
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryAllContractStateRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryAllContractStateResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Models) > 0 {
for _, e := range m.Models {
l = e.Size()
n += 1 + l + sovQuery(uint64(l))
}
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryRawContractStateRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
l = len(m.QueryData)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryRawContractStateResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Data)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QuerySmartContractStateRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
l = len(m.QueryData)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QuerySmartContractStateResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Data)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryCodeRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.CodeId != 0 {
n += 1 + sovQuery(uint64(m.CodeId))
}
return n
}
func (m *CodeInfoResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.CodeID != 0 {
n += 1 + sovQuery(uint64(m.CodeID))
}
l = len(m.Creator)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
l = len(m.DataHash)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
l = m.InstantiatePermission.Size()
n += 1 + l + sovQuery(uint64(l))
return n
}
func (m *QueryCodeResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.CodeInfoResponse != nil {
l = m.CodeInfoResponse.Size()
n += 1 + l + sovQuery(uint64(l))
}
l = len(m.Data)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryCodesRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryCodesResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.CodeInfos) > 0 {
for _, e := range m.CodeInfos {
l = e.Size()
n += 1 + l + sovQuery(uint64(l))
}
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryPinnedCodesRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryPinnedCodesResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.CodeIDs) > 0 {
l = 0
for _, e := range m.CodeIDs {
l += sovQuery(uint64(e))
}
n += 1 + sovQuery(uint64(l)) + l
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryParamsRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *QueryParamsResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.Params.Size()
n += 1 + l + sovQuery(uint64(l))
return n
}
func (m *QueryContractsByCreatorRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.CreatorAddress)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryContractsByCreatorResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.ContractAddresses) > 0 {
for _, s := range m.ContractAddresses {
l = len(s)
n += 1 + l + sovQuery(uint64(l))
}
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryBuildAddressRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.CodeHash)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
l = len(m.CreatorAddress)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
l = len(m.Salt)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
l = len(m.InitArgs)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryBuildAddressResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func sovQuery(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozQuery(x uint64) (n int) {
return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *QueryContractInfoRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryContractInfoRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryContractInfoRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryContractInfoResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryContractInfoResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryContractInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ContractInfo", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ContractInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryContractHistoryRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryContractHistoryRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryContractHistoryRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryContractHistoryResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryContractHistoryResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryContractHistoryResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Entries", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Entries = append(m.Entries, ContractCodeHistoryEntry{})
if err := m.Entries[len(m.Entries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryContractsByCodeRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryContractsByCodeRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryContractsByCodeRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CodeId", wireType)
}
m.CodeId = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.CodeId |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryContractsByCodeResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryContractsByCodeResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryContractsByCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Contracts", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Contracts = append(m.Contracts, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAllContractStateRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAllContractStateRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAllContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAllContractStateResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAllContractStateResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAllContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Models", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Models = append(m.Models, Model{})
if err := m.Models[len(m.Models)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryRawContractStateRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryRawContractStateRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryRawContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field QueryData", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.QueryData = append(m.QueryData[:0], dAtA[iNdEx:postIndex]...)
if m.QueryData == nil {
m.QueryData = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryRawContractStateResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryRawContractStateResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryRawContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QuerySmartContractStateRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QuerySmartContractStateRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QuerySmartContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field QueryData", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.QueryData = append(m.QueryData[:0], dAtA[iNdEx:postIndex]...)
if m.QueryData == nil {
m.QueryData = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QuerySmartContractStateResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QuerySmartContractStateResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QuerySmartContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryCodeRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryCodeRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryCodeRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CodeId", wireType)
}
m.CodeId = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.CodeId |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *CodeInfoResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: CodeInfoResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: CodeInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType)
}
m.CodeID = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.CodeID |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Creator = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DataHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.DataHash = append(m.DataHash[:0], dAtA[iNdEx:postIndex]...)
if m.DataHash == nil {
m.DataHash = []byte{}
}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryCodeResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryCodeResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CodeInfoResponse", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.CodeInfoResponse == nil {
m.CodeInfoResponse = &CodeInfoResponse{}
}
if err := m.CodeInfoResponse.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryCodesRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryCodesRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryCodesRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryCodesResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryCodesResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CodeInfos", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.CodeInfos = append(m.CodeInfos, CodeInfoResponse{})
if err := m.CodeInfos[len(m.CodeInfos)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryPinnedCodesRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryPinnedCodesRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryPinnedCodesRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryPinnedCodesResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryPinnedCodesResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryPinnedCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType == 0 {
var v uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.CodeIDs = append(m.CodeIDs, v)
} else if wireType == 2 {
var packedLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
packedLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if packedLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + packedLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
var elementCount int
var count int
for _, integer := range dAtA[iNdEx:postIndex] {
if integer < 128 {
count++
}
}
elementCount = count
if elementCount != 0 && len(m.CodeIDs) == 0 {
m.CodeIDs = make([]uint64, 0, elementCount)
}
for iNdEx < postIndex {
var v uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.CodeIDs = append(m.CodeIDs, v)
}
} else {
return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType)
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryContractsByCreatorRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryContractsByCreatorRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryContractsByCreatorRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CreatorAddress", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.CreatorAddress = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryContractsByCreatorResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryContractsByCreatorResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryContractsByCreatorResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ContractAddresses", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ContractAddresses = append(m.ContractAddresses, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryBuildAddressRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryBuildAddressRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryBuildAddressRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.CodeHash = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CreatorAddress", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.CreatorAddress = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Salt", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Salt = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field InitArgs", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.InitArgs = append(m.InitArgs[:0], dAtA[iNdEx:postIndex]...)
if m.InitArgs == nil {
m.InitArgs = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryBuildAddressResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryBuildAddressResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryBuildAddressResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipQuery(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthQuery
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupQuery
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthQuery
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group")
)
package api
// #include <stdlib.h>
// #include "bindings.h"
import "C"
import (
"fmt"
"os"
"runtime"
"strings"
"syscall"
"golang.org/x/sys/unix"
"github.com/CosmWasm/wasmvm/v2/types"
)
// Value types
type (
cint = C.int
cbool = C.bool
cusize = C.size_t
cu8 = C.uint8_t
cu32 = C.uint32_t
cu64 = C.uint64_t
ci8 = C.int8_t
ci32 = C.int32_t
ci64 = C.int64_t
)
// Pointers
type (
cu8_ptr = *C.uint8_t
)
type Cache struct {
ptr *C.cache_t
lockfile os.File
}
type Querier = types.Querier
func InitCache(dataDir string, supportedCapabilities []string, cacheSize uint32, instanceMemoryLimit uint32) (Cache, error) {
// libwasmvm would create this directory too but we need it earlier for the lockfile
err := os.MkdirAll(dataDir, 0o755)
if err != nil {
return Cache{}, fmt.Errorf("Could not create base directory")
}
lockfile, err := os.OpenFile(dataDir+"/exclusive.lock", os.O_WRONLY|os.O_CREATE, 0o666)
if err != nil {
return Cache{}, fmt.Errorf("Could not open exclusive.lock")
}
_, err = lockfile.WriteString("This is a lockfile that prevent two VM instances to operate on the same directory in parallel.\nSee codebase at github.com/CosmWasm/wasmvm for more information.\nSafety first – brought to you by Confio ❤️\n")
if err != nil {
return Cache{}, fmt.Errorf("Error writing to exclusive.lock")
}
err = unix.Flock(int(lockfile.Fd()), unix.LOCK_EX|unix.LOCK_NB)
if err != nil {
return Cache{}, fmt.Errorf("Could not lock exclusive.lock. Is a different VM running in the same directory already?")
}
dataDirBytes := []byte(dataDir)
supportedCapabilitiesBytes := []byte(strings.Join(supportedCapabilities, ","))
d := makeView(dataDirBytes)
defer runtime.KeepAlive(dataDirBytes)
capabilitiesView := makeView(supportedCapabilitiesBytes)
defer runtime.KeepAlive(supportedCapabilitiesBytes)
errmsg := uninitializedUnmanagedVector()
ptr, err := C.init_cache(d, capabilitiesView, cu32(cacheSize), cu32(instanceMemoryLimit), &errmsg)
if err != nil {
return Cache{}, errorWithMessage(err, errmsg)
}
return Cache{ptr: ptr, lockfile: *lockfile}, nil
}
func ReleaseCache(cache Cache) {
C.release_cache(cache.ptr)
cache.lockfile.Close() // Also releases the file lock
}
func StoreCode(cache Cache, wasm []byte, persist bool) ([]byte, error) {
w := makeView(wasm)
defer runtime.KeepAlive(wasm)
errmsg := uninitializedUnmanagedVector()
checksum, err := C.store_code(cache.ptr, w, cbool(true), cbool(persist), &errmsg)
if err != nil {
return nil, errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(checksum), nil
}
func StoreCodeUnchecked(cache Cache, wasm []byte) ([]byte, error) {
w := makeView(wasm)
defer runtime.KeepAlive(wasm)
errmsg := uninitializedUnmanagedVector()
checksum, err := C.store_code(cache.ptr, w, cbool(false), cbool(true), &errmsg)
if err != nil {
return nil, errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(checksum), nil
}
func RemoveCode(cache Cache, checksum []byte) error {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
errmsg := uninitializedUnmanagedVector()
_, err := C.remove_wasm(cache.ptr, cs, &errmsg)
if err != nil {
return errorWithMessage(err, errmsg)
}
return nil
}
func GetCode(cache Cache, checksum []byte) ([]byte, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
errmsg := uninitializedUnmanagedVector()
wasm, err := C.load_wasm(cache.ptr, cs, &errmsg)
if err != nil {
return nil, errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(wasm), nil
}
func Pin(cache Cache, checksum []byte) error {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
errmsg := uninitializedUnmanagedVector()
_, err := C.pin(cache.ptr, cs, &errmsg)
if err != nil {
return errorWithMessage(err, errmsg)
}
return nil
}
func Unpin(cache Cache, checksum []byte) error {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
errmsg := uninitializedUnmanagedVector()
_, err := C.unpin(cache.ptr, cs, &errmsg)
if err != nil {
return errorWithMessage(err, errmsg)
}
return nil
}
func AnalyzeCode(cache Cache, checksum []byte) (*types.AnalysisReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
errmsg := uninitializedUnmanagedVector()
report, err := C.analyze_code(cache.ptr, cs, &errmsg)
if err != nil {
return nil, errorWithMessage(err, errmsg)
}
requiredCapabilities := string(copyAndDestroyUnmanagedVector(report.required_capabilities))
entrypoints := string(copyAndDestroyUnmanagedVector(report.entrypoints))
res := types.AnalysisReport{
HasIBCEntryPoints: bool(report.has_ibc_entry_points),
RequiredCapabilities: requiredCapabilities,
Entrypoints: strings.Split(entrypoints, ","),
ContractMigrateVersion: optionalU64ToPtr(report.contract_migrate_version),
}
return &res, nil
}
func GetMetrics(cache Cache) (*types.Metrics, error) {
errmsg := uninitializedUnmanagedVector()
metrics, err := C.get_metrics(cache.ptr, &errmsg)
if err != nil {
return nil, errorWithMessage(err, errmsg)
}
return &types.Metrics{
HitsPinnedMemoryCache: uint32(metrics.hits_pinned_memory_cache),
HitsMemoryCache: uint32(metrics.hits_memory_cache),
HitsFsCache: uint32(metrics.hits_fs_cache),
Misses: uint32(metrics.misses),
ElementsPinnedMemoryCache: uint64(metrics.elements_pinned_memory_cache),
ElementsMemoryCache: uint64(metrics.elements_memory_cache),
SizePinnedMemoryCache: uint64(metrics.size_pinned_memory_cache),
SizeMemoryCache: uint64(metrics.size_memory_cache),
}, nil
}
func GetPinnedMetrics(cache Cache) (*types.PinnedMetrics, error) {
errmsg := uninitializedUnmanagedVector()
metrics, err := C.get_pinned_metrics(cache.ptr, &errmsg)
if err != nil {
return nil, errorWithMessage(err, errmsg)
}
var pinnedMetrics types.PinnedMetrics
if err := pinnedMetrics.UnmarshalMessagePack(copyAndDestroyUnmanagedVector(metrics)); err != nil {
return nil, err
}
return &pinnedMetrics, nil
}
func Instantiate(
cache Cache,
checksum []byte,
env []byte,
info []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
i := makeView(info)
defer runtime.KeepAlive(info)
m := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.instantiate(cache.ptr, cs, e, i, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func Execute(
cache Cache,
checksum []byte,
env []byte,
info []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
i := makeView(info)
defer runtime.KeepAlive(info)
m := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.execute(cache.ptr, cs, e, i, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func Migrate(
cache Cache,
checksum []byte,
env []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
m := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.migrate(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func Sudo(
cache Cache,
checksum []byte,
env []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
m := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.sudo(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func Reply(
cache Cache,
checksum []byte,
env []byte,
reply []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
r := makeView(reply)
defer runtime.KeepAlive(reply)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.reply(cache.ptr, cs, e, r, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func Query(
cache Cache,
checksum []byte,
env []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
m := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.query(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func IBCChannelOpen(
cache Cache,
checksum []byte,
env []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
m := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.ibc_channel_open(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func IBCChannelConnect(
cache Cache,
checksum []byte,
env []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
m := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.ibc_channel_connect(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func IBCChannelClose(
cache Cache,
checksum []byte,
env []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
m := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.ibc_channel_close(cache.ptr, cs, e, m, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func IBCPacketReceive(
cache Cache,
checksum []byte,
env []byte,
packet []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
pa := makeView(packet)
defer runtime.KeepAlive(packet)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.ibc_packet_receive(cache.ptr, cs, e, pa, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func IBCPacketAck(
cache Cache,
checksum []byte,
env []byte,
ack []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
ac := makeView(ack)
defer runtime.KeepAlive(ack)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.ibc_packet_ack(cache.ptr, cs, e, ac, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func IBCPacketTimeout(
cache Cache,
checksum []byte,
env []byte,
packet []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
pa := makeView(packet)
defer runtime.KeepAlive(packet)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.ibc_packet_timeout(cache.ptr, cs, e, pa, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func IBCSourceCallback(
cache Cache,
checksum []byte,
env []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
msgBytes := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.ibc_source_callback(cache.ptr, cs, e, msgBytes, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func IBCDestinationCallback(
cache Cache,
checksum []byte,
env []byte,
msg []byte,
gasMeter *types.GasMeter,
store types.KVStore,
api *types.GoAPI,
querier *Querier,
gasLimit uint64,
printDebug bool,
) ([]byte, types.GasReport, error) {
cs := makeView(checksum)
defer runtime.KeepAlive(checksum)
e := makeView(env)
defer runtime.KeepAlive(env)
msgBytes := makeView(msg)
defer runtime.KeepAlive(msg)
var pinner runtime.Pinner
pinner.Pin(gasMeter)
checkAndPinAPI(api, pinner)
checkAndPinQuerier(querier, pinner)
defer pinner.Unpin()
callID := startCall()
defer endCall(callID)
dbState := buildDBState(store, callID)
db := buildDB(&dbState, gasMeter)
a := buildAPI(api)
q := buildQuerier(querier)
var gasReport C.GasReport
errmsg := uninitializedUnmanagedVector()
res, err := C.ibc_destination_callback(cache.ptr, cs, e, msgBytes, db, a, q, cu64(gasLimit), cbool(printDebug), &gasReport, &errmsg)
if err != nil && err.(syscall.Errno) != C.ErrnoValue_Success {
// Depending on the nature of the error, `gasUsed` will either have a meaningful value, or just 0.
return nil, convertGasReport(gasReport), errorWithMessage(err, errmsg)
}
return copyAndDestroyUnmanagedVector(res), convertGasReport(gasReport), nil
}
func convertGasReport(report C.GasReport) types.GasReport {
return types.GasReport{
Limit: uint64(report.limit),
Remaining: uint64(report.remaining),
UsedExternally: uint64(report.used_externally),
UsedInternally: uint64(report.used_internally),
}
}
/**** To error module ***/
func errorWithMessage(err error, b C.UnmanagedVector) error {
// we always destroy the unmanaged vector to avoid a memory leak
msg := copyAndDestroyUnmanagedVector(b)
// this checks for out of gas as a special case
if errno, ok := err.(syscall.Errno); ok && int(errno) == 2 {
return types.OutOfGasError{}
}
if msg == nil {
return err
}
return fmt.Errorf("%s", string(msg))
}
// checkAndPinAPI checks and pins the API and relevant pointers inside of it.
// All errors will result in panics as they indicate misuse of the wasmvm API and are not expected
// to be caused by user data.
func checkAndPinAPI(api *types.GoAPI, pinner runtime.Pinner) {
if api == nil {
panic("API must not be nil. If you don't want to provide API functionality, please create an instance that returns an error on every call to HumanizeAddress(), CanonicalizeAddress() and ValidateAddress().")
}
// func cHumanizeAddress assumes this is set
if api.HumanizeAddress == nil {
panic("HumanizeAddress in API must not be nil. If you don't want to provide API functionality, please create an instance that returns an error on every call to HumanizeAddress(), CanonicalizeAddress() and ValidateAddress().")
}
// func cCanonicalizeAddress assumes this is set
if api.CanonicalizeAddress == nil {
panic("CanonicalizeAddress in API must not be nil. If you don't want to provide API functionality, please create an instance that returns an error on every call to HumanizeAddress(), CanonicalizeAddress() and ValidateAddress().")
}
// func cValidateAddress assumes this is set
if api.ValidateAddress == nil {
panic("ValidateAddress in API must not be nil. If you don't want to provide API functionality, please create an instance that returns an error on every call to HumanizeAddress(), CanonicalizeAddress() and ValidateAddress().")
}
pinner.Pin(api) // this pointer is used in Rust (`state` in `C.GoApi`) and must not change
}
// checkAndPinQuerier checks and pins the querier.
// All errors will result in panics as they indicate misuse of the wasmvm API and are not expected
// to be caused by user data.
func checkAndPinQuerier(querier *Querier, pinner runtime.Pinner) {
if querier == nil {
panic("Querier must not be nil. If you don't want to provide querier functionality, please create an instance that returns an error on every call to Query().")
}
pinner.Pin(querier) // this pointer is used in Rust (`state` in `C.GoQuerier`) and must not change
}
//go:build cgo && !nolink_libwasmvm
// This file contains the part of the API that is exposed when libwasmvm
// is available (i.e. cgo is enabled and nolink_libwasmvm is not set).
package cosmwasm
import (
"encoding/json"
"fmt"
"github.com/CosmWasm/wasmvm/v2/internal/api"
"github.com/CosmWasm/wasmvm/v2/types"
)
// 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.
type VM struct {
cache api.Cache
printDebug bool
}
// 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 NewVM(dataDir string, supportedCapabilities []string, memoryLimit uint32, printDebug bool, cacheSize uint32) (*VM, error) {
cache, err := api.InitCache(dataDir, supportedCapabilities, cacheSize, memoryLimit)
if err != nil {
return nil, err
}
return &VM{cache: cache, printDebug: printDebug}, nil
}
// 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 *VM) Cleanup() {
api.ReleaseCache(vm.cache)
}
// 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 *VM) StoreCode(code WasmCode, gasLimit uint64) (Checksum, uint64, error) {
gasCost := compileCost(code)
if gasLimit < gasCost {
return nil, gasCost, types.OutOfGasError{}
}
checksum, err := api.StoreCode(vm.cache, code, true)
return checksum, gasCost, err
}
// SimulateStoreCode is the same as StoreCode but does not actually store the code.
// This is useful for simulating all the validations happening in StoreCode without actually
// writing anything to disk.
func (vm *VM) SimulateStoreCode(code WasmCode, gasLimit uint64) (Checksum, uint64, error) {
gasCost := compileCost(code)
if gasLimit < gasCost {
return nil, gasCost, types.OutOfGasError{}
}
checksum, err := api.StoreCode(vm.cache, code, false)
return checksum, gasCost, err
}
// 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 *VM) StoreCodeUnchecked(code WasmCode) (Checksum, error) {
return api.StoreCodeUnchecked(vm.cache, code)
}
func (vm *VM) RemoveCode(checksum Checksum) error {
return api.RemoveCode(vm.cache, checksum)
}
// 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 *VM) GetCode(checksum Checksum) (WasmCode, error) {
return api.GetCode(vm.cache, checksum)
}
// Pin pins a code to an in-memory cache, such that is
// always loaded quickly when executed.
// Pin is idempotent.
func (vm *VM) Pin(checksum Checksum) error {
return api.Pin(vm.cache, checksum)
}
// 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.
func (vm *VM) Unpin(checksum Checksum) error {
return api.Unpin(vm.cache, checksum)
}
// 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 *VM) AnalyzeCode(checksum Checksum) (*types.AnalysisReport, error) {
return api.AnalyzeCode(vm.cache, checksum)
}
// GetMetrics some internal metrics for monitoring purposes.
func (vm *VM) GetMetrics() (*types.Metrics, error) {
return api.GetMetrics(vm.cache)
}
// 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 *VM) GetPinnedMetrics() (*types.PinnedMetrics, error) {
return api.GetPinnedMetrics(vm.cache)
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
infoBin, err := json.Marshal(info)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.Instantiate(vm.cache, checksum, envBin, infoBin, initMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.ContractResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
infoBin, err := json.Marshal(info)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.Execute(vm.cache, checksum, envBin, infoBin, executeMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.ContractResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.Query(vm.cache, checksum, envBin, queryMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.QueryResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.Migrate(vm.cache, checksum, envBin, migrateMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.ContractResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// Sudo allows native Go modules to make privileged (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 privileged entry points
// without forking cosmwasm-vm.
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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.Sudo(vm.cache, checksum, envBin, sudoMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.ContractResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// Reply allows the native Go wasm modules to make a privileged 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
replyBin, err := json.Marshal(reply)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.Reply(vm.cache, checksum, envBin, replyBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.ContractResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// IBCChannelOpen is available on IBC-enabled contracts and is a hook to call into
// during the handshake pahse
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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.IBCChannelOpen(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.IBCChannelOpenResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// IBCChannelConnect is available on IBC-enabled contracts and is a hook to call into
// during the handshake pahse
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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.IBCChannelConnect(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.IBCBasicResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// IBCChannelClose is available on IBC-enabled contracts and is a hook to call into
// at the end of the channel lifetime
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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.IBCChannelClose(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.IBCBasicResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.IBCPacketReceive(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.IBCReceiveResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.IBCPacketAck(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.IBCBasicResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.IBCPacketTimeout(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.IBCBasicResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.IBCSourceCallback(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.IBCBasicResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
// 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 *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) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
msgBin, err := json.Marshal(msg)
if err != nil {
return nil, 0, err
}
data, gasReport, err := api.IBCDestinationCallback(vm.cache, checksum, envBin, msgBin, &gasMeter, store, &goapi, &querier, gasLimit, vm.printDebug)
if err != nil {
return nil, gasReport.UsedInternally, err
}
var result types.IBCBasicResult
err = DeserializeResponse(gasLimit, deserCost, &gasReport, data, &result)
if err != nil {
return nil, gasReport.UsedInternally, err
}
return &result, gasReport.UsedInternally, nil
}
func compileCost(code WasmCode) uint64 {
// CostPerByte is how much CosmWasm gas is charged *per byte* for compiling WASM code.
// Benchmarks and numbers (in SDK Gas) were discussed in:
// https://github.com/CosmWasm/wasmd/pull/634#issuecomment-938056803
const CostPerByte uint64 = 3 * 140_000
return CostPerByte * uint64(len(code))
}
// hasSubMessages is an interface for contract results that can contain sub-messages.
type hasSubMessages interface {
SubMessages() []types.SubMsg
}
// make sure the types implement the interface
// cannot put these next to the types, as the interface is private
var (
_ hasSubMessages = (*types.IBCBasicResult)(nil)
_ hasSubMessages = (*types.IBCReceiveResult)(nil)
_ hasSubMessages = (*types.ContractResult)(nil)
)
func DeserializeResponse(gasLimit uint64, deserCost types.UFraction, gasReport *types.GasReport, data []byte, response any) error {
gasForDeserialization := deserCost.Mul(uint64(len(data))).Floor()
if gasLimit < gasForDeserialization+gasReport.UsedInternally {
return fmt.Errorf("Insufficient gas left to deserialize contract execution result (%d bytes)", len(data))
}
gasReport.UsedInternally += gasForDeserialization
gasReport.Remaining -= gasForDeserialization
err := json.Unmarshal(data, response)
if err != nil {
return err
}
// All responses that have sub-messages need their payload size to be checked
const ReplyPayloadMaxBytes = 128 * 1024 // 128 KiB
if response, ok := response.(hasSubMessages); ok {
for i, m := range response.SubMessages() {
// each payload needs to be below maximum size
if len(m.Payload) > ReplyPayloadMaxBytes {
return fmt.Errorf("reply contains submessage at index %d with payload larger than %d bytes: %d bytes", i, ReplyPayloadMaxBytes, len(m.Payload))
}
}
}
return nil
}
package ethsecp256k1
import (
"bytes"
"crypto/ecdsa"
"crypto/subtle"
"fmt"
"cosmossdk.io/errors"
tmcrypto "github.com/cometbft/cometbft/crypto"
"github.com/cosmos/cosmos-sdk/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/secp256k1"
)
const (
// PrivKeySize defines the size of the PrivKey bytes
PrivKeySize = 32
// PubKeySize defines the size of the PubKey bytes
PubKeySize = 33
// KeyType is the string constant for the Secp256k1 algorithm
KeyType = "eth_secp256k1"
)
// Amino encoding names
const (
// PrivKeyName defines the amino encoding name for the EthSecp256k1 private key
PrivKeyName = "injective/PrivKeyEthSecp256k1"
// PubKeyName defines the amino encoding name for the EthSecp256k1 public key
PubKeyName = "injective/PubKeyEthSecp256k1"
)
// ----------------------------------------------------------------------------
// secp256k1 Private Key
var (
_ cryptotypes.PrivKey = &PrivKey{}
_ codec.AminoMarshaler = &PrivKey{}
)
// GenerateKey generates a new random private key. It returns an error upon
// failure.
func GenerateKey() (*PrivKey, error) {
priv, err := ethcrypto.GenerateKey()
if err != nil {
return nil, err
}
return &PrivKey{
Key: ethcrypto.FromECDSA(priv),
}, nil
}
// Bytes returns the byte representation of the ECDSA Private Key.
func (privKey *PrivKey) Bytes() []byte {
return privKey.Key
}
// PubKey returns the ECDSA private key's public key.
func (privKey PrivKey) PubKey() cryptotypes.PubKey {
ecdsaPrivKey := privKey.ToECDSA()
return &PubKey{
Key: ethcrypto.CompressPubkey(&ecdsaPrivKey.PublicKey),
}
}
// Equals returns true if two ECDSA private keys are equal and false otherwise.
func (privKey *PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool {
return privKey.Type() == other.Type() && subtle.ConstantTimeCompare(privKey.Bytes(), other.Bytes()) == 1
}
// Type returns eth_secp256k1
func (privKey *PrivKey) Type() string {
return KeyType
}
// MarshalAmino overrides Amino binary marshalling.
func (privKey PrivKey) MarshalAmino() ([]byte, error) {
return privKey.Key, nil
}
// UnmarshalAmino overrides Amino binary marshalling.
func (privKey *PrivKey) UnmarshalAmino(bz []byte) error {
if len(bz) != PrivKeySize {
return fmt.Errorf("invalid privkey size, expected %d got %d", PrivKeySize, len(bz))
}
privKey.Key = bz
return nil
}
// MarshalAminoJSON overrides Amino JSON marshalling.
func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) {
// When we marshal to Amino JSON, we don't marshal the "key" field itself,
// just its contents (i.e. the key bytes).
return privKey.MarshalAmino()
}
// UnmarshalAminoJSON overrides Amino JSON marshalling.
func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error {
return privKey.UnmarshalAmino(bz)
}
// Sign creates a recoverable ECDSA signature on the secp256k1 curve over the
// Keccak256 hash of the provided message. The produced signature is 65 bytes
// where the last byte contains the recovery ID.
func (privKey PrivKey) Sign(msg []byte) ([]byte, error) {
return ethcrypto.Sign(ethcrypto.Keccak256Hash(msg).Bytes(), privKey.ToECDSA())
}
// ToECDSA returns the ECDSA private key as a reference to ecdsa.PrivateKey type.
// The function will panic if the private key is invalid.
func (privKey PrivKey) ToECDSA() *ecdsa.PrivateKey {
key, err := ethcrypto.ToECDSA(privKey.Bytes())
if err != nil {
panic(err)
}
return key
}
// ----------------------------------------------------------------------------
// secp256k1 Public Key
var (
_ cryptotypes.PubKey = &PubKey{}
_ codec.AminoMarshaler = &PubKey{}
)
// Address returns the address of the ECDSA public key.
// The function will panic if the public key is invalid.
func (pubKey PubKey) Address() tmcrypto.Address {
pubk, err := ethcrypto.DecompressPubkey(pubKey.Key)
if err != nil {
if pubk, err = ethcrypto.UnmarshalPubkey(pubKey.Key); err != nil {
panic(err)
}
}
return tmcrypto.Address(ethcrypto.PubkeyToAddress(*pubk).Bytes())
}
// Bytes returns the raw bytes of the ECDSA public key.
func (pubKey PubKey) Bytes() []byte {
return pubKey.Key
}
// String implements the fmt.Stringer interface.
func (pubKey *PubKey) String() string {
return fmt.Sprintf("EthPubKeySecp256k1{%X}", pubKey.Key)
}
// Type returns eth_secp256k1
func (pubKey *PubKey) Type() string {
return KeyType
}
// Equals returns true if the pubkey type is the same and their bytes are deeply equal.
func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool {
return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes())
}
// MarshalAmino overrides Amino binary marshalling.
func (pubKey PubKey) MarshalAmino() ([]byte, error) {
return pubKey.Key, nil
}
// UnmarshalAmino overrides Amino binary marshalling.
func (pubKey *PubKey) UnmarshalAmino(bz []byte) error {
if len(bz) != PubKeySize {
return errors.Wrapf(sdkerrors.ErrInvalidPubKey, "invalid pubkey size, expected %d, got %d", PubKeySize, len(bz))
}
pubKey.Key = bz
return nil
}
// MarshalAminoJSON overrides Amino JSON marshalling.
func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) {
// When we marshal to Amino JSON, we don't marshal the "key" field itself,
// just its contents (i.e. the key bytes).
return pubKey.MarshalAmino()
}
// UnmarshalAminoJSON overrides Amino JSON marshalling.
func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error {
return pubKey.UnmarshalAmino(bz)
}
// VerifySignature verifies that the ECDSA public key created a given signature over
// the provided message. It will calculate the Keccak256 hash of the message
// prior to verification.
func (pubKey PubKey) VerifySignature(msg, sig []byte) bool {
if len(sig) == 65 {
// remove recovery ID if contained in the signature
sig = sig[:64]
}
// the signature needs to be in [R || S] format when provided to VerifySignature
return secp256k1.VerifySignature(pubKey.Key, ethcrypto.Keccak256Hash(msg).Bytes(), sig)
}
package abcicli
import (
"context"
types "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/service"
cmtsync "github.com/cometbft/cometbft/libs/sync"
)
// NOTE: use defer to unlock mutex because Application might panic (e.g., in
// case of malicious tx or query). It only makes sense for publicly exposed
// methods like CheckTx (/broadcast_tx_* RPC endpoint) or Query (/abci_query
// RPC endpoint), but defers are used everywhere for the sake of consistency.
type localClient struct {
service.BaseService
mtx *cmtsync.Mutex
types.Application
Callback
}
var _ Client = (*localClient)(nil)
// NewLocalClient creates a local client, which wraps the application interface that
// Tendermint as the client will call to the application as the server. The only
// difference, is that the local client has a global mutex which enforces serialization
// of all the ABCI calls from Tendermint to the Application.
func NewLocalClient(mtx *cmtsync.Mutex, app types.Application) Client {
if mtx == nil {
mtx = new(cmtsync.Mutex)
}
cli := &localClient{
mtx: mtx,
Application: app,
}
cli.BaseService = *service.NewBaseService(nil, "localClient", cli)
return cli
}
func (app *localClient) SetResponseCallback(cb Callback) {
app.mtx.Lock()
app.Callback = cb
app.mtx.Unlock()
}
func (app *localClient) CheckTxAsync(ctx context.Context, req *types.RequestCheckTx) (*ReqRes, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
res, err := app.Application.CheckTx(ctx, req)
if err != nil {
return nil, err
}
return app.callback(
types.ToRequestCheckTx(req),
types.ToResponseCheckTx(res),
), nil
}
func (app *localClient) callback(req *types.Request, res *types.Response) *ReqRes {
app.Callback(req, res)
rr := newLocalReqRes(req, res)
rr.callbackInvoked = true
return rr
}
func newLocalReqRes(req *types.Request, res *types.Response) *ReqRes {
reqRes := NewReqRes(req)
reqRes.Response = res
return reqRes
}
//-------------------------------------------------------
func (app *localClient) Error() error {
return nil
}
func (app *localClient) Flush(context.Context) error {
return nil
}
func (app *localClient) Echo(_ context.Context, msg string) (*types.ResponseEcho, error) {
return &types.ResponseEcho{Message: msg}, nil
}
func (app *localClient) Info(ctx context.Context, req *types.RequestInfo) (*types.ResponseInfo, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.Info(ctx, req)
}
func (app *localClient) CheckTx(ctx context.Context, req *types.RequestCheckTx) (*types.ResponseCheckTx, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.CheckTx(ctx, req)
}
func (app *localClient) Query(ctx context.Context, req *types.RequestQuery) (*types.ResponseQuery, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.Query(ctx, req)
}
func (app *localClient) Commit(ctx context.Context, req *types.RequestCommit) (*types.ResponseCommit, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.Commit(ctx, req)
}
func (app *localClient) InitChain(ctx context.Context, req *types.RequestInitChain) (*types.ResponseInitChain, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.InitChain(ctx, req)
}
func (app *localClient) ListSnapshots(ctx context.Context, req *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.ListSnapshots(ctx, req)
}
func (app *localClient) OfferSnapshot(ctx context.Context, req *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.OfferSnapshot(ctx, req)
}
func (app *localClient) LoadSnapshotChunk(ctx context.Context,
req *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.LoadSnapshotChunk(ctx, req)
}
func (app *localClient) ApplySnapshotChunk(ctx context.Context,
req *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.ApplySnapshotChunk(ctx, req)
}
func (app *localClient) PrepareProposal(ctx context.Context, req *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.PrepareProposal(ctx, req)
}
func (app *localClient) ProcessProposal(ctx context.Context, req *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.ProcessProposal(ctx, req)
}
func (app *localClient) ExtendVote(ctx context.Context, req *types.RequestExtendVote) (*types.ResponseExtendVote, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.ExtendVote(ctx, req)
}
func (app *localClient) VerifyVoteExtension(ctx context.Context, req *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.VerifyVoteExtension(ctx, req)
}
func (app *localClient) FinalizeBlock(ctx context.Context, req *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) {
app.mtx.Lock()
defer app.mtx.Unlock()
return app.Application.FinalizeBlock(ctx, req)
}
package types
import (
"bytes"
"encoding/json"
"github.com/cosmos/gogoproto/jsonpb"
)
const (
CodeTypeOK uint32 = 0
)
// IsOK returns true if Code is OK.
func (r ResponseCheckTx) IsOK() bool {
return r.Code == CodeTypeOK
}
// IsErr returns true if Code is something other than OK.
func (r ResponseCheckTx) IsErr() bool {
return r.Code != CodeTypeOK
}
// IsOK returns true if Code is OK.
func (r ExecTxResult) IsOK() bool {
return r.Code == CodeTypeOK
}
// IsErr returns true if Code is something other than OK.
func (r ExecTxResult) IsErr() bool {
return r.Code != CodeTypeOK
}
// IsOK returns true if Code is OK.
func (r ResponseQuery) IsOK() bool {
return r.Code == CodeTypeOK
}
// IsErr returns true if Code is something other than OK.
func (r ResponseQuery) IsErr() bool {
return r.Code != CodeTypeOK
}
// IsAccepted returns true if Code is ACCEPT
func (r ResponseProcessProposal) IsAccepted() bool {
return r.Status == ResponseProcessProposal_ACCEPT
}
// IsStatusUnknown returns true if Code is UNKNOWN
func (r ResponseProcessProposal) IsStatusUnknown() bool {
return r.Status == ResponseProcessProposal_UNKNOWN
}
func (r ResponseVerifyVoteExtension) IsAccepted() bool {
return r.Status == ResponseVerifyVoteExtension_ACCEPT
}
// IsStatusUnknown returns true if Code is Unknown
func (r ResponseVerifyVoteExtension) IsStatusUnknown() bool {
return r.Status == ResponseVerifyVoteExtension_UNKNOWN
}
//---------------------------------------------------------------------------
// override JSON marshaling so we emit defaults (ie. disable omitempty)
var (
jsonpbMarshaller = jsonpb.Marshaler{
EnumsAsInts: true,
EmitDefaults: true,
}
jsonpbUnmarshaller = jsonpb.Unmarshaler{}
)
func (r *ResponseCheckTx) MarshalJSON() ([]byte, error) {
s, err := jsonpbMarshaller.MarshalToString(r)
return []byte(s), err
}
func (r *ResponseCheckTx) UnmarshalJSON(b []byte) error {
reader := bytes.NewBuffer(b)
return jsonpbUnmarshaller.Unmarshal(reader, r)
}
func (r *ExecTxResult) MarshalJSON() ([]byte, error) {
s, err := jsonpbMarshaller.MarshalToString(r)
return []byte(s), err
}
func (r *ExecTxResult) UnmarshalJSON(b []byte) error {
reader := bytes.NewBuffer(b)
return jsonpbUnmarshaller.Unmarshal(reader, r)
}
func (r *ResponseQuery) MarshalJSON() ([]byte, error) {
s, err := jsonpbMarshaller.MarshalToString(r)
return []byte(s), err
}
func (r *ResponseQuery) UnmarshalJSON(b []byte) error {
reader := bytes.NewBuffer(b)
return jsonpbUnmarshaller.Unmarshal(reader, r)
}
func (r *ResponseCommit) MarshalJSON() ([]byte, error) {
s, err := jsonpbMarshaller.MarshalToString(r)
return []byte(s), err
}
func (r *ResponseCommit) UnmarshalJSON(b []byte) error {
reader := bytes.NewBuffer(b)
return jsonpbUnmarshaller.Unmarshal(reader, r)
}
func (r *EventAttribute) MarshalJSON() ([]byte, error) {
s, err := jsonpbMarshaller.MarshalToString(r)
return []byte(s), err
}
func (r *EventAttribute) UnmarshalJSON(b []byte) error {
reader := bytes.NewBuffer(b)
return jsonpbUnmarshaller.Unmarshal(reader, r)
}
// Some compile time assertions to ensure we don't
// have accidental runtime surprises later on.
// jsonEncodingRoundTripper ensures that asserted
// interfaces implement both MarshalJSON and UnmarshalJSON
type jsonRoundTripper interface {
json.Marshaler
json.Unmarshaler
}
var _ jsonRoundTripper = (*ResponseCommit)(nil)
var _ jsonRoundTripper = (*ResponseQuery)(nil)
var _ jsonRoundTripper = (*ExecTxResult)(nil)
var _ jsonRoundTripper = (*ResponseCheckTx)(nil)
var _ jsonRoundTripper = (*EventAttribute)(nil)
// deterministicExecTxResult constructs a copy of response that omits
// non-deterministic fields. The input response is not modified.
func deterministicExecTxResult(response *ExecTxResult) *ExecTxResult {
return &ExecTxResult{
Code: response.Code,
Data: response.Data,
GasWanted: response.GasWanted,
GasUsed: response.GasUsed,
}
}
// MarshalTxResults encodes the the TxResults as a list of byte
// slices. It strips off the non-deterministic pieces of the TxResults
// so that the resulting data can be used for hash comparisons and used
// in Merkle proofs.
func MarshalTxResults(r []*ExecTxResult) ([][]byte, error) {
s := make([][]byte, len(r))
for i, e := range r {
d := deterministicExecTxResult(e)
b, err := d.Marshal()
if err != nil {
return nil, err
}
s[i] = b
}
return s, nil
}
// -----------------------------------------------
// construct Result data
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: tendermint/abci/types.proto
package types
import (
context "context"
fmt "fmt"
crypto "github.com/cometbft/cometbft/proto/tendermint/crypto"
types1 "github.com/cometbft/cometbft/proto/tendermint/types"
_ "github.com/cosmos/gogoproto/gogoproto"
grpc1 "github.com/cosmos/gogoproto/grpc"
proto "github.com/cosmos/gogoproto/proto"
_ "github.com/cosmos/gogoproto/types"
github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
io "io"
math "math"
math_bits "math/bits"
time "time"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
var _ = time.Kitchen
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
type CheckTxType int32
const (
CheckTxType_New CheckTxType = 0
CheckTxType_Recheck CheckTxType = 1
)
var CheckTxType_name = map[int32]string{
0: "NEW",
1: "RECHECK",
}
var CheckTxType_value = map[string]int32{
"NEW": 0,
"RECHECK": 1,
}
func (x CheckTxType) String() string {
return proto.EnumName(CheckTxType_name, int32(x))
}
func (CheckTxType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{0}
}
type MisbehaviorType int32
const (
MisbehaviorType_UNKNOWN MisbehaviorType = 0
MisbehaviorType_DUPLICATE_VOTE MisbehaviorType = 1
MisbehaviorType_LIGHT_CLIENT_ATTACK MisbehaviorType = 2
)
var MisbehaviorType_name = map[int32]string{
0: "UNKNOWN",
1: "DUPLICATE_VOTE",
2: "LIGHT_CLIENT_ATTACK",
}
var MisbehaviorType_value = map[string]int32{
"UNKNOWN": 0,
"DUPLICATE_VOTE": 1,
"LIGHT_CLIENT_ATTACK": 2,
}
func (x MisbehaviorType) String() string {
return proto.EnumName(MisbehaviorType_name, int32(x))
}
func (MisbehaviorType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{1}
}
type ResponseOfferSnapshot_Result int32
const (
ResponseOfferSnapshot_UNKNOWN ResponseOfferSnapshot_Result = 0
ResponseOfferSnapshot_ACCEPT ResponseOfferSnapshot_Result = 1
ResponseOfferSnapshot_ABORT ResponseOfferSnapshot_Result = 2
ResponseOfferSnapshot_REJECT ResponseOfferSnapshot_Result = 3
ResponseOfferSnapshot_REJECT_FORMAT ResponseOfferSnapshot_Result = 4
ResponseOfferSnapshot_REJECT_SENDER ResponseOfferSnapshot_Result = 5
)
var ResponseOfferSnapshot_Result_name = map[int32]string{
0: "UNKNOWN",
1: "ACCEPT",
2: "ABORT",
3: "REJECT",
4: "REJECT_FORMAT",
5: "REJECT_SENDER",
}
var ResponseOfferSnapshot_Result_value = map[string]int32{
"UNKNOWN": 0,
"ACCEPT": 1,
"ABORT": 2,
"REJECT": 3,
"REJECT_FORMAT": 4,
"REJECT_SENDER": 5,
}
func (x ResponseOfferSnapshot_Result) String() string {
return proto.EnumName(ResponseOfferSnapshot_Result_name, int32(x))
}
func (ResponseOfferSnapshot_Result) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{27, 0}
}
type ResponseApplySnapshotChunk_Result int32
const (
ResponseApplySnapshotChunk_UNKNOWN ResponseApplySnapshotChunk_Result = 0
ResponseApplySnapshotChunk_ACCEPT ResponseApplySnapshotChunk_Result = 1
ResponseApplySnapshotChunk_ABORT ResponseApplySnapshotChunk_Result = 2
ResponseApplySnapshotChunk_RETRY ResponseApplySnapshotChunk_Result = 3
ResponseApplySnapshotChunk_RETRY_SNAPSHOT ResponseApplySnapshotChunk_Result = 4
ResponseApplySnapshotChunk_REJECT_SNAPSHOT ResponseApplySnapshotChunk_Result = 5
)
var ResponseApplySnapshotChunk_Result_name = map[int32]string{
0: "UNKNOWN",
1: "ACCEPT",
2: "ABORT",
3: "RETRY",
4: "RETRY_SNAPSHOT",
5: "REJECT_SNAPSHOT",
}
var ResponseApplySnapshotChunk_Result_value = map[string]int32{
"UNKNOWN": 0,
"ACCEPT": 1,
"ABORT": 2,
"RETRY": 3,
"RETRY_SNAPSHOT": 4,
"REJECT_SNAPSHOT": 5,
}
func (x ResponseApplySnapshotChunk_Result) String() string {
return proto.EnumName(ResponseApplySnapshotChunk_Result_name, int32(x))
}
func (ResponseApplySnapshotChunk_Result) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{29, 0}
}
type ResponseProcessProposal_ProposalStatus int32
const (
ResponseProcessProposal_UNKNOWN ResponseProcessProposal_ProposalStatus = 0
ResponseProcessProposal_ACCEPT ResponseProcessProposal_ProposalStatus = 1
ResponseProcessProposal_REJECT ResponseProcessProposal_ProposalStatus = 2
)
var ResponseProcessProposal_ProposalStatus_name = map[int32]string{
0: "UNKNOWN",
1: "ACCEPT",
2: "REJECT",
}
var ResponseProcessProposal_ProposalStatus_value = map[string]int32{
"UNKNOWN": 0,
"ACCEPT": 1,
"REJECT": 2,
}
func (x ResponseProcessProposal_ProposalStatus) String() string {
return proto.EnumName(ResponseProcessProposal_ProposalStatus_name, int32(x))
}
func (ResponseProcessProposal_ProposalStatus) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{31, 0}
}
type ResponseVerifyVoteExtension_VerifyStatus int32
const (
ResponseVerifyVoteExtension_UNKNOWN ResponseVerifyVoteExtension_VerifyStatus = 0
ResponseVerifyVoteExtension_ACCEPT ResponseVerifyVoteExtension_VerifyStatus = 1
// Rejecting the vote extension will reject the entire precommit by the sender.
// Incorrectly implementing this thus has liveness implications as it may affect
// CometBFT's ability to receive 2/3+ valid votes to finalize the block.
// Honest nodes should never be rejected.
ResponseVerifyVoteExtension_REJECT ResponseVerifyVoteExtension_VerifyStatus = 2
)
var ResponseVerifyVoteExtension_VerifyStatus_name = map[int32]string{
0: "UNKNOWN",
1: "ACCEPT",
2: "REJECT",
}
var ResponseVerifyVoteExtension_VerifyStatus_value = map[string]int32{
"UNKNOWN": 0,
"ACCEPT": 1,
"REJECT": 2,
}
func (x ResponseVerifyVoteExtension_VerifyStatus) String() string {
return proto.EnumName(ResponseVerifyVoteExtension_VerifyStatus_name, int32(x))
}
func (ResponseVerifyVoteExtension_VerifyStatus) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{33, 0}
}
type Request struct {
// Types that are valid to be assigned to Value:
// *Request_Echo
// *Request_Flush
// *Request_Info
// *Request_InitChain
// *Request_Query
// *Request_CheckTx
// *Request_Commit
// *Request_ListSnapshots
// *Request_OfferSnapshot
// *Request_LoadSnapshotChunk
// *Request_ApplySnapshotChunk
// *Request_PrepareProposal
// *Request_ProcessProposal
// *Request_ExtendVote
// *Request_VerifyVoteExtension
// *Request_FinalizeBlock
Value isRequest_Value `protobuf_oneof:"value"`
}
func (m *Request) Reset() { *m = Request{} }
func (m *Request) String() string { return proto.CompactTextString(m) }
func (*Request) ProtoMessage() {}
func (*Request) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{0}
}
func (m *Request) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Request.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Request) XXX_Merge(src proto.Message) {
xxx_messageInfo_Request.Merge(m, src)
}
func (m *Request) XXX_Size() int {
return m.Size()
}
func (m *Request) XXX_DiscardUnknown() {
xxx_messageInfo_Request.DiscardUnknown(m)
}
var xxx_messageInfo_Request proto.InternalMessageInfo
type isRequest_Value interface {
isRequest_Value()
MarshalTo([]byte) (int, error)
Size() int
}
type Request_Echo struct {
Echo *RequestEcho `protobuf:"bytes,1,opt,name=echo,proto3,oneof" json:"echo,omitempty"`
}
type Request_Flush struct {
Flush *RequestFlush `protobuf:"bytes,2,opt,name=flush,proto3,oneof" json:"flush,omitempty"`
}
type Request_Info struct {
Info *RequestInfo `protobuf:"bytes,3,opt,name=info,proto3,oneof" json:"info,omitempty"`
}
type Request_InitChain struct {
InitChain *RequestInitChain `protobuf:"bytes,5,opt,name=init_chain,json=initChain,proto3,oneof" json:"init_chain,omitempty"`
}
type Request_Query struct {
Query *RequestQuery `protobuf:"bytes,6,opt,name=query,proto3,oneof" json:"query,omitempty"`
}
type Request_CheckTx struct {
CheckTx *RequestCheckTx `protobuf:"bytes,8,opt,name=check_tx,json=checkTx,proto3,oneof" json:"check_tx,omitempty"`
}
type Request_Commit struct {
Commit *RequestCommit `protobuf:"bytes,11,opt,name=commit,proto3,oneof" json:"commit,omitempty"`
}
type Request_ListSnapshots struct {
ListSnapshots *RequestListSnapshots `protobuf:"bytes,12,opt,name=list_snapshots,json=listSnapshots,proto3,oneof" json:"list_snapshots,omitempty"`
}
type Request_OfferSnapshot struct {
OfferSnapshot *RequestOfferSnapshot `protobuf:"bytes,13,opt,name=offer_snapshot,json=offerSnapshot,proto3,oneof" json:"offer_snapshot,omitempty"`
}
type Request_LoadSnapshotChunk struct {
LoadSnapshotChunk *RequestLoadSnapshotChunk `protobuf:"bytes,14,opt,name=load_snapshot_chunk,json=loadSnapshotChunk,proto3,oneof" json:"load_snapshot_chunk,omitempty"`
}
type Request_ApplySnapshotChunk struct {
ApplySnapshotChunk *RequestApplySnapshotChunk `protobuf:"bytes,15,opt,name=apply_snapshot_chunk,json=applySnapshotChunk,proto3,oneof" json:"apply_snapshot_chunk,omitempty"`
}
type Request_PrepareProposal struct {
PrepareProposal *RequestPrepareProposal `protobuf:"bytes,16,opt,name=prepare_proposal,json=prepareProposal,proto3,oneof" json:"prepare_proposal,omitempty"`
}
type Request_ProcessProposal struct {
ProcessProposal *RequestProcessProposal `protobuf:"bytes,17,opt,name=process_proposal,json=processProposal,proto3,oneof" json:"process_proposal,omitempty"`
}
type Request_ExtendVote struct {
ExtendVote *RequestExtendVote `protobuf:"bytes,18,opt,name=extend_vote,json=extendVote,proto3,oneof" json:"extend_vote,omitempty"`
}
type Request_VerifyVoteExtension struct {
VerifyVoteExtension *RequestVerifyVoteExtension `protobuf:"bytes,19,opt,name=verify_vote_extension,json=verifyVoteExtension,proto3,oneof" json:"verify_vote_extension,omitempty"`
}
type Request_FinalizeBlock struct {
FinalizeBlock *RequestFinalizeBlock `protobuf:"bytes,20,opt,name=finalize_block,json=finalizeBlock,proto3,oneof" json:"finalize_block,omitempty"`
}
func (*Request_Echo) isRequest_Value() {}
func (*Request_Flush) isRequest_Value() {}
func (*Request_Info) isRequest_Value() {}
func (*Request_InitChain) isRequest_Value() {}
func (*Request_Query) isRequest_Value() {}
func (*Request_CheckTx) isRequest_Value() {}
func (*Request_Commit) isRequest_Value() {}
func (*Request_ListSnapshots) isRequest_Value() {}
func (*Request_OfferSnapshot) isRequest_Value() {}
func (*Request_LoadSnapshotChunk) isRequest_Value() {}
func (*Request_ApplySnapshotChunk) isRequest_Value() {}
func (*Request_PrepareProposal) isRequest_Value() {}
func (*Request_ProcessProposal) isRequest_Value() {}
func (*Request_ExtendVote) isRequest_Value() {}
func (*Request_VerifyVoteExtension) isRequest_Value() {}
func (*Request_FinalizeBlock) isRequest_Value() {}
func (m *Request) GetValue() isRequest_Value {
if m != nil {
return m.Value
}
return nil
}
func (m *Request) GetEcho() *RequestEcho {
if x, ok := m.GetValue().(*Request_Echo); ok {
return x.Echo
}
return nil
}
func (m *Request) GetFlush() *RequestFlush {
if x, ok := m.GetValue().(*Request_Flush); ok {
return x.Flush
}
return nil
}
func (m *Request) GetInfo() *RequestInfo {
if x, ok := m.GetValue().(*Request_Info); ok {
return x.Info
}
return nil
}
func (m *Request) GetInitChain() *RequestInitChain {
if x, ok := m.GetValue().(*Request_InitChain); ok {
return x.InitChain
}
return nil
}
func (m *Request) GetQuery() *RequestQuery {
if x, ok := m.GetValue().(*Request_Query); ok {
return x.Query
}
return nil
}
func (m *Request) GetCheckTx() *RequestCheckTx {
if x, ok := m.GetValue().(*Request_CheckTx); ok {
return x.CheckTx
}
return nil
}
func (m *Request) GetCommit() *RequestCommit {
if x, ok := m.GetValue().(*Request_Commit); ok {
return x.Commit
}
return nil
}
func (m *Request) GetListSnapshots() *RequestListSnapshots {
if x, ok := m.GetValue().(*Request_ListSnapshots); ok {
return x.ListSnapshots
}
return nil
}
func (m *Request) GetOfferSnapshot() *RequestOfferSnapshot {
if x, ok := m.GetValue().(*Request_OfferSnapshot); ok {
return x.OfferSnapshot
}
return nil
}
func (m *Request) GetLoadSnapshotChunk() *RequestLoadSnapshotChunk {
if x, ok := m.GetValue().(*Request_LoadSnapshotChunk); ok {
return x.LoadSnapshotChunk
}
return nil
}
func (m *Request) GetApplySnapshotChunk() *RequestApplySnapshotChunk {
if x, ok := m.GetValue().(*Request_ApplySnapshotChunk); ok {
return x.ApplySnapshotChunk
}
return nil
}
func (m *Request) GetPrepareProposal() *RequestPrepareProposal {
if x, ok := m.GetValue().(*Request_PrepareProposal); ok {
return x.PrepareProposal
}
return nil
}
func (m *Request) GetProcessProposal() *RequestProcessProposal {
if x, ok := m.GetValue().(*Request_ProcessProposal); ok {
return x.ProcessProposal
}
return nil
}
func (m *Request) GetExtendVote() *RequestExtendVote {
if x, ok := m.GetValue().(*Request_ExtendVote); ok {
return x.ExtendVote
}
return nil
}
func (m *Request) GetVerifyVoteExtension() *RequestVerifyVoteExtension {
if x, ok := m.GetValue().(*Request_VerifyVoteExtension); ok {
return x.VerifyVoteExtension
}
return nil
}
func (m *Request) GetFinalizeBlock() *RequestFinalizeBlock {
if x, ok := m.GetValue().(*Request_FinalizeBlock); ok {
return x.FinalizeBlock
}
return nil
}
// XXX_OneofWrappers is for the internal use of the proto package.
func (*Request) XXX_OneofWrappers() []interface{} {
return []interface{}{
(*Request_Echo)(nil),
(*Request_Flush)(nil),
(*Request_Info)(nil),
(*Request_InitChain)(nil),
(*Request_Query)(nil),
(*Request_CheckTx)(nil),
(*Request_Commit)(nil),
(*Request_ListSnapshots)(nil),
(*Request_OfferSnapshot)(nil),
(*Request_LoadSnapshotChunk)(nil),
(*Request_ApplySnapshotChunk)(nil),
(*Request_PrepareProposal)(nil),
(*Request_ProcessProposal)(nil),
(*Request_ExtendVote)(nil),
(*Request_VerifyVoteExtension)(nil),
(*Request_FinalizeBlock)(nil),
}
}
type RequestEcho struct {
Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
}
func (m *RequestEcho) Reset() { *m = RequestEcho{} }
func (m *RequestEcho) String() string { return proto.CompactTextString(m) }
func (*RequestEcho) ProtoMessage() {}
func (*RequestEcho) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{1}
}
func (m *RequestEcho) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestEcho) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestEcho.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestEcho) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestEcho.Merge(m, src)
}
func (m *RequestEcho) XXX_Size() int {
return m.Size()
}
func (m *RequestEcho) XXX_DiscardUnknown() {
xxx_messageInfo_RequestEcho.DiscardUnknown(m)
}
var xxx_messageInfo_RequestEcho proto.InternalMessageInfo
func (m *RequestEcho) GetMessage() string {
if m != nil {
return m.Message
}
return ""
}
type RequestFlush struct {
}
func (m *RequestFlush) Reset() { *m = RequestFlush{} }
func (m *RequestFlush) String() string { return proto.CompactTextString(m) }
func (*RequestFlush) ProtoMessage() {}
func (*RequestFlush) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{2}
}
func (m *RequestFlush) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestFlush) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestFlush.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestFlush) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestFlush.Merge(m, src)
}
func (m *RequestFlush) XXX_Size() int {
return m.Size()
}
func (m *RequestFlush) XXX_DiscardUnknown() {
xxx_messageInfo_RequestFlush.DiscardUnknown(m)
}
var xxx_messageInfo_RequestFlush proto.InternalMessageInfo
type RequestInfo struct {
Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"`
BlockVersion uint64 `protobuf:"varint,2,opt,name=block_version,json=blockVersion,proto3" json:"block_version,omitempty"`
P2PVersion uint64 `protobuf:"varint,3,opt,name=p2p_version,json=p2pVersion,proto3" json:"p2p_version,omitempty"`
AbciVersion string `protobuf:"bytes,4,opt,name=abci_version,json=abciVersion,proto3" json:"abci_version,omitempty"`
}
func (m *RequestInfo) Reset() { *m = RequestInfo{} }
func (m *RequestInfo) String() string { return proto.CompactTextString(m) }
func (*RequestInfo) ProtoMessage() {}
func (*RequestInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{3}
}
func (m *RequestInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestInfo.Merge(m, src)
}
func (m *RequestInfo) XXX_Size() int {
return m.Size()
}
func (m *RequestInfo) XXX_DiscardUnknown() {
xxx_messageInfo_RequestInfo.DiscardUnknown(m)
}
var xxx_messageInfo_RequestInfo proto.InternalMessageInfo
func (m *RequestInfo) GetVersion() string {
if m != nil {
return m.Version
}
return ""
}
func (m *RequestInfo) GetBlockVersion() uint64 {
if m != nil {
return m.BlockVersion
}
return 0
}
func (m *RequestInfo) GetP2PVersion() uint64 {
if m != nil {
return m.P2PVersion
}
return 0
}
func (m *RequestInfo) GetAbciVersion() string {
if m != nil {
return m.AbciVersion
}
return ""
}
type RequestInitChain struct {
Time time.Time `protobuf:"bytes,1,opt,name=time,proto3,stdtime" json:"time"`
ChainId string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"`
ConsensusParams *types1.ConsensusParams `protobuf:"bytes,3,opt,name=consensus_params,json=consensusParams,proto3" json:"consensus_params,omitempty"`
Validators []ValidatorUpdate `protobuf:"bytes,4,rep,name=validators,proto3" json:"validators"`
AppStateBytes []byte `protobuf:"bytes,5,opt,name=app_state_bytes,json=appStateBytes,proto3" json:"app_state_bytes,omitempty"`
InitialHeight int64 `protobuf:"varint,6,opt,name=initial_height,json=initialHeight,proto3" json:"initial_height,omitempty"`
}
func (m *RequestInitChain) Reset() { *m = RequestInitChain{} }
func (m *RequestInitChain) String() string { return proto.CompactTextString(m) }
func (*RequestInitChain) ProtoMessage() {}
func (*RequestInitChain) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{4}
}
func (m *RequestInitChain) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestInitChain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestInitChain.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestInitChain) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestInitChain.Merge(m, src)
}
func (m *RequestInitChain) XXX_Size() int {
return m.Size()
}
func (m *RequestInitChain) XXX_DiscardUnknown() {
xxx_messageInfo_RequestInitChain.DiscardUnknown(m)
}
var xxx_messageInfo_RequestInitChain proto.InternalMessageInfo
func (m *RequestInitChain) GetTime() time.Time {
if m != nil {
return m.Time
}
return time.Time{}
}
func (m *RequestInitChain) GetChainId() string {
if m != nil {
return m.ChainId
}
return ""
}
func (m *RequestInitChain) GetConsensusParams() *types1.ConsensusParams {
if m != nil {
return m.ConsensusParams
}
return nil
}
func (m *RequestInitChain) GetValidators() []ValidatorUpdate {
if m != nil {
return m.Validators
}
return nil
}
func (m *RequestInitChain) GetAppStateBytes() []byte {
if m != nil {
return m.AppStateBytes
}
return nil
}
func (m *RequestInitChain) GetInitialHeight() int64 {
if m != nil {
return m.InitialHeight
}
return 0
}
type RequestQuery struct {
Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"`
Prove bool `protobuf:"varint,4,opt,name=prove,proto3" json:"prove,omitempty"`
}
func (m *RequestQuery) Reset() { *m = RequestQuery{} }
func (m *RequestQuery) String() string { return proto.CompactTextString(m) }
func (*RequestQuery) ProtoMessage() {}
func (*RequestQuery) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{5}
}
func (m *RequestQuery) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestQuery) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestQuery.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestQuery) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestQuery.Merge(m, src)
}
func (m *RequestQuery) XXX_Size() int {
return m.Size()
}
func (m *RequestQuery) XXX_DiscardUnknown() {
xxx_messageInfo_RequestQuery.DiscardUnknown(m)
}
var xxx_messageInfo_RequestQuery proto.InternalMessageInfo
func (m *RequestQuery) GetData() []byte {
if m != nil {
return m.Data
}
return nil
}
func (m *RequestQuery) GetPath() string {
if m != nil {
return m.Path
}
return ""
}
func (m *RequestQuery) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *RequestQuery) GetProve() bool {
if m != nil {
return m.Prove
}
return false
}
type RequestCheckTx struct {
Tx []byte `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"`
Type CheckTxType `protobuf:"varint,2,opt,name=type,proto3,enum=tendermint.abci.CheckTxType" json:"type,omitempty"`
}
func (m *RequestCheckTx) Reset() { *m = RequestCheckTx{} }
func (m *RequestCheckTx) String() string { return proto.CompactTextString(m) }
func (*RequestCheckTx) ProtoMessage() {}
func (*RequestCheckTx) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{6}
}
func (m *RequestCheckTx) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestCheckTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestCheckTx.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestCheckTx) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestCheckTx.Merge(m, src)
}
func (m *RequestCheckTx) XXX_Size() int {
return m.Size()
}
func (m *RequestCheckTx) XXX_DiscardUnknown() {
xxx_messageInfo_RequestCheckTx.DiscardUnknown(m)
}
var xxx_messageInfo_RequestCheckTx proto.InternalMessageInfo
func (m *RequestCheckTx) GetTx() []byte {
if m != nil {
return m.Tx
}
return nil
}
func (m *RequestCheckTx) GetType() CheckTxType {
if m != nil {
return m.Type
}
return CheckTxType_New
}
type RequestCommit struct {
}
func (m *RequestCommit) Reset() { *m = RequestCommit{} }
func (m *RequestCommit) String() string { return proto.CompactTextString(m) }
func (*RequestCommit) ProtoMessage() {}
func (*RequestCommit) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{7}
}
func (m *RequestCommit) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestCommit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestCommit.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestCommit) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestCommit.Merge(m, src)
}
func (m *RequestCommit) XXX_Size() int {
return m.Size()
}
func (m *RequestCommit) XXX_DiscardUnknown() {
xxx_messageInfo_RequestCommit.DiscardUnknown(m)
}
var xxx_messageInfo_RequestCommit proto.InternalMessageInfo
// lists available snapshots
type RequestListSnapshots struct {
}
func (m *RequestListSnapshots) Reset() { *m = RequestListSnapshots{} }
func (m *RequestListSnapshots) String() string { return proto.CompactTextString(m) }
func (*RequestListSnapshots) ProtoMessage() {}
func (*RequestListSnapshots) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{8}
}
func (m *RequestListSnapshots) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestListSnapshots) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestListSnapshots.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestListSnapshots) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestListSnapshots.Merge(m, src)
}
func (m *RequestListSnapshots) XXX_Size() int {
return m.Size()
}
func (m *RequestListSnapshots) XXX_DiscardUnknown() {
xxx_messageInfo_RequestListSnapshots.DiscardUnknown(m)
}
var xxx_messageInfo_RequestListSnapshots proto.InternalMessageInfo
// offers a snapshot to the application
type RequestOfferSnapshot struct {
Snapshot *Snapshot `protobuf:"bytes,1,opt,name=snapshot,proto3" json:"snapshot,omitempty"`
AppHash []byte `protobuf:"bytes,2,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"`
}
func (m *RequestOfferSnapshot) Reset() { *m = RequestOfferSnapshot{} }
func (m *RequestOfferSnapshot) String() string { return proto.CompactTextString(m) }
func (*RequestOfferSnapshot) ProtoMessage() {}
func (*RequestOfferSnapshot) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{9}
}
func (m *RequestOfferSnapshot) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestOfferSnapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestOfferSnapshot.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestOfferSnapshot) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestOfferSnapshot.Merge(m, src)
}
func (m *RequestOfferSnapshot) XXX_Size() int {
return m.Size()
}
func (m *RequestOfferSnapshot) XXX_DiscardUnknown() {
xxx_messageInfo_RequestOfferSnapshot.DiscardUnknown(m)
}
var xxx_messageInfo_RequestOfferSnapshot proto.InternalMessageInfo
func (m *RequestOfferSnapshot) GetSnapshot() *Snapshot {
if m != nil {
return m.Snapshot
}
return nil
}
func (m *RequestOfferSnapshot) GetAppHash() []byte {
if m != nil {
return m.AppHash
}
return nil
}
// loads a snapshot chunk
type RequestLoadSnapshotChunk struct {
Height uint64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"`
Format uint32 `protobuf:"varint,2,opt,name=format,proto3" json:"format,omitempty"`
Chunk uint32 `protobuf:"varint,3,opt,name=chunk,proto3" json:"chunk,omitempty"`
}
func (m *RequestLoadSnapshotChunk) Reset() { *m = RequestLoadSnapshotChunk{} }
func (m *RequestLoadSnapshotChunk) String() string { return proto.CompactTextString(m) }
func (*RequestLoadSnapshotChunk) ProtoMessage() {}
func (*RequestLoadSnapshotChunk) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{10}
}
func (m *RequestLoadSnapshotChunk) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestLoadSnapshotChunk) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestLoadSnapshotChunk.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestLoadSnapshotChunk) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestLoadSnapshotChunk.Merge(m, src)
}
func (m *RequestLoadSnapshotChunk) XXX_Size() int {
return m.Size()
}
func (m *RequestLoadSnapshotChunk) XXX_DiscardUnknown() {
xxx_messageInfo_RequestLoadSnapshotChunk.DiscardUnknown(m)
}
var xxx_messageInfo_RequestLoadSnapshotChunk proto.InternalMessageInfo
func (m *RequestLoadSnapshotChunk) GetHeight() uint64 {
if m != nil {
return m.Height
}
return 0
}
func (m *RequestLoadSnapshotChunk) GetFormat() uint32 {
if m != nil {
return m.Format
}
return 0
}
func (m *RequestLoadSnapshotChunk) GetChunk() uint32 {
if m != nil {
return m.Chunk
}
return 0
}
// Applies a snapshot chunk
type RequestApplySnapshotChunk struct {
Index uint32 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Chunk []byte `protobuf:"bytes,2,opt,name=chunk,proto3" json:"chunk,omitempty"`
Sender string `protobuf:"bytes,3,opt,name=sender,proto3" json:"sender,omitempty"`
}
func (m *RequestApplySnapshotChunk) Reset() { *m = RequestApplySnapshotChunk{} }
func (m *RequestApplySnapshotChunk) String() string { return proto.CompactTextString(m) }
func (*RequestApplySnapshotChunk) ProtoMessage() {}
func (*RequestApplySnapshotChunk) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{11}
}
func (m *RequestApplySnapshotChunk) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestApplySnapshotChunk) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestApplySnapshotChunk.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestApplySnapshotChunk) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestApplySnapshotChunk.Merge(m, src)
}
func (m *RequestApplySnapshotChunk) XXX_Size() int {
return m.Size()
}
func (m *RequestApplySnapshotChunk) XXX_DiscardUnknown() {
xxx_messageInfo_RequestApplySnapshotChunk.DiscardUnknown(m)
}
var xxx_messageInfo_RequestApplySnapshotChunk proto.InternalMessageInfo
func (m *RequestApplySnapshotChunk) GetIndex() uint32 {
if m != nil {
return m.Index
}
return 0
}
func (m *RequestApplySnapshotChunk) GetChunk() []byte {
if m != nil {
return m.Chunk
}
return nil
}
func (m *RequestApplySnapshotChunk) GetSender() string {
if m != nil {
return m.Sender
}
return ""
}
type RequestPrepareProposal struct {
// the modified transactions cannot exceed this size.
MaxTxBytes int64 `protobuf:"varint,1,opt,name=max_tx_bytes,json=maxTxBytes,proto3" json:"max_tx_bytes,omitempty"`
// txs is an array of transactions that will be included in a block,
// sent to the app for possible modifications.
Txs [][]byte `protobuf:"bytes,2,rep,name=txs,proto3" json:"txs,omitempty"`
LocalLastCommit ExtendedCommitInfo `protobuf:"bytes,3,opt,name=local_last_commit,json=localLastCommit,proto3" json:"local_last_commit"`
Misbehavior []Misbehavior `protobuf:"bytes,4,rep,name=misbehavior,proto3" json:"misbehavior"`
Height int64 `protobuf:"varint,5,opt,name=height,proto3" json:"height,omitempty"`
Time time.Time `protobuf:"bytes,6,opt,name=time,proto3,stdtime" json:"time"`
NextValidatorsHash []byte `protobuf:"bytes,7,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"`
// address of the public key of the validator proposing the block.
ProposerAddress []byte `protobuf:"bytes,8,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"`
}
func (m *RequestPrepareProposal) Reset() { *m = RequestPrepareProposal{} }
func (m *RequestPrepareProposal) String() string { return proto.CompactTextString(m) }
func (*RequestPrepareProposal) ProtoMessage() {}
func (*RequestPrepareProposal) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{12}
}
func (m *RequestPrepareProposal) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestPrepareProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestPrepareProposal.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestPrepareProposal) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestPrepareProposal.Merge(m, src)
}
func (m *RequestPrepareProposal) XXX_Size() int {
return m.Size()
}
func (m *RequestPrepareProposal) XXX_DiscardUnknown() {
xxx_messageInfo_RequestPrepareProposal.DiscardUnknown(m)
}
var xxx_messageInfo_RequestPrepareProposal proto.InternalMessageInfo
func (m *RequestPrepareProposal) GetMaxTxBytes() int64 {
if m != nil {
return m.MaxTxBytes
}
return 0
}
func (m *RequestPrepareProposal) GetTxs() [][]byte {
if m != nil {
return m.Txs
}
return nil
}
func (m *RequestPrepareProposal) GetLocalLastCommit() ExtendedCommitInfo {
if m != nil {
return m.LocalLastCommit
}
return ExtendedCommitInfo{}
}
func (m *RequestPrepareProposal) GetMisbehavior() []Misbehavior {
if m != nil {
return m.Misbehavior
}
return nil
}
func (m *RequestPrepareProposal) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *RequestPrepareProposal) GetTime() time.Time {
if m != nil {
return m.Time
}
return time.Time{}
}
func (m *RequestPrepareProposal) GetNextValidatorsHash() []byte {
if m != nil {
return m.NextValidatorsHash
}
return nil
}
func (m *RequestPrepareProposal) GetProposerAddress() []byte {
if m != nil {
return m.ProposerAddress
}
return nil
}
type RequestProcessProposal struct {
Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"`
ProposedLastCommit CommitInfo `protobuf:"bytes,2,opt,name=proposed_last_commit,json=proposedLastCommit,proto3" json:"proposed_last_commit"`
Misbehavior []Misbehavior `protobuf:"bytes,3,rep,name=misbehavior,proto3" json:"misbehavior"`
// hash is the merkle root hash of the fields of the proposed block.
Hash []byte `protobuf:"bytes,4,opt,name=hash,proto3" json:"hash,omitempty"`
Height int64 `protobuf:"varint,5,opt,name=height,proto3" json:"height,omitempty"`
Time time.Time `protobuf:"bytes,6,opt,name=time,proto3,stdtime" json:"time"`
NextValidatorsHash []byte `protobuf:"bytes,7,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"`
// address of the public key of the original proposer of the block.
ProposerAddress []byte `protobuf:"bytes,8,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"`
}
func (m *RequestProcessProposal) Reset() { *m = RequestProcessProposal{} }
func (m *RequestProcessProposal) String() string { return proto.CompactTextString(m) }
func (*RequestProcessProposal) ProtoMessage() {}
func (*RequestProcessProposal) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{13}
}
func (m *RequestProcessProposal) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestProcessProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestProcessProposal.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestProcessProposal) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestProcessProposal.Merge(m, src)
}
func (m *RequestProcessProposal) XXX_Size() int {
return m.Size()
}
func (m *RequestProcessProposal) XXX_DiscardUnknown() {
xxx_messageInfo_RequestProcessProposal.DiscardUnknown(m)
}
var xxx_messageInfo_RequestProcessProposal proto.InternalMessageInfo
func (m *RequestProcessProposal) GetTxs() [][]byte {
if m != nil {
return m.Txs
}
return nil
}
func (m *RequestProcessProposal) GetProposedLastCommit() CommitInfo {
if m != nil {
return m.ProposedLastCommit
}
return CommitInfo{}
}
func (m *RequestProcessProposal) GetMisbehavior() []Misbehavior {
if m != nil {
return m.Misbehavior
}
return nil
}
func (m *RequestProcessProposal) GetHash() []byte {
if m != nil {
return m.Hash
}
return nil
}
func (m *RequestProcessProposal) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *RequestProcessProposal) GetTime() time.Time {
if m != nil {
return m.Time
}
return time.Time{}
}
func (m *RequestProcessProposal) GetNextValidatorsHash() []byte {
if m != nil {
return m.NextValidatorsHash
}
return nil
}
func (m *RequestProcessProposal) GetProposerAddress() []byte {
if m != nil {
return m.ProposerAddress
}
return nil
}
// Extends a vote with application-injected data
type RequestExtendVote struct {
// the hash of the block that this vote may be referring to
Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"`
// the height of the extended vote
Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"`
// info of the block that this vote may be referring to
Time time.Time `protobuf:"bytes,3,opt,name=time,proto3,stdtime" json:"time"`
Txs [][]byte `protobuf:"bytes,4,rep,name=txs,proto3" json:"txs,omitempty"`
ProposedLastCommit CommitInfo `protobuf:"bytes,5,opt,name=proposed_last_commit,json=proposedLastCommit,proto3" json:"proposed_last_commit"`
Misbehavior []Misbehavior `protobuf:"bytes,6,rep,name=misbehavior,proto3" json:"misbehavior"`
NextValidatorsHash []byte `protobuf:"bytes,7,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"`
// address of the public key of the original proposer of the block.
ProposerAddress []byte `protobuf:"bytes,8,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"`
}
func (m *RequestExtendVote) Reset() { *m = RequestExtendVote{} }
func (m *RequestExtendVote) String() string { return proto.CompactTextString(m) }
func (*RequestExtendVote) ProtoMessage() {}
func (*RequestExtendVote) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{14}
}
func (m *RequestExtendVote) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestExtendVote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestExtendVote.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestExtendVote) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestExtendVote.Merge(m, src)
}
func (m *RequestExtendVote) XXX_Size() int {
return m.Size()
}
func (m *RequestExtendVote) XXX_DiscardUnknown() {
xxx_messageInfo_RequestExtendVote.DiscardUnknown(m)
}
var xxx_messageInfo_RequestExtendVote proto.InternalMessageInfo
func (m *RequestExtendVote) GetHash() []byte {
if m != nil {
return m.Hash
}
return nil
}
func (m *RequestExtendVote) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *RequestExtendVote) GetTime() time.Time {
if m != nil {
return m.Time
}
return time.Time{}
}
func (m *RequestExtendVote) GetTxs() [][]byte {
if m != nil {
return m.Txs
}
return nil
}
func (m *RequestExtendVote) GetProposedLastCommit() CommitInfo {
if m != nil {
return m.ProposedLastCommit
}
return CommitInfo{}
}
func (m *RequestExtendVote) GetMisbehavior() []Misbehavior {
if m != nil {
return m.Misbehavior
}
return nil
}
func (m *RequestExtendVote) GetNextValidatorsHash() []byte {
if m != nil {
return m.NextValidatorsHash
}
return nil
}
func (m *RequestExtendVote) GetProposerAddress() []byte {
if m != nil {
return m.ProposerAddress
}
return nil
}
// Verify the vote extension
type RequestVerifyVoteExtension struct {
// the hash of the block that this received vote corresponds to
Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"`
// the validator that signed the vote extension
ValidatorAddress []byte `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"`
Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"`
VoteExtension []byte `protobuf:"bytes,4,opt,name=vote_extension,json=voteExtension,proto3" json:"vote_extension,omitempty"`
}
func (m *RequestVerifyVoteExtension) Reset() { *m = RequestVerifyVoteExtension{} }
func (m *RequestVerifyVoteExtension) String() string { return proto.CompactTextString(m) }
func (*RequestVerifyVoteExtension) ProtoMessage() {}
func (*RequestVerifyVoteExtension) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{15}
}
func (m *RequestVerifyVoteExtension) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestVerifyVoteExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestVerifyVoteExtension.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestVerifyVoteExtension) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestVerifyVoteExtension.Merge(m, src)
}
func (m *RequestVerifyVoteExtension) XXX_Size() int {
return m.Size()
}
func (m *RequestVerifyVoteExtension) XXX_DiscardUnknown() {
xxx_messageInfo_RequestVerifyVoteExtension.DiscardUnknown(m)
}
var xxx_messageInfo_RequestVerifyVoteExtension proto.InternalMessageInfo
func (m *RequestVerifyVoteExtension) GetHash() []byte {
if m != nil {
return m.Hash
}
return nil
}
func (m *RequestVerifyVoteExtension) GetValidatorAddress() []byte {
if m != nil {
return m.ValidatorAddress
}
return nil
}
func (m *RequestVerifyVoteExtension) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *RequestVerifyVoteExtension) GetVoteExtension() []byte {
if m != nil {
return m.VoteExtension
}
return nil
}
type RequestFinalizeBlock struct {
Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"`
DecidedLastCommit CommitInfo `protobuf:"bytes,2,opt,name=decided_last_commit,json=decidedLastCommit,proto3" json:"decided_last_commit"`
Misbehavior []Misbehavior `protobuf:"bytes,3,rep,name=misbehavior,proto3" json:"misbehavior"`
// hash is the merkle root hash of the fields of the decided block.
Hash []byte `protobuf:"bytes,4,opt,name=hash,proto3" json:"hash,omitempty"`
Height int64 `protobuf:"varint,5,opt,name=height,proto3" json:"height,omitempty"`
Time time.Time `protobuf:"bytes,6,opt,name=time,proto3,stdtime" json:"time"`
NextValidatorsHash []byte `protobuf:"bytes,7,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"`
// proposer_address is the address of the public key of the original proposer of the block.
ProposerAddress []byte `protobuf:"bytes,8,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"`
}
func (m *RequestFinalizeBlock) Reset() { *m = RequestFinalizeBlock{} }
func (m *RequestFinalizeBlock) String() string { return proto.CompactTextString(m) }
func (*RequestFinalizeBlock) ProtoMessage() {}
func (*RequestFinalizeBlock) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{16}
}
func (m *RequestFinalizeBlock) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RequestFinalizeBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RequestFinalizeBlock.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RequestFinalizeBlock) XXX_Merge(src proto.Message) {
xxx_messageInfo_RequestFinalizeBlock.Merge(m, src)
}
func (m *RequestFinalizeBlock) XXX_Size() int {
return m.Size()
}
func (m *RequestFinalizeBlock) XXX_DiscardUnknown() {
xxx_messageInfo_RequestFinalizeBlock.DiscardUnknown(m)
}
var xxx_messageInfo_RequestFinalizeBlock proto.InternalMessageInfo
func (m *RequestFinalizeBlock) GetTxs() [][]byte {
if m != nil {
return m.Txs
}
return nil
}
func (m *RequestFinalizeBlock) GetDecidedLastCommit() CommitInfo {
if m != nil {
return m.DecidedLastCommit
}
return CommitInfo{}
}
func (m *RequestFinalizeBlock) GetMisbehavior() []Misbehavior {
if m != nil {
return m.Misbehavior
}
return nil
}
func (m *RequestFinalizeBlock) GetHash() []byte {
if m != nil {
return m.Hash
}
return nil
}
func (m *RequestFinalizeBlock) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *RequestFinalizeBlock) GetTime() time.Time {
if m != nil {
return m.Time
}
return time.Time{}
}
func (m *RequestFinalizeBlock) GetNextValidatorsHash() []byte {
if m != nil {
return m.NextValidatorsHash
}
return nil
}
func (m *RequestFinalizeBlock) GetProposerAddress() []byte {
if m != nil {
return m.ProposerAddress
}
return nil
}
type Response struct {
// Types that are valid to be assigned to Value:
//
// *Response_Exception
// *Response_Echo
// *Response_Flush
// *Response_Info
// *Response_InitChain
// *Response_Query
// *Response_CheckTx
// *Response_Commit
// *Response_ListSnapshots
// *Response_OfferSnapshot
// *Response_LoadSnapshotChunk
// *Response_ApplySnapshotChunk
// *Response_PrepareProposal
// *Response_ProcessProposal
// *Response_ExtendVote
// *Response_VerifyVoteExtension
// *Response_FinalizeBlock
Value isResponse_Value `protobuf_oneof:"value"`
}
func (m *Response) Reset() { *m = Response{} }
func (m *Response) String() string { return proto.CompactTextString(m) }
func (*Response) ProtoMessage() {}
func (*Response) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{17}
}
func (m *Response) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Response.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Response) XXX_Merge(src proto.Message) {
xxx_messageInfo_Response.Merge(m, src)
}
func (m *Response) XXX_Size() int {
return m.Size()
}
func (m *Response) XXX_DiscardUnknown() {
xxx_messageInfo_Response.DiscardUnknown(m)
}
var xxx_messageInfo_Response proto.InternalMessageInfo
type isResponse_Value interface {
isResponse_Value()
MarshalTo([]byte) (int, error)
Size() int
}
type Response_Exception struct {
Exception *ResponseException `protobuf:"bytes,1,opt,name=exception,proto3,oneof" json:"exception,omitempty"`
}
type Response_Echo struct {
Echo *ResponseEcho `protobuf:"bytes,2,opt,name=echo,proto3,oneof" json:"echo,omitempty"`
}
type Response_Flush struct {
Flush *ResponseFlush `protobuf:"bytes,3,opt,name=flush,proto3,oneof" json:"flush,omitempty"`
}
type Response_Info struct {
Info *ResponseInfo `protobuf:"bytes,4,opt,name=info,proto3,oneof" json:"info,omitempty"`
}
type Response_InitChain struct {
InitChain *ResponseInitChain `protobuf:"bytes,6,opt,name=init_chain,json=initChain,proto3,oneof" json:"init_chain,omitempty"`
}
type Response_Query struct {
Query *ResponseQuery `protobuf:"bytes,7,opt,name=query,proto3,oneof" json:"query,omitempty"`
}
type Response_CheckTx struct {
CheckTx *ResponseCheckTx `protobuf:"bytes,9,opt,name=check_tx,json=checkTx,proto3,oneof" json:"check_tx,omitempty"`
}
type Response_Commit struct {
Commit *ResponseCommit `protobuf:"bytes,12,opt,name=commit,proto3,oneof" json:"commit,omitempty"`
}
type Response_ListSnapshots struct {
ListSnapshots *ResponseListSnapshots `protobuf:"bytes,13,opt,name=list_snapshots,json=listSnapshots,proto3,oneof" json:"list_snapshots,omitempty"`
}
type Response_OfferSnapshot struct {
OfferSnapshot *ResponseOfferSnapshot `protobuf:"bytes,14,opt,name=offer_snapshot,json=offerSnapshot,proto3,oneof" json:"offer_snapshot,omitempty"`
}
type Response_LoadSnapshotChunk struct {
LoadSnapshotChunk *ResponseLoadSnapshotChunk `protobuf:"bytes,15,opt,name=load_snapshot_chunk,json=loadSnapshotChunk,proto3,oneof" json:"load_snapshot_chunk,omitempty"`
}
type Response_ApplySnapshotChunk struct {
ApplySnapshotChunk *ResponseApplySnapshotChunk `protobuf:"bytes,16,opt,name=apply_snapshot_chunk,json=applySnapshotChunk,proto3,oneof" json:"apply_snapshot_chunk,omitempty"`
}
type Response_PrepareProposal struct {
PrepareProposal *ResponsePrepareProposal `protobuf:"bytes,17,opt,name=prepare_proposal,json=prepareProposal,proto3,oneof" json:"prepare_proposal,omitempty"`
}
type Response_ProcessProposal struct {
ProcessProposal *ResponseProcessProposal `protobuf:"bytes,18,opt,name=process_proposal,json=processProposal,proto3,oneof" json:"process_proposal,omitempty"`
}
type Response_ExtendVote struct {
ExtendVote *ResponseExtendVote `protobuf:"bytes,19,opt,name=extend_vote,json=extendVote,proto3,oneof" json:"extend_vote,omitempty"`
}
type Response_VerifyVoteExtension struct {
VerifyVoteExtension *ResponseVerifyVoteExtension `protobuf:"bytes,20,opt,name=verify_vote_extension,json=verifyVoteExtension,proto3,oneof" json:"verify_vote_extension,omitempty"`
}
type Response_FinalizeBlock struct {
FinalizeBlock *ResponseFinalizeBlock `protobuf:"bytes,21,opt,name=finalize_block,json=finalizeBlock,proto3,oneof" json:"finalize_block,omitempty"`
}
func (*Response_Exception) isResponse_Value() {}
func (*Response_Echo) isResponse_Value() {}
func (*Response_Flush) isResponse_Value() {}
func (*Response_Info) isResponse_Value() {}
func (*Response_InitChain) isResponse_Value() {}
func (*Response_Query) isResponse_Value() {}
func (*Response_CheckTx) isResponse_Value() {}
func (*Response_Commit) isResponse_Value() {}
func (*Response_ListSnapshots) isResponse_Value() {}
func (*Response_OfferSnapshot) isResponse_Value() {}
func (*Response_LoadSnapshotChunk) isResponse_Value() {}
func (*Response_ApplySnapshotChunk) isResponse_Value() {}
func (*Response_PrepareProposal) isResponse_Value() {}
func (*Response_ProcessProposal) isResponse_Value() {}
func (*Response_ExtendVote) isResponse_Value() {}
func (*Response_VerifyVoteExtension) isResponse_Value() {}
func (*Response_FinalizeBlock) isResponse_Value() {}
func (m *Response) GetValue() isResponse_Value {
if m != nil {
return m.Value
}
return nil
}
func (m *Response) GetException() *ResponseException {
if x, ok := m.GetValue().(*Response_Exception); ok {
return x.Exception
}
return nil
}
func (m *Response) GetEcho() *ResponseEcho {
if x, ok := m.GetValue().(*Response_Echo); ok {
return x.Echo
}
return nil
}
func (m *Response) GetFlush() *ResponseFlush {
if x, ok := m.GetValue().(*Response_Flush); ok {
return x.Flush
}
return nil
}
func (m *Response) GetInfo() *ResponseInfo {
if x, ok := m.GetValue().(*Response_Info); ok {
return x.Info
}
return nil
}
func (m *Response) GetInitChain() *ResponseInitChain {
if x, ok := m.GetValue().(*Response_InitChain); ok {
return x.InitChain
}
return nil
}
func (m *Response) GetQuery() *ResponseQuery {
if x, ok := m.GetValue().(*Response_Query); ok {
return x.Query
}
return nil
}
func (m *Response) GetCheckTx() *ResponseCheckTx {
if x, ok := m.GetValue().(*Response_CheckTx); ok {
return x.CheckTx
}
return nil
}
func (m *Response) GetCommit() *ResponseCommit {
if x, ok := m.GetValue().(*Response_Commit); ok {
return x.Commit
}
return nil
}
func (m *Response) GetListSnapshots() *ResponseListSnapshots {
if x, ok := m.GetValue().(*Response_ListSnapshots); ok {
return x.ListSnapshots
}
return nil
}
func (m *Response) GetOfferSnapshot() *ResponseOfferSnapshot {
if x, ok := m.GetValue().(*Response_OfferSnapshot); ok {
return x.OfferSnapshot
}
return nil
}
func (m *Response) GetLoadSnapshotChunk() *ResponseLoadSnapshotChunk {
if x, ok := m.GetValue().(*Response_LoadSnapshotChunk); ok {
return x.LoadSnapshotChunk
}
return nil
}
func (m *Response) GetApplySnapshotChunk() *ResponseApplySnapshotChunk {
if x, ok := m.GetValue().(*Response_ApplySnapshotChunk); ok {
return x.ApplySnapshotChunk
}
return nil
}
func (m *Response) GetPrepareProposal() *ResponsePrepareProposal {
if x, ok := m.GetValue().(*Response_PrepareProposal); ok {
return x.PrepareProposal
}
return nil
}
func (m *Response) GetProcessProposal() *ResponseProcessProposal {
if x, ok := m.GetValue().(*Response_ProcessProposal); ok {
return x.ProcessProposal
}
return nil
}
func (m *Response) GetExtendVote() *ResponseExtendVote {
if x, ok := m.GetValue().(*Response_ExtendVote); ok {
return x.ExtendVote
}
return nil
}
func (m *Response) GetVerifyVoteExtension() *ResponseVerifyVoteExtension {
if x, ok := m.GetValue().(*Response_VerifyVoteExtension); ok {
return x.VerifyVoteExtension
}
return nil
}
func (m *Response) GetFinalizeBlock() *ResponseFinalizeBlock {
if x, ok := m.GetValue().(*Response_FinalizeBlock); ok {
return x.FinalizeBlock
}
return nil
}
// XXX_OneofWrappers is for the internal use of the proto package.
func (*Response) XXX_OneofWrappers() []interface{} {
return []interface{}{
(*Response_Exception)(nil),
(*Response_Echo)(nil),
(*Response_Flush)(nil),
(*Response_Info)(nil),
(*Response_InitChain)(nil),
(*Response_Query)(nil),
(*Response_CheckTx)(nil),
(*Response_Commit)(nil),
(*Response_ListSnapshots)(nil),
(*Response_OfferSnapshot)(nil),
(*Response_LoadSnapshotChunk)(nil),
(*Response_ApplySnapshotChunk)(nil),
(*Response_PrepareProposal)(nil),
(*Response_ProcessProposal)(nil),
(*Response_ExtendVote)(nil),
(*Response_VerifyVoteExtension)(nil),
(*Response_FinalizeBlock)(nil),
}
}
// nondeterministic
type ResponseException struct {
Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"`
}
func (m *ResponseException) Reset() { *m = ResponseException{} }
func (m *ResponseException) String() string { return proto.CompactTextString(m) }
func (*ResponseException) ProtoMessage() {}
func (*ResponseException) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{18}
}
func (m *ResponseException) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseException) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseException.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseException) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseException.Merge(m, src)
}
func (m *ResponseException) XXX_Size() int {
return m.Size()
}
func (m *ResponseException) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseException.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseException proto.InternalMessageInfo
func (m *ResponseException) GetError() string {
if m != nil {
return m.Error
}
return ""
}
type ResponseEcho struct {
Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
}
func (m *ResponseEcho) Reset() { *m = ResponseEcho{} }
func (m *ResponseEcho) String() string { return proto.CompactTextString(m) }
func (*ResponseEcho) ProtoMessage() {}
func (*ResponseEcho) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{19}
}
func (m *ResponseEcho) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseEcho) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseEcho.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseEcho) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseEcho.Merge(m, src)
}
func (m *ResponseEcho) XXX_Size() int {
return m.Size()
}
func (m *ResponseEcho) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseEcho.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseEcho proto.InternalMessageInfo
func (m *ResponseEcho) GetMessage() string {
if m != nil {
return m.Message
}
return ""
}
type ResponseFlush struct {
}
func (m *ResponseFlush) Reset() { *m = ResponseFlush{} }
func (m *ResponseFlush) String() string { return proto.CompactTextString(m) }
func (*ResponseFlush) ProtoMessage() {}
func (*ResponseFlush) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{20}
}
func (m *ResponseFlush) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseFlush) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseFlush.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseFlush) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseFlush.Merge(m, src)
}
func (m *ResponseFlush) XXX_Size() int {
return m.Size()
}
func (m *ResponseFlush) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseFlush.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseFlush proto.InternalMessageInfo
type ResponseInfo struct {
Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"`
AppVersion uint64 `protobuf:"varint,3,opt,name=app_version,json=appVersion,proto3" json:"app_version,omitempty"`
LastBlockHeight int64 `protobuf:"varint,4,opt,name=last_block_height,json=lastBlockHeight,proto3" json:"last_block_height,omitempty"`
LastBlockAppHash []byte `protobuf:"bytes,5,opt,name=last_block_app_hash,json=lastBlockAppHash,proto3" json:"last_block_app_hash,omitempty"`
}
func (m *ResponseInfo) Reset() { *m = ResponseInfo{} }
func (m *ResponseInfo) String() string { return proto.CompactTextString(m) }
func (*ResponseInfo) ProtoMessage() {}
func (*ResponseInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{21}
}
func (m *ResponseInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseInfo.Merge(m, src)
}
func (m *ResponseInfo) XXX_Size() int {
return m.Size()
}
func (m *ResponseInfo) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseInfo.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseInfo proto.InternalMessageInfo
func (m *ResponseInfo) GetData() string {
if m != nil {
return m.Data
}
return ""
}
func (m *ResponseInfo) GetVersion() string {
if m != nil {
return m.Version
}
return ""
}
func (m *ResponseInfo) GetAppVersion() uint64 {
if m != nil {
return m.AppVersion
}
return 0
}
func (m *ResponseInfo) GetLastBlockHeight() int64 {
if m != nil {
return m.LastBlockHeight
}
return 0
}
func (m *ResponseInfo) GetLastBlockAppHash() []byte {
if m != nil {
return m.LastBlockAppHash
}
return nil
}
type ResponseInitChain struct {
ConsensusParams *types1.ConsensusParams `protobuf:"bytes,1,opt,name=consensus_params,json=consensusParams,proto3" json:"consensus_params,omitempty"`
Validators []ValidatorUpdate `protobuf:"bytes,2,rep,name=validators,proto3" json:"validators"`
AppHash []byte `protobuf:"bytes,3,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"`
}
func (m *ResponseInitChain) Reset() { *m = ResponseInitChain{} }
func (m *ResponseInitChain) String() string { return proto.CompactTextString(m) }
func (*ResponseInitChain) ProtoMessage() {}
func (*ResponseInitChain) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{22}
}
func (m *ResponseInitChain) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseInitChain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseInitChain.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseInitChain) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseInitChain.Merge(m, src)
}
func (m *ResponseInitChain) XXX_Size() int {
return m.Size()
}
func (m *ResponseInitChain) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseInitChain.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseInitChain proto.InternalMessageInfo
func (m *ResponseInitChain) GetConsensusParams() *types1.ConsensusParams {
if m != nil {
return m.ConsensusParams
}
return nil
}
func (m *ResponseInitChain) GetValidators() []ValidatorUpdate {
if m != nil {
return m.Validators
}
return nil
}
func (m *ResponseInitChain) GetAppHash() []byte {
if m != nil {
return m.AppHash
}
return nil
}
type ResponseQuery struct {
Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`
// bytes data = 2; // use "value" instead.
Log string `protobuf:"bytes,3,opt,name=log,proto3" json:"log,omitempty"`
Info string `protobuf:"bytes,4,opt,name=info,proto3" json:"info,omitempty"`
Index int64 `protobuf:"varint,5,opt,name=index,proto3" json:"index,omitempty"`
Key []byte `protobuf:"bytes,6,opt,name=key,proto3" json:"key,omitempty"`
Value []byte `protobuf:"bytes,7,opt,name=value,proto3" json:"value,omitempty"`
ProofOps *crypto.ProofOps `protobuf:"bytes,8,opt,name=proof_ops,json=proofOps,proto3" json:"proof_ops,omitempty"`
Height int64 `protobuf:"varint,9,opt,name=height,proto3" json:"height,omitempty"`
Codespace string `protobuf:"bytes,10,opt,name=codespace,proto3" json:"codespace,omitempty"`
}
func (m *ResponseQuery) Reset() { *m = ResponseQuery{} }
func (m *ResponseQuery) String() string { return proto.CompactTextString(m) }
func (*ResponseQuery) ProtoMessage() {}
func (*ResponseQuery) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{23}
}
func (m *ResponseQuery) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseQuery) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseQuery.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseQuery) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseQuery.Merge(m, src)
}
func (m *ResponseQuery) XXX_Size() int {
return m.Size()
}
func (m *ResponseQuery) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseQuery.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseQuery proto.InternalMessageInfo
func (m *ResponseQuery) GetCode() uint32 {
if m != nil {
return m.Code
}
return 0
}
func (m *ResponseQuery) GetLog() string {
if m != nil {
return m.Log
}
return ""
}
func (m *ResponseQuery) GetInfo() string {
if m != nil {
return m.Info
}
return ""
}
func (m *ResponseQuery) GetIndex() int64 {
if m != nil {
return m.Index
}
return 0
}
func (m *ResponseQuery) GetKey() []byte {
if m != nil {
return m.Key
}
return nil
}
func (m *ResponseQuery) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *ResponseQuery) GetProofOps() *crypto.ProofOps {
if m != nil {
return m.ProofOps
}
return nil
}
func (m *ResponseQuery) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *ResponseQuery) GetCodespace() string {
if m != nil {
return m.Codespace
}
return ""
}
type ResponseCheckTx struct {
Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
Log string `protobuf:"bytes,3,opt,name=log,proto3" json:"log,omitempty"`
Info string `protobuf:"bytes,4,opt,name=info,proto3" json:"info,omitempty"`
GasWanted int64 `protobuf:"varint,5,opt,name=gas_wanted,proto3" json:"gas_wanted,omitempty"`
GasUsed int64 `protobuf:"varint,6,opt,name=gas_used,proto3" json:"gas_used,omitempty"`
Events []Event `protobuf:"bytes,7,rep,name=events,proto3" json:"events,omitempty"`
Codespace string `protobuf:"bytes,8,opt,name=codespace,proto3" json:"codespace,omitempty"`
}
func (m *ResponseCheckTx) Reset() { *m = ResponseCheckTx{} }
func (m *ResponseCheckTx) String() string { return proto.CompactTextString(m) }
func (*ResponseCheckTx) ProtoMessage() {}
func (*ResponseCheckTx) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{24}
}
func (m *ResponseCheckTx) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseCheckTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseCheckTx.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseCheckTx) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseCheckTx.Merge(m, src)
}
func (m *ResponseCheckTx) XXX_Size() int {
return m.Size()
}
func (m *ResponseCheckTx) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseCheckTx.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseCheckTx proto.InternalMessageInfo
func (m *ResponseCheckTx) GetCode() uint32 {
if m != nil {
return m.Code
}
return 0
}
func (m *ResponseCheckTx) GetData() []byte {
if m != nil {
return m.Data
}
return nil
}
func (m *ResponseCheckTx) GetLog() string {
if m != nil {
return m.Log
}
return ""
}
func (m *ResponseCheckTx) GetInfo() string {
if m != nil {
return m.Info
}
return ""
}
func (m *ResponseCheckTx) GetGasWanted() int64 {
if m != nil {
return m.GasWanted
}
return 0
}
func (m *ResponseCheckTx) GetGasUsed() int64 {
if m != nil {
return m.GasUsed
}
return 0
}
func (m *ResponseCheckTx) GetEvents() []Event {
if m != nil {
return m.Events
}
return nil
}
func (m *ResponseCheckTx) GetCodespace() string {
if m != nil {
return m.Codespace
}
return ""
}
type ResponseCommit struct {
RetainHeight int64 `protobuf:"varint,3,opt,name=retain_height,json=retainHeight,proto3" json:"retain_height,omitempty"`
}
func (m *ResponseCommit) Reset() { *m = ResponseCommit{} }
func (m *ResponseCommit) String() string { return proto.CompactTextString(m) }
func (*ResponseCommit) ProtoMessage() {}
func (*ResponseCommit) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{25}
}
func (m *ResponseCommit) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseCommit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseCommit.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseCommit) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseCommit.Merge(m, src)
}
func (m *ResponseCommit) XXX_Size() int {
return m.Size()
}
func (m *ResponseCommit) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseCommit.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseCommit proto.InternalMessageInfo
func (m *ResponseCommit) GetRetainHeight() int64 {
if m != nil {
return m.RetainHeight
}
return 0
}
type ResponseListSnapshots struct {
Snapshots []*Snapshot `protobuf:"bytes,1,rep,name=snapshots,proto3" json:"snapshots,omitempty"`
}
func (m *ResponseListSnapshots) Reset() { *m = ResponseListSnapshots{} }
func (m *ResponseListSnapshots) String() string { return proto.CompactTextString(m) }
func (*ResponseListSnapshots) ProtoMessage() {}
func (*ResponseListSnapshots) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{26}
}
func (m *ResponseListSnapshots) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseListSnapshots) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseListSnapshots.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseListSnapshots) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseListSnapshots.Merge(m, src)
}
func (m *ResponseListSnapshots) XXX_Size() int {
return m.Size()
}
func (m *ResponseListSnapshots) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseListSnapshots.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseListSnapshots proto.InternalMessageInfo
func (m *ResponseListSnapshots) GetSnapshots() []*Snapshot {
if m != nil {
return m.Snapshots
}
return nil
}
type ResponseOfferSnapshot struct {
Result ResponseOfferSnapshot_Result `protobuf:"varint,1,opt,name=result,proto3,enum=tendermint.abci.ResponseOfferSnapshot_Result" json:"result,omitempty"`
}
func (m *ResponseOfferSnapshot) Reset() { *m = ResponseOfferSnapshot{} }
func (m *ResponseOfferSnapshot) String() string { return proto.CompactTextString(m) }
func (*ResponseOfferSnapshot) ProtoMessage() {}
func (*ResponseOfferSnapshot) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{27}
}
func (m *ResponseOfferSnapshot) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseOfferSnapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseOfferSnapshot.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseOfferSnapshot) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseOfferSnapshot.Merge(m, src)
}
func (m *ResponseOfferSnapshot) XXX_Size() int {
return m.Size()
}
func (m *ResponseOfferSnapshot) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseOfferSnapshot.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseOfferSnapshot proto.InternalMessageInfo
func (m *ResponseOfferSnapshot) GetResult() ResponseOfferSnapshot_Result {
if m != nil {
return m.Result
}
return ResponseOfferSnapshot_UNKNOWN
}
type ResponseLoadSnapshotChunk struct {
Chunk []byte `protobuf:"bytes,1,opt,name=chunk,proto3" json:"chunk,omitempty"`
}
func (m *ResponseLoadSnapshotChunk) Reset() { *m = ResponseLoadSnapshotChunk{} }
func (m *ResponseLoadSnapshotChunk) String() string { return proto.CompactTextString(m) }
func (*ResponseLoadSnapshotChunk) ProtoMessage() {}
func (*ResponseLoadSnapshotChunk) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{28}
}
func (m *ResponseLoadSnapshotChunk) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseLoadSnapshotChunk) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseLoadSnapshotChunk.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseLoadSnapshotChunk) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseLoadSnapshotChunk.Merge(m, src)
}
func (m *ResponseLoadSnapshotChunk) XXX_Size() int {
return m.Size()
}
func (m *ResponseLoadSnapshotChunk) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseLoadSnapshotChunk.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseLoadSnapshotChunk proto.InternalMessageInfo
func (m *ResponseLoadSnapshotChunk) GetChunk() []byte {
if m != nil {
return m.Chunk
}
return nil
}
type ResponseApplySnapshotChunk struct {
Result ResponseApplySnapshotChunk_Result `protobuf:"varint,1,opt,name=result,proto3,enum=tendermint.abci.ResponseApplySnapshotChunk_Result" json:"result,omitempty"`
RefetchChunks []uint32 `protobuf:"varint,2,rep,packed,name=refetch_chunks,json=refetchChunks,proto3" json:"refetch_chunks,omitempty"`
RejectSenders []string `protobuf:"bytes,3,rep,name=reject_senders,json=rejectSenders,proto3" json:"reject_senders,omitempty"`
}
func (m *ResponseApplySnapshotChunk) Reset() { *m = ResponseApplySnapshotChunk{} }
func (m *ResponseApplySnapshotChunk) String() string { return proto.CompactTextString(m) }
func (*ResponseApplySnapshotChunk) ProtoMessage() {}
func (*ResponseApplySnapshotChunk) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{29}
}
func (m *ResponseApplySnapshotChunk) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseApplySnapshotChunk) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseApplySnapshotChunk.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseApplySnapshotChunk) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseApplySnapshotChunk.Merge(m, src)
}
func (m *ResponseApplySnapshotChunk) XXX_Size() int {
return m.Size()
}
func (m *ResponseApplySnapshotChunk) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseApplySnapshotChunk.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseApplySnapshotChunk proto.InternalMessageInfo
func (m *ResponseApplySnapshotChunk) GetResult() ResponseApplySnapshotChunk_Result {
if m != nil {
return m.Result
}
return ResponseApplySnapshotChunk_UNKNOWN
}
func (m *ResponseApplySnapshotChunk) GetRefetchChunks() []uint32 {
if m != nil {
return m.RefetchChunks
}
return nil
}
func (m *ResponseApplySnapshotChunk) GetRejectSenders() []string {
if m != nil {
return m.RejectSenders
}
return nil
}
type ResponsePrepareProposal struct {
Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"`
}
func (m *ResponsePrepareProposal) Reset() { *m = ResponsePrepareProposal{} }
func (m *ResponsePrepareProposal) String() string { return proto.CompactTextString(m) }
func (*ResponsePrepareProposal) ProtoMessage() {}
func (*ResponsePrepareProposal) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{30}
}
func (m *ResponsePrepareProposal) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponsePrepareProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponsePrepareProposal.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponsePrepareProposal) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponsePrepareProposal.Merge(m, src)
}
func (m *ResponsePrepareProposal) XXX_Size() int {
return m.Size()
}
func (m *ResponsePrepareProposal) XXX_DiscardUnknown() {
xxx_messageInfo_ResponsePrepareProposal.DiscardUnknown(m)
}
var xxx_messageInfo_ResponsePrepareProposal proto.InternalMessageInfo
func (m *ResponsePrepareProposal) GetTxs() [][]byte {
if m != nil {
return m.Txs
}
return nil
}
type ResponseProcessProposal struct {
Status ResponseProcessProposal_ProposalStatus `protobuf:"varint,1,opt,name=status,proto3,enum=tendermint.abci.ResponseProcessProposal_ProposalStatus" json:"status,omitempty"`
}
func (m *ResponseProcessProposal) Reset() { *m = ResponseProcessProposal{} }
func (m *ResponseProcessProposal) String() string { return proto.CompactTextString(m) }
func (*ResponseProcessProposal) ProtoMessage() {}
func (*ResponseProcessProposal) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{31}
}
func (m *ResponseProcessProposal) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseProcessProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseProcessProposal.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseProcessProposal) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseProcessProposal.Merge(m, src)
}
func (m *ResponseProcessProposal) XXX_Size() int {
return m.Size()
}
func (m *ResponseProcessProposal) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseProcessProposal.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseProcessProposal proto.InternalMessageInfo
func (m *ResponseProcessProposal) GetStatus() ResponseProcessProposal_ProposalStatus {
if m != nil {
return m.Status
}
return ResponseProcessProposal_UNKNOWN
}
type ResponseExtendVote struct {
VoteExtension []byte `protobuf:"bytes,1,opt,name=vote_extension,json=voteExtension,proto3" json:"vote_extension,omitempty"`
}
func (m *ResponseExtendVote) Reset() { *m = ResponseExtendVote{} }
func (m *ResponseExtendVote) String() string { return proto.CompactTextString(m) }
func (*ResponseExtendVote) ProtoMessage() {}
func (*ResponseExtendVote) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{32}
}
func (m *ResponseExtendVote) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseExtendVote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseExtendVote.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseExtendVote) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseExtendVote.Merge(m, src)
}
func (m *ResponseExtendVote) XXX_Size() int {
return m.Size()
}
func (m *ResponseExtendVote) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseExtendVote.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseExtendVote proto.InternalMessageInfo
func (m *ResponseExtendVote) GetVoteExtension() []byte {
if m != nil {
return m.VoteExtension
}
return nil
}
type ResponseVerifyVoteExtension struct {
Status ResponseVerifyVoteExtension_VerifyStatus `protobuf:"varint,1,opt,name=status,proto3,enum=tendermint.abci.ResponseVerifyVoteExtension_VerifyStatus" json:"status,omitempty"`
}
func (m *ResponseVerifyVoteExtension) Reset() { *m = ResponseVerifyVoteExtension{} }
func (m *ResponseVerifyVoteExtension) String() string { return proto.CompactTextString(m) }
func (*ResponseVerifyVoteExtension) ProtoMessage() {}
func (*ResponseVerifyVoteExtension) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{33}
}
func (m *ResponseVerifyVoteExtension) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseVerifyVoteExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseVerifyVoteExtension.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseVerifyVoteExtension) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseVerifyVoteExtension.Merge(m, src)
}
func (m *ResponseVerifyVoteExtension) XXX_Size() int {
return m.Size()
}
func (m *ResponseVerifyVoteExtension) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseVerifyVoteExtension.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseVerifyVoteExtension proto.InternalMessageInfo
func (m *ResponseVerifyVoteExtension) GetStatus() ResponseVerifyVoteExtension_VerifyStatus {
if m != nil {
return m.Status
}
return ResponseVerifyVoteExtension_UNKNOWN
}
type ResponseFinalizeBlock struct {
// set of block events emmitted as part of executing the block
Events []Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"`
// the result of executing each transaction including the events
// the particular transction emitted. This should match the order
// of the transactions delivered in the block itself
TxResults []*ExecTxResult `protobuf:"bytes,2,rep,name=tx_results,json=txResults,proto3" json:"tx_results,omitempty"`
// a list of updates to the validator set. These will reflect the validator set at current height + 2.
ValidatorUpdates []ValidatorUpdate `protobuf:"bytes,3,rep,name=validator_updates,json=validatorUpdates,proto3" json:"validator_updates"`
// updates to the consensus params, if any.
ConsensusParamUpdates *types1.ConsensusParams `protobuf:"bytes,4,opt,name=consensus_param_updates,json=consensusParamUpdates,proto3" json:"consensus_param_updates,omitempty"`
// app_hash is the hash of the applications' state which is used to confirm that execution of the transactions was deterministic. It is up to the application to decide which algorithm to use.
AppHash []byte `protobuf:"bytes,5,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"`
}
func (m *ResponseFinalizeBlock) Reset() { *m = ResponseFinalizeBlock{} }
func (m *ResponseFinalizeBlock) String() string { return proto.CompactTextString(m) }
func (*ResponseFinalizeBlock) ProtoMessage() {}
func (*ResponseFinalizeBlock) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{34}
}
func (m *ResponseFinalizeBlock) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ResponseFinalizeBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ResponseFinalizeBlock.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ResponseFinalizeBlock) XXX_Merge(src proto.Message) {
xxx_messageInfo_ResponseFinalizeBlock.Merge(m, src)
}
func (m *ResponseFinalizeBlock) XXX_Size() int {
return m.Size()
}
func (m *ResponseFinalizeBlock) XXX_DiscardUnknown() {
xxx_messageInfo_ResponseFinalizeBlock.DiscardUnknown(m)
}
var xxx_messageInfo_ResponseFinalizeBlock proto.InternalMessageInfo
func (m *ResponseFinalizeBlock) GetEvents() []Event {
if m != nil {
return m.Events
}
return nil
}
func (m *ResponseFinalizeBlock) GetTxResults() []*ExecTxResult {
if m != nil {
return m.TxResults
}
return nil
}
func (m *ResponseFinalizeBlock) GetValidatorUpdates() []ValidatorUpdate {
if m != nil {
return m.ValidatorUpdates
}
return nil
}
func (m *ResponseFinalizeBlock) GetConsensusParamUpdates() *types1.ConsensusParams {
if m != nil {
return m.ConsensusParamUpdates
}
return nil
}
func (m *ResponseFinalizeBlock) GetAppHash() []byte {
if m != nil {
return m.AppHash
}
return nil
}
type CommitInfo struct {
Round int32 `protobuf:"varint,1,opt,name=round,proto3" json:"round,omitempty"`
Votes []VoteInfo `protobuf:"bytes,2,rep,name=votes,proto3" json:"votes"`
}
func (m *CommitInfo) Reset() { *m = CommitInfo{} }
func (m *CommitInfo) String() string { return proto.CompactTextString(m) }
func (*CommitInfo) ProtoMessage() {}
func (*CommitInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{35}
}
func (m *CommitInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *CommitInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_CommitInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *CommitInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_CommitInfo.Merge(m, src)
}
func (m *CommitInfo) XXX_Size() int {
return m.Size()
}
func (m *CommitInfo) XXX_DiscardUnknown() {
xxx_messageInfo_CommitInfo.DiscardUnknown(m)
}
var xxx_messageInfo_CommitInfo proto.InternalMessageInfo
func (m *CommitInfo) GetRound() int32 {
if m != nil {
return m.Round
}
return 0
}
func (m *CommitInfo) GetVotes() []VoteInfo {
if m != nil {
return m.Votes
}
return nil
}
// ExtendedCommitInfo is similar to CommitInfo except that it is only used in
// the PrepareProposal request such that CometBFT can provide vote extensions
// to the application.
type ExtendedCommitInfo struct {
// The round at which the block proposer decided in the previous height.
Round int32 `protobuf:"varint,1,opt,name=round,proto3" json:"round,omitempty"`
// List of validators' addresses in the last validator set with their voting
// information, including vote extensions.
Votes []ExtendedVoteInfo `protobuf:"bytes,2,rep,name=votes,proto3" json:"votes"`
}
func (m *ExtendedCommitInfo) Reset() { *m = ExtendedCommitInfo{} }
func (m *ExtendedCommitInfo) String() string { return proto.CompactTextString(m) }
func (*ExtendedCommitInfo) ProtoMessage() {}
func (*ExtendedCommitInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{36}
}
func (m *ExtendedCommitInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ExtendedCommitInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ExtendedCommitInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ExtendedCommitInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExtendedCommitInfo.Merge(m, src)
}
func (m *ExtendedCommitInfo) XXX_Size() int {
return m.Size()
}
func (m *ExtendedCommitInfo) XXX_DiscardUnknown() {
xxx_messageInfo_ExtendedCommitInfo.DiscardUnknown(m)
}
var xxx_messageInfo_ExtendedCommitInfo proto.InternalMessageInfo
func (m *ExtendedCommitInfo) GetRound() int32 {
if m != nil {
return m.Round
}
return 0
}
func (m *ExtendedCommitInfo) GetVotes() []ExtendedVoteInfo {
if m != nil {
return m.Votes
}
return nil
}
// Event allows application developers to attach additional information to
// ResponseFinalizeBlock and ResponseCheckTx.
// Later, transactions may be queried using these events.
type Event struct {
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
Attributes []EventAttribute `protobuf:"bytes,2,rep,name=attributes,proto3" json:"attributes,omitempty"`
}
func (m *Event) Reset() { *m = Event{} }
func (m *Event) String() string { return proto.CompactTextString(m) }
func (*Event) ProtoMessage() {}
func (*Event) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{37}
}
func (m *Event) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Event.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Event) XXX_Merge(src proto.Message) {
xxx_messageInfo_Event.Merge(m, src)
}
func (m *Event) XXX_Size() int {
return m.Size()
}
func (m *Event) XXX_DiscardUnknown() {
xxx_messageInfo_Event.DiscardUnknown(m)
}
var xxx_messageInfo_Event proto.InternalMessageInfo
func (m *Event) GetType() string {
if m != nil {
return m.Type
}
return ""
}
func (m *Event) GetAttributes() []EventAttribute {
if m != nil {
return m.Attributes
}
return nil
}
// EventAttribute is a single key-value pair, associated with an event.
type EventAttribute struct {
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Index bool `protobuf:"varint,3,opt,name=index,proto3" json:"index,omitempty"`
}
func (m *EventAttribute) Reset() { *m = EventAttribute{} }
func (m *EventAttribute) String() string { return proto.CompactTextString(m) }
func (*EventAttribute) ProtoMessage() {}
func (*EventAttribute) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{38}
}
func (m *EventAttribute) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *EventAttribute) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_EventAttribute.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *EventAttribute) XXX_Merge(src proto.Message) {
xxx_messageInfo_EventAttribute.Merge(m, src)
}
func (m *EventAttribute) XXX_Size() int {
return m.Size()
}
func (m *EventAttribute) XXX_DiscardUnknown() {
xxx_messageInfo_EventAttribute.DiscardUnknown(m)
}
var xxx_messageInfo_EventAttribute proto.InternalMessageInfo
func (m *EventAttribute) GetKey() string {
if m != nil {
return m.Key
}
return ""
}
func (m *EventAttribute) GetValue() string {
if m != nil {
return m.Value
}
return ""
}
func (m *EventAttribute) GetIndex() bool {
if m != nil {
return m.Index
}
return false
}
// ExecTxResult contains results of executing one individual transaction.
//
// * Its structure is equivalent to #ResponseDeliverTx which will be deprecated/deleted
type ExecTxResult struct {
Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
Log string `protobuf:"bytes,3,opt,name=log,proto3" json:"log,omitempty"`
Info string `protobuf:"bytes,4,opt,name=info,proto3" json:"info,omitempty"`
GasWanted int64 `protobuf:"varint,5,opt,name=gas_wanted,proto3" json:"gas_wanted,omitempty"`
GasUsed int64 `protobuf:"varint,6,opt,name=gas_used,proto3" json:"gas_used,omitempty"`
Events []Event `protobuf:"bytes,7,rep,name=events,proto3" json:"events,omitempty"`
Codespace string `protobuf:"bytes,8,opt,name=codespace,proto3" json:"codespace,omitempty"`
}
func (m *ExecTxResult) Reset() { *m = ExecTxResult{} }
func (m *ExecTxResult) String() string { return proto.CompactTextString(m) }
func (*ExecTxResult) ProtoMessage() {}
func (*ExecTxResult) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{39}
}
func (m *ExecTxResult) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ExecTxResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ExecTxResult.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ExecTxResult) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExecTxResult.Merge(m, src)
}
func (m *ExecTxResult) XXX_Size() int {
return m.Size()
}
func (m *ExecTxResult) XXX_DiscardUnknown() {
xxx_messageInfo_ExecTxResult.DiscardUnknown(m)
}
var xxx_messageInfo_ExecTxResult proto.InternalMessageInfo
func (m *ExecTxResult) GetCode() uint32 {
if m != nil {
return m.Code
}
return 0
}
func (m *ExecTxResult) GetData() []byte {
if m != nil {
return m.Data
}
return nil
}
func (m *ExecTxResult) GetLog() string {
if m != nil {
return m.Log
}
return ""
}
func (m *ExecTxResult) GetInfo() string {
if m != nil {
return m.Info
}
return ""
}
func (m *ExecTxResult) GetGasWanted() int64 {
if m != nil {
return m.GasWanted
}
return 0
}
func (m *ExecTxResult) GetGasUsed() int64 {
if m != nil {
return m.GasUsed
}
return 0
}
func (m *ExecTxResult) GetEvents() []Event {
if m != nil {
return m.Events
}
return nil
}
func (m *ExecTxResult) GetCodespace() string {
if m != nil {
return m.Codespace
}
return ""
}
// TxResult contains results of executing the transaction.
//
// One usage is indexing transaction results.
type TxResult struct {
Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"`
Index uint32 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty"`
Tx []byte `protobuf:"bytes,3,opt,name=tx,proto3" json:"tx,omitempty"`
Result ExecTxResult `protobuf:"bytes,4,opt,name=result,proto3" json:"result"`
}
func (m *TxResult) Reset() { *m = TxResult{} }
func (m *TxResult) String() string { return proto.CompactTextString(m) }
func (*TxResult) ProtoMessage() {}
func (*TxResult) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{40}
}
func (m *TxResult) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxResult.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxResult) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxResult.Merge(m, src)
}
func (m *TxResult) XXX_Size() int {
return m.Size()
}
func (m *TxResult) XXX_DiscardUnknown() {
xxx_messageInfo_TxResult.DiscardUnknown(m)
}
var xxx_messageInfo_TxResult proto.InternalMessageInfo
func (m *TxResult) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *TxResult) GetIndex() uint32 {
if m != nil {
return m.Index
}
return 0
}
func (m *TxResult) GetTx() []byte {
if m != nil {
return m.Tx
}
return nil
}
func (m *TxResult) GetResult() ExecTxResult {
if m != nil {
return m.Result
}
return ExecTxResult{}
}
type Validator struct {
Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
// PubKey pub_key = 2 [(gogoproto.nullable)=false];
Power int64 `protobuf:"varint,3,opt,name=power,proto3" json:"power,omitempty"`
}
func (m *Validator) Reset() { *m = Validator{} }
func (m *Validator) String() string { return proto.CompactTextString(m) }
func (*Validator) ProtoMessage() {}
func (*Validator) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{41}
}
func (m *Validator) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Validator) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Validator.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Validator) XXX_Merge(src proto.Message) {
xxx_messageInfo_Validator.Merge(m, src)
}
func (m *Validator) XXX_Size() int {
return m.Size()
}
func (m *Validator) XXX_DiscardUnknown() {
xxx_messageInfo_Validator.DiscardUnknown(m)
}
var xxx_messageInfo_Validator proto.InternalMessageInfo
func (m *Validator) GetAddress() []byte {
if m != nil {
return m.Address
}
return nil
}
func (m *Validator) GetPower() int64 {
if m != nil {
return m.Power
}
return 0
}
type ValidatorUpdate struct {
PubKey crypto.PublicKey `protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3" json:"pub_key"`
Power int64 `protobuf:"varint,2,opt,name=power,proto3" json:"power,omitempty"`
}
func (m *ValidatorUpdate) Reset() { *m = ValidatorUpdate{} }
func (m *ValidatorUpdate) String() string { return proto.CompactTextString(m) }
func (*ValidatorUpdate) ProtoMessage() {}
func (*ValidatorUpdate) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{42}
}
func (m *ValidatorUpdate) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ValidatorUpdate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ValidatorUpdate.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ValidatorUpdate) XXX_Merge(src proto.Message) {
xxx_messageInfo_ValidatorUpdate.Merge(m, src)
}
func (m *ValidatorUpdate) XXX_Size() int {
return m.Size()
}
func (m *ValidatorUpdate) XXX_DiscardUnknown() {
xxx_messageInfo_ValidatorUpdate.DiscardUnknown(m)
}
var xxx_messageInfo_ValidatorUpdate proto.InternalMessageInfo
func (m *ValidatorUpdate) GetPubKey() crypto.PublicKey {
if m != nil {
return m.PubKey
}
return crypto.PublicKey{}
}
func (m *ValidatorUpdate) GetPower() int64 {
if m != nil {
return m.Power
}
return 0
}
type VoteInfo struct {
Validator Validator `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator"`
BlockIdFlag types1.BlockIDFlag `protobuf:"varint,3,opt,name=block_id_flag,json=blockIdFlag,proto3,enum=tendermint.types.BlockIDFlag" json:"block_id_flag,omitempty"`
}
func (m *VoteInfo) Reset() { *m = VoteInfo{} }
func (m *VoteInfo) String() string { return proto.CompactTextString(m) }
func (*VoteInfo) ProtoMessage() {}
func (*VoteInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{43}
}
func (m *VoteInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *VoteInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_VoteInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *VoteInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_VoteInfo.Merge(m, src)
}
func (m *VoteInfo) XXX_Size() int {
return m.Size()
}
func (m *VoteInfo) XXX_DiscardUnknown() {
xxx_messageInfo_VoteInfo.DiscardUnknown(m)
}
var xxx_messageInfo_VoteInfo proto.InternalMessageInfo
func (m *VoteInfo) GetValidator() Validator {
if m != nil {
return m.Validator
}
return Validator{}
}
func (m *VoteInfo) GetBlockIdFlag() types1.BlockIDFlag {
if m != nil {
return m.BlockIdFlag
}
return types1.BlockIDFlagUnknown
}
type ExtendedVoteInfo struct {
// The validator that sent the vote.
Validator Validator `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator"`
// Non-deterministic extension provided by the sending validator's application.
VoteExtension []byte `protobuf:"bytes,3,opt,name=vote_extension,json=voteExtension,proto3" json:"vote_extension,omitempty"`
// Vote extension signature created by CometBFT
ExtensionSignature []byte `protobuf:"bytes,4,opt,name=extension_signature,json=extensionSignature,proto3" json:"extension_signature,omitempty"`
// block_id_flag indicates whether the validator voted for a block, nil, or did not vote at all
BlockIdFlag types1.BlockIDFlag `protobuf:"varint,5,opt,name=block_id_flag,json=blockIdFlag,proto3,enum=tendermint.types.BlockIDFlag" json:"block_id_flag,omitempty"`
}
func (m *ExtendedVoteInfo) Reset() { *m = ExtendedVoteInfo{} }
func (m *ExtendedVoteInfo) String() string { return proto.CompactTextString(m) }
func (*ExtendedVoteInfo) ProtoMessage() {}
func (*ExtendedVoteInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{44}
}
func (m *ExtendedVoteInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ExtendedVoteInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ExtendedVoteInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ExtendedVoteInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExtendedVoteInfo.Merge(m, src)
}
func (m *ExtendedVoteInfo) XXX_Size() int {
return m.Size()
}
func (m *ExtendedVoteInfo) XXX_DiscardUnknown() {
xxx_messageInfo_ExtendedVoteInfo.DiscardUnknown(m)
}
var xxx_messageInfo_ExtendedVoteInfo proto.InternalMessageInfo
func (m *ExtendedVoteInfo) GetValidator() Validator {
if m != nil {
return m.Validator
}
return Validator{}
}
func (m *ExtendedVoteInfo) GetVoteExtension() []byte {
if m != nil {
return m.VoteExtension
}
return nil
}
func (m *ExtendedVoteInfo) GetExtensionSignature() []byte {
if m != nil {
return m.ExtensionSignature
}
return nil
}
func (m *ExtendedVoteInfo) GetBlockIdFlag() types1.BlockIDFlag {
if m != nil {
return m.BlockIdFlag
}
return types1.BlockIDFlagUnknown
}
type Misbehavior struct {
Type MisbehaviorType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.abci.MisbehaviorType" json:"type,omitempty"`
// The offending validator
Validator Validator `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator"`
// The height when the offense occurred
Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"`
// The corresponding time where the offense occurred
Time time.Time `protobuf:"bytes,4,opt,name=time,proto3,stdtime" json:"time"`
// Total voting power of the validator set in case the ABCI application does
// not store historical validators.
// https://github.com/tendermint/tendermint/issues/4581
TotalVotingPower int64 `protobuf:"varint,5,opt,name=total_voting_power,json=totalVotingPower,proto3" json:"total_voting_power,omitempty"`
}
func (m *Misbehavior) Reset() { *m = Misbehavior{} }
func (m *Misbehavior) String() string { return proto.CompactTextString(m) }
func (*Misbehavior) ProtoMessage() {}
func (*Misbehavior) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{45}
}
func (m *Misbehavior) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Misbehavior) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Misbehavior.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Misbehavior) XXX_Merge(src proto.Message) {
xxx_messageInfo_Misbehavior.Merge(m, src)
}
func (m *Misbehavior) XXX_Size() int {
return m.Size()
}
func (m *Misbehavior) XXX_DiscardUnknown() {
xxx_messageInfo_Misbehavior.DiscardUnknown(m)
}
var xxx_messageInfo_Misbehavior proto.InternalMessageInfo
func (m *Misbehavior) GetType() MisbehaviorType {
if m != nil {
return m.Type
}
return MisbehaviorType_UNKNOWN
}
func (m *Misbehavior) GetValidator() Validator {
if m != nil {
return m.Validator
}
return Validator{}
}
func (m *Misbehavior) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *Misbehavior) GetTime() time.Time {
if m != nil {
return m.Time
}
return time.Time{}
}
func (m *Misbehavior) GetTotalVotingPower() int64 {
if m != nil {
return m.TotalVotingPower
}
return 0
}
type Snapshot struct {
Height uint64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"`
Format uint32 `protobuf:"varint,2,opt,name=format,proto3" json:"format,omitempty"`
Chunks uint32 `protobuf:"varint,3,opt,name=chunks,proto3" json:"chunks,omitempty"`
Hash []byte `protobuf:"bytes,4,opt,name=hash,proto3" json:"hash,omitempty"`
Metadata []byte `protobuf:"bytes,5,opt,name=metadata,proto3" json:"metadata,omitempty"`
}
func (m *Snapshot) Reset() { *m = Snapshot{} }
func (m *Snapshot) String() string { return proto.CompactTextString(m) }
func (*Snapshot) ProtoMessage() {}
func (*Snapshot) Descriptor() ([]byte, []int) {
return fileDescriptor_252557cfdd89a31a, []int{46}
}
func (m *Snapshot) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Snapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Snapshot.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Snapshot) XXX_Merge(src proto.Message) {
xxx_messageInfo_Snapshot.Merge(m, src)
}
func (m *Snapshot) XXX_Size() int {
return m.Size()
}
func (m *Snapshot) XXX_DiscardUnknown() {
xxx_messageInfo_Snapshot.DiscardUnknown(m)
}
var xxx_messageInfo_Snapshot proto.InternalMessageInfo
func (m *Snapshot) GetHeight() uint64 {
if m != nil {
return m.Height
}
return 0
}
func (m *Snapshot) GetFormat() uint32 {
if m != nil {
return m.Format
}
return 0
}
func (m *Snapshot) GetChunks() uint32 {
if m != nil {
return m.Chunks
}
return 0
}
func (m *Snapshot) GetHash() []byte {
if m != nil {
return m.Hash
}
return nil
}
func (m *Snapshot) GetMetadata() []byte {
if m != nil {
return m.Metadata
}
return nil
}
func init() {
proto.RegisterEnum("tendermint.abci.CheckTxType", CheckTxType_name, CheckTxType_value)
proto.RegisterEnum("tendermint.abci.MisbehaviorType", MisbehaviorType_name, MisbehaviorType_value)
proto.RegisterEnum("tendermint.abci.ResponseOfferSnapshot_Result", ResponseOfferSnapshot_Result_name, ResponseOfferSnapshot_Result_value)
proto.RegisterEnum("tendermint.abci.ResponseApplySnapshotChunk_Result", ResponseApplySnapshotChunk_Result_name, ResponseApplySnapshotChunk_Result_value)
proto.RegisterEnum("tendermint.abci.ResponseProcessProposal_ProposalStatus", ResponseProcessProposal_ProposalStatus_name, ResponseProcessProposal_ProposalStatus_value)
proto.RegisterEnum("tendermint.abci.ResponseVerifyVoteExtension_VerifyStatus", ResponseVerifyVoteExtension_VerifyStatus_name, ResponseVerifyVoteExtension_VerifyStatus_value)
proto.RegisterType((*Request)(nil), "tendermint.abci.Request")
proto.RegisterType((*RequestEcho)(nil), "tendermint.abci.RequestEcho")
proto.RegisterType((*RequestFlush)(nil), "tendermint.abci.RequestFlush")
proto.RegisterType((*RequestInfo)(nil), "tendermint.abci.RequestInfo")
proto.RegisterType((*RequestInitChain)(nil), "tendermint.abci.RequestInitChain")
proto.RegisterType((*RequestQuery)(nil), "tendermint.abci.RequestQuery")
proto.RegisterType((*RequestCheckTx)(nil), "tendermint.abci.RequestCheckTx")
proto.RegisterType((*RequestCommit)(nil), "tendermint.abci.RequestCommit")
proto.RegisterType((*RequestListSnapshots)(nil), "tendermint.abci.RequestListSnapshots")
proto.RegisterType((*RequestOfferSnapshot)(nil), "tendermint.abci.RequestOfferSnapshot")
proto.RegisterType((*RequestLoadSnapshotChunk)(nil), "tendermint.abci.RequestLoadSnapshotChunk")
proto.RegisterType((*RequestApplySnapshotChunk)(nil), "tendermint.abci.RequestApplySnapshotChunk")
proto.RegisterType((*RequestPrepareProposal)(nil), "tendermint.abci.RequestPrepareProposal")
proto.RegisterType((*RequestProcessProposal)(nil), "tendermint.abci.RequestProcessProposal")
proto.RegisterType((*RequestExtendVote)(nil), "tendermint.abci.RequestExtendVote")
proto.RegisterType((*RequestVerifyVoteExtension)(nil), "tendermint.abci.RequestVerifyVoteExtension")
proto.RegisterType((*RequestFinalizeBlock)(nil), "tendermint.abci.RequestFinalizeBlock")
proto.RegisterType((*Response)(nil), "tendermint.abci.Response")
proto.RegisterType((*ResponseException)(nil), "tendermint.abci.ResponseException")
proto.RegisterType((*ResponseEcho)(nil), "tendermint.abci.ResponseEcho")
proto.RegisterType((*ResponseFlush)(nil), "tendermint.abci.ResponseFlush")
proto.RegisterType((*ResponseInfo)(nil), "tendermint.abci.ResponseInfo")
proto.RegisterType((*ResponseInitChain)(nil), "tendermint.abci.ResponseInitChain")
proto.RegisterType((*ResponseQuery)(nil), "tendermint.abci.ResponseQuery")
proto.RegisterType((*ResponseCheckTx)(nil), "tendermint.abci.ResponseCheckTx")
proto.RegisterType((*ResponseCommit)(nil), "tendermint.abci.ResponseCommit")
proto.RegisterType((*ResponseListSnapshots)(nil), "tendermint.abci.ResponseListSnapshots")
proto.RegisterType((*ResponseOfferSnapshot)(nil), "tendermint.abci.ResponseOfferSnapshot")
proto.RegisterType((*ResponseLoadSnapshotChunk)(nil), "tendermint.abci.ResponseLoadSnapshotChunk")
proto.RegisterType((*ResponseApplySnapshotChunk)(nil), "tendermint.abci.ResponseApplySnapshotChunk")
proto.RegisterType((*ResponsePrepareProposal)(nil), "tendermint.abci.ResponsePrepareProposal")
proto.RegisterType((*ResponseProcessProposal)(nil), "tendermint.abci.ResponseProcessProposal")
proto.RegisterType((*ResponseExtendVote)(nil), "tendermint.abci.ResponseExtendVote")
proto.RegisterType((*ResponseVerifyVoteExtension)(nil), "tendermint.abci.ResponseVerifyVoteExtension")
proto.RegisterType((*ResponseFinalizeBlock)(nil), "tendermint.abci.ResponseFinalizeBlock")
proto.RegisterType((*CommitInfo)(nil), "tendermint.abci.CommitInfo")
proto.RegisterType((*ExtendedCommitInfo)(nil), "tendermint.abci.ExtendedCommitInfo")
proto.RegisterType((*Event)(nil), "tendermint.abci.Event")
proto.RegisterType((*EventAttribute)(nil), "tendermint.abci.EventAttribute")
proto.RegisterType((*ExecTxResult)(nil), "tendermint.abci.ExecTxResult")
proto.RegisterType((*TxResult)(nil), "tendermint.abci.TxResult")
proto.RegisterType((*Validator)(nil), "tendermint.abci.Validator")
proto.RegisterType((*ValidatorUpdate)(nil), "tendermint.abci.ValidatorUpdate")
proto.RegisterType((*VoteInfo)(nil), "tendermint.abci.VoteInfo")
proto.RegisterType((*ExtendedVoteInfo)(nil), "tendermint.abci.ExtendedVoteInfo")
proto.RegisterType((*Misbehavior)(nil), "tendermint.abci.Misbehavior")
proto.RegisterType((*Snapshot)(nil), "tendermint.abci.Snapshot")
}
func init() { proto.RegisterFile("tendermint/abci/types.proto", fileDescriptor_252557cfdd89a31a) }
var fileDescriptor_252557cfdd89a31a = []byte{
// 3167 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x5a, 0xcb, 0x73, 0x23, 0xd5,
0xd5, 0x57, 0xeb, 0xad, 0xa3, 0x87, 0xdb, 0xd7, 0x9e, 0x41, 0x23, 0x06, 0xdb, 0x34, 0x05, 0x0c,
0x03, 0xd8, 0x7c, 0x9e, 0x6f, 0x78, 0xd4, 0xc0, 0x57, 0x25, 0x6b, 0x34, 0x9f, 0xec, 0x31, 0xb6,
0x69, 0xcb, 0x43, 0x91, 0x07, 0x4d, 0x5b, 0xba, 0xb2, 0x9a, 0x91, 0xd4, 0x4d, 0xf7, 0x95, 0x91,
0x59, 0xa5, 0x42, 0x52, 0x95, 0x62, 0x45, 0x55, 0xb2, 0x60, 0x11, 0x16, 0x59, 0x64, 0x93, 0xbf,
0x20, 0xab, 0x64, 0x93, 0x05, 0x8b, 0x2c, 0x58, 0x66, 0x45, 0x52, 0xb0, 0x63, 0x9b, 0x45, 0xb6,
0xa9, 0xfb, 0xe8, 0x97, 0xa4, 0xb6, 0xa4, 0x81, 0x2c, 0x52, 0xc9, 0xae, 0xef, 0xe9, 0x73, 0xce,
0xed, 0x7b, 0xee, 0xb9, 0xe7, 0xf1, 0xeb, 0x0b, 0x8f, 0x13, 0x3c, 0x68, 0x63, 0xbb, 0x6f, 0x0c,
0xc8, 0x96, 0x7e, 0xda, 0x32, 0xb6, 0xc8, 0x85, 0x85, 0x9d, 0x4d, 0xcb, 0x36, 0x89, 0x89, 0x96,
0xfc, 0x97, 0x9b, 0xf4, 0x65, 0xe5, 0x89, 0x00, 0x77, 0xcb, 0xbe, 0xb0, 0x88, 0xb9, 0x65, 0xd9,
0xa6, 0xd9, 0xe1, 0xfc, 0x95, 0xeb, 0x93, 0xaf, 0x1f, 0xe2, 0x0b, 0xa1, 0x2d, 0x24, 0xcc, 0x66,
0xd9, 0xb2, 0x74, 0x5b, 0xef, 0xbb, 0xaf, 0x37, 0x26, 0x5e, 0x9f, 0xeb, 0x3d, 0xa3, 0xad, 0x13,
0xd3, 0x16, 0x1c, 0xeb, 0x67, 0xa6, 0x79, 0xd6, 0xc3, 0x5b, 0x6c, 0x74, 0x3a, 0xec, 0x6c, 0x11,
0xa3, 0x8f, 0x1d, 0xa2, 0xf7, 0x2d, 0xc1, 0xb0, 0x7a, 0x66, 0x9e, 0x99, 0xec, 0x71, 0x8b, 0x3e,
0x71, 0xaa, 0xf2, 0xc7, 0x1c, 0x64, 0x54, 0xfc, 0xc1, 0x10, 0x3b, 0x04, 0x6d, 0x43, 0x12, 0xb7,
0xba, 0x66, 0x59, 0xda, 0x90, 0x6e, 0xe4, 0xb7, 0xaf, 0x6f, 0x8e, 0x2d, 0x70, 0x53, 0xf0, 0xd5,
0x5b, 0x5d, 0xb3, 0x11, 0x53, 0x19, 0x2f, 0xba, 0x0d, 0xa9, 0x4e, 0x6f, 0xe8, 0x74, 0xcb, 0x71,
0x26, 0xf4, 0x44, 0x94, 0xd0, 0x3d, 0xca, 0xd4, 0x88, 0xa9, 0x9c, 0x9b, 0x4e, 0x65, 0x0c, 0x3a,
0x66, 0x39, 0x71, 0xf9, 0x54, 0xbb, 0x83, 0x0e, 0x9b, 0x8a, 0xf2, 0xa2, 0x1d, 0x00, 0x63, 0x60,
0x10, 0xad, 0xd5, 0xd5, 0x8d, 0x41, 0x39, 0xc5, 0x24, 0x9f, 0x8c, 0x96, 0x34, 0x48, 0x8d, 0x32,
0x36, 0x62, 0x6a, 0xce, 0x70, 0x07, 0xf4, 0x73, 0x3f, 0x18, 0x62, 0xfb, 0xa2, 0x9c, 0xbe, 0xfc,
0x73, 0xdf, 0xa2, 0x4c, 0xf4, 0x73, 0x19, 0x37, 0x7a, 0x1d, 0xb2, 0xad, 0x2e, 0x6e, 0x3d, 0xd4,
0xc8, 0xa8, 0x9c, 0x65, 0x92, 0xeb, 0x51, 0x92, 0x35, 0xca, 0xd7, 0x1c, 0x35, 0x62, 0x6a, 0xa6,
0xc5, 0x1f, 0xd1, 0xab, 0x90, 0x6e, 0x99, 0xfd, 0xbe, 0x41, 0xca, 0x79, 0x26, 0xbb, 0x16, 0x29,
0xcb, 0xb8, 0x1a, 0x31, 0x55, 0xf0, 0xa3, 0x03, 0x28, 0xf5, 0x0c, 0x87, 0x68, 0xce, 0x40, 0xb7,
0x9c, 0xae, 0x49, 0x9c, 0x72, 0x81, 0x69, 0x78, 0x3a, 0x4a, 0xc3, 0xbe, 0xe1, 0x90, 0x63, 0x97,
0xb9, 0x11, 0x53, 0x8b, 0xbd, 0x20, 0x81, 0xea, 0x33, 0x3b, 0x1d, 0x6c, 0x7b, 0x0a, 0xcb, 0xc5,
0xcb, 0xf5, 0x1d, 0x52, 0x6e, 0x57, 0x9e, 0xea, 0x33, 0x83, 0x04, 0xf4, 0x43, 0x58, 0xe9, 0x99,
0x7a, 0xdb, 0x53, 0xa7, 0xb5, 0xba, 0xc3, 0xc1, 0xc3, 0x72, 0x89, 0x29, 0x7d, 0x2e, 0xf2, 0x23,
0x4d, 0xbd, 0xed, 0xaa, 0xa8, 0x51, 0x81, 0x46, 0x4c, 0x5d, 0xee, 0x8d, 0x13, 0xd1, 0xbb, 0xb0,
0xaa, 0x5b, 0x56, 0xef, 0x62, 0x5c, 0xfb, 0x12, 0xd3, 0x7e, 0x33, 0x4a, 0x7b, 0x95, 0xca, 0x8c,
0xab, 0x47, 0xfa, 0x04, 0x15, 0x35, 0x41, 0xb6, 0x6c, 0x6c, 0xe9, 0x36, 0xd6, 0x2c, 0xdb, 0xb4,
0x4c, 0x47, 0xef, 0x95, 0x65, 0xa6, 0xfb, 0xd9, 0x28, 0xdd, 0x47, 0x9c, 0xff, 0x48, 0xb0, 0x37,
0x62, 0xea, 0x92, 0x15, 0x26, 0x71, 0xad, 0x66, 0x0b, 0x3b, 0x8e, 0xaf, 0x75, 0x79, 0x96, 0x56,
0xc6, 0x1f, 0xd6, 0x1a, 0x22, 0xa1, 0x3a, 0xe4, 0xf1, 0x88, 0x8a, 0x6b, 0xe7, 0x26, 0xc1, 0x65,
0xc4, 0x14, 0x2a, 0x91, 0x27, 0x94, 0xb1, 0x3e, 0x30, 0x09, 0x6e, 0xc4, 0x54, 0xc0, 0xde, 0x08,
0xe9, 0x70, 0xe5, 0x1c, 0xdb, 0x46, 0xe7, 0x82, 0xa9, 0xd1, 0xd8, 0x1b, 0xc7, 0x30, 0x07, 0xe5,
0x15, 0xa6, 0xf0, 0xf9, 0x28, 0x85, 0x0f, 0x98, 0x10, 0x55, 0x51, 0x77, 0x45, 0x1a, 0x31, 0x75,
0xe5, 0x7c, 0x92, 0x4c, 0x5d, 0xac, 0x63, 0x0c, 0xf4, 0x9e, 0xf1, 0x11, 0xd6, 0x4e, 0x7b, 0x66,
0xeb, 0x61, 0x79, 0xf5, 0x72, 0x17, 0xbb, 0x27, 0xb8, 0x77, 0x28, 0x33, 0x75, 0xb1, 0x4e, 0x90,
0xb0, 0x93, 0x81, 0xd4, 0xb9, 0xde, 0x1b, 0xe2, 0xbd, 0x64, 0x36, 0x29, 0xa7, 0xf6, 0x92, 0xd9,
0x8c, 0x9c, 0xdd, 0x4b, 0x66, 0x73, 0x32, 0xec, 0x25, 0xb3, 0x20, 0xe7, 0x95, 0x67, 0x21, 0x1f,
0x08, 0x4c, 0xa8, 0x0c, 0x99, 0x3e, 0x76, 0x1c, 0xfd, 0x0c, 0xb3, 0x38, 0x96, 0x53, 0xdd, 0xa1,
0x52, 0x82, 0x42, 0x30, 0x18, 0x29, 0x9f, 0x4a, 0x9e, 0x24, 0x8d, 0x33, 0x54, 0xf2, 0x1c, 0xdb,
0xcc, 0x1c, 0x42, 0x52, 0x0c, 0xd1, 0x53, 0x50, 0x64, 0x4b, 0xd1, 0xdc, 0xf7, 0x34, 0xd8, 0x25,
0xd5, 0x02, 0x23, 0x3e, 0x10, 0x4c, 0xeb, 0x90, 0xb7, 0xb6, 0x2d, 0x8f, 0x25, 0xc1, 0x58, 0xc0,
0xda, 0xb6, 0x5c, 0x86, 0x27, 0xa1, 0x40, 0xd7, 0xed, 0x71, 0x24, 0xd9, 0x24, 0x79, 0x4a, 0x13,
0x2c, 0xca, 0x9f, 0xe3, 0x20, 0x8f, 0x07, 0x30, 0xf4, 0x2a, 0x24, 0x69, 0x2c, 0x17, 0x61, 0xb9,
0xb2, 0xc9, 0x03, 0xfd, 0xa6, 0x1b, 0xe8, 0x37, 0x9b, 0x6e, 0xa0, 0xdf, 0xc9, 0x7e, 0xf1, 0xd5,
0x7a, 0xec, 0xd3, 0xbf, 0xae, 0x4b, 0x2a, 0x93, 0x40, 0xd7, 0x68, 0xd8, 0xd2, 0x8d, 0x81, 0x66,
0xb4, 0xd9, 0x27, 0xe7, 0x68, 0x4c, 0xd2, 0x8d, 0xc1, 0x6e, 0x1b, 0xed, 0x83, 0xdc, 0x32, 0x07,
0x0e, 0x1e, 0x38, 0x43, 0x47, 0xe3, 0xa9, 0x46, 0x04, 0xe3, 0x50, 0x48, 0xe5, 0x09, 0xaf, 0xe6,
0x72, 0x1e, 0x31, 0x46, 0x75, 0xa9, 0x15, 0x26, 0xa0, 0x7b, 0x00, 0x5e, 0x3e, 0x72, 0xca, 0xc9,
0x8d, 0xc4, 0x8d, 0xfc, 0xf6, 0xc6, 0xc4, 0x86, 0x3f, 0x70, 0x59, 0x4e, 0xac, 0xb6, 0x4e, 0xf0,
0x4e, 0x92, 0x7e, 0xae, 0x1a, 0x90, 0x44, 0xcf, 0xc0, 0x92, 0x6e, 0x59, 0x9a, 0x43, 0x74, 0x82,
0xb5, 0xd3, 0x0b, 0x82, 0x1d, 0x16, 0xe7, 0x0b, 0x6a, 0x51, 0xb7, 0xac, 0x63, 0x4a, 0xdd, 0xa1,
0x44, 0xf4, 0x34, 0x94, 0x68, 0x4c, 0x37, 0xf4, 0x9e, 0xd6, 0xc5, 0xc6, 0x59, 0x97, 0xb0, 0x78,
0x9e, 0x50, 0x8b, 0x82, 0xda, 0x60, 0x44, 0xa5, 0xed, 0xed, 0x38, 0x8b, 0xe7, 0x08, 0x41, 0xb2,
0xad, 0x13, 0x9d, 0x59, 0xb2, 0xa0, 0xb2, 0x67, 0x4a, 0xb3, 0x74, 0xd2, 0x15, 0xf6, 0x61, 0xcf,
0xe8, 0x2a, 0xa4, 0x85, 0xda, 0x04, 0x53, 0x2b, 0x46, 0x68, 0x15, 0x52, 0x96, 0x6d, 0x9e, 0x63,
0xb6, 0x75, 0x59, 0x95, 0x0f, 0x14, 0x15, 0x4a, 0xe1, 0xd8, 0x8f, 0x4a, 0x10, 0x27, 0x23, 0x31,
0x4b, 0x9c, 0x8c, 0xd0, 0x4b, 0x90, 0xa4, 0x86, 0x64, 0x73, 0x94, 0xa6, 0x64, 0x3b, 0x21, 0xd7,
0xbc, 0xb0, 0xb0, 0xca, 0x38, 0x95, 0x25, 0x28, 0x86, 0x72, 0x82, 0x72, 0x15, 0x56, 0xa7, 0x85,
0x78, 0xa5, 0xeb, 0xd1, 0x43, 0xa1, 0x1a, 0xdd, 0x86, 0xac, 0x17, 0xe3, 0xb9, 0xe3, 0x5c, 0x9b,
0x98, 0xd6, 0x65, 0x56, 0x3d, 0x56, 0xea, 0x31, 0x74, 0x03, 0xba, 0xba, 0xc8, 0xe8, 0x05, 0x35,
0xa3, 0x5b, 0x56, 0x43, 0x77, 0xba, 0xca, 0x7b, 0x50, 0x8e, 0x8a, 0xdf, 0x01, 0x83, 0x49, 0xcc,
0xed, 0x5d, 0x83, 0x5d, 0x85, 0x74, 0xc7, 0xb4, 0xfb, 0x3a, 0x61, 0xca, 0x8a, 0xaa, 0x18, 0x51,
0x43, 0xf2, 0x58, 0x9e, 0x60, 0x64, 0x3e, 0x50, 0x34, 0xb8, 0x16, 0x19, 0xc3, 0xa9, 0x88, 0x31,
0x68, 0x63, 0x6e, 0xd6, 0xa2, 0xca, 0x07, 0xbe, 0x22, 0xfe, 0xb1, 0x7c, 0x40, 0xa7, 0x75, 0xd8,
0x5a, 0x99, 0xfe, 0x9c, 0x2a, 0x46, 0xca, 0x67, 0x09, 0xb8, 0x3a, 0x3d, 0x92, 0xa3, 0x0d, 0x28,
0xf4, 0xf5, 0x91, 0x46, 0x46, 0xc2, 0xed, 0x24, 0xb6, 0xf1, 0xd0, 0xd7, 0x47, 0xcd, 0x11, 0xf7,
0x39, 0x19, 0x12, 0x64, 0xe4, 0x94, 0xe3, 0x1b, 0x89, 0x1b, 0x05, 0x95, 0x3e, 0xa2, 0x13, 0x58,
0xee, 0x99, 0x2d, 0xbd, 0xa7, 0xf5, 0x74, 0x87, 0x68, 0x22, 0xc5, 0xf3, 0x43, 0xf4, 0xd4, 0x84,
0xb1, 0x79, 0x4c, 0xc6, 0x6d, 0xbe, 0x9f, 0x34, 0xe0, 0x08, 0xff, 0x5f, 0x62, 0x3a, 0xf6, 0x75,
0x77, 0xab, 0xd1, 0x5d, 0xc8, 0xf7, 0x0d, 0xe7, 0x14, 0x77, 0xf5, 0x73, 0xc3, 0xb4, 0xc5, 0x69,
0x9a, 0x74, 0x9a, 0x37, 0x7d, 0x1e, 0xa1, 0x29, 0x28, 0x16, 0xd8, 0x92, 0x54, 0xc8, 0x87, 0xdd,
0x68, 0x92, 0x5e, 0x38, 0x9a, 0xbc, 0x04, 0xab, 0x03, 0x3c, 0x22, 0x9a, 0x7f, 0x5e, 0xb9, 0x9f,
0x64, 0x98, 0xe9, 0x11, 0x7d, 0xe7, 0x9d, 0x70, 0x87, 0xba, 0x0c, 0x7a, 0x8e, 0xe5, 0x42, 0xcb,
0x74, 0xb0, 0xad, 0xe9, 0xed, 0xb6, 0x8d, 0x1d, 0x87, 0x95, 0x4f, 0x05, 0x96, 0xe0, 0x18, 0xbd,
0xca, 0xc9, 0xca, 0x2f, 0x82, 0x5b, 0x13, 0xce, 0x7d, 0xc2, 0xf0, 0x92, 0x6f, 0xf8, 0x63, 0x58,
0x15, 0xf2, 0xed, 0x90, 0xed, 0x79, 0x0d, 0xfa, 0xf8, 0xe4, 0xf9, 0x1a, 0xb7, 0x39, 0x72, 0xc5,
0xa3, 0xcd, 0x9e, 0x78, 0x34, 0xb3, 0x23, 0x48, 0x32, 0xa3, 0x24, 0x79, 0x88, 0xa1, 0xcf, 0xff,
0x6e, 0x5b, 0xf1, 0x71, 0x02, 0x96, 0x27, 0x0a, 0x09, 0x6f, 0x61, 0xd2, 0xd4, 0x85, 0xc5, 0xa7,
0x2e, 0x2c, 0xb1, 0xf0, 0xc2, 0xc4, 0x5e, 0x27, 0x67, 0xef, 0x75, 0xea, 0x7b, 0xdc, 0xeb, 0xf4,
0xa3, 0xed, 0xf5, 0xbf, 0x74, 0x17, 0x7e, 0x2d, 0x41, 0x25, 0xba, 0xfa, 0x9a, 0xba, 0x1d, 0xcf,
0xc3, 0xb2, 0xf7, 0x29, 0x9e, 0x7a, 0x1e, 0x18, 0x65, 0xef, 0x85, 0xd0, 0x1f, 0x99, 0xe3, 0x9e,
0x86, 0xd2, 0x58, 0x6d, 0xc8, 0x5d, 0xb9, 0x78, 0x1e, 0x9c, 0x5f, 0xf9, 0x59, 0xc2, 0x4b, 0x3c,
0xa1, 0x02, 0x6e, 0xca, 0x69, 0x7d, 0x0b, 0x56, 0xda, 0xb8, 0x65, 0xb4, 0x1f, 0xf5, 0xb0, 0x2e,
0x0b, 0xe9, 0xff, 0x9e, 0xd5, 0x49, 0x2f, 0xf9, 0x15, 0x40, 0x56, 0xc5, 0x8e, 0x45, 0xeb, 0x31,
0xb4, 0x03, 0x39, 0x3c, 0x6a, 0x61, 0x8b, 0xb8, 0x25, 0xec, 0xf4, 0x16, 0x81, 0x73, 0xd7, 0x5d,
0x4e, 0xda, 0x20, 0x7b, 0x62, 0xe8, 0x96, 0xc0, 0x00, 0xa2, 0xdb, 0x79, 0x21, 0x1e, 0x04, 0x01,
0x5e, 0x76, 0x41, 0x80, 0x44, 0x64, 0x7f, 0xcb, 0xa5, 0xc6, 0x50, 0x80, 0x5b, 0x02, 0x05, 0x48,
0xce, 0x98, 0x2c, 0x04, 0x03, 0xd4, 0x42, 0x30, 0x40, 0x7a, 0xc6, 0x32, 0x23, 0x70, 0x80, 0x97,
0x5d, 0x1c, 0x20, 0x33, 0xe3, 0x8b, 0xc7, 0x80, 0x80, 0x37, 0x02, 0x40, 0x40, 0x8e, 0x89, 0x6e,
0x44, 0x8a, 0x4e, 0x41, 0x02, 0x5e, 0xf3, 0x90, 0x80, 0x42, 0x24, 0x8a, 0x20, 0x84, 0xc7, 0xa1,
0x80, 0xc3, 0x09, 0x28, 0x80, 0xb7, 0xee, 0xcf, 0x44, 0xaa, 0x98, 0x81, 0x05, 0x1c, 0x4e, 0x60,
0x01, 0xa5, 0x19, 0x0a, 0x67, 0x80, 0x01, 0x3f, 0x9a, 0x0e, 0x06, 0x44, 0xb7, 0xeb, 0xe2, 0x33,
0xe7, 0x43, 0x03, 0xb4, 0x08, 0x34, 0x40, 0x8e, 0xec, 0x5c, 0xb9, 0xfa, 0xb9, 0xe1, 0x80, 0x93,
0x29, 0x70, 0x00, 0x6f, 0xdc, 0x6f, 0x44, 0x2a, 0x9f, 0x03, 0x0f, 0x38, 0x99, 0x82, 0x07, 0xa0,
0x99, 0x6a, 0x67, 0x02, 0x02, 0xf7, 0xc2, 0x80, 0xc0, 0x4a, 0x44, 0xd5, 0xe9, 0x9f, 0xf6, 0x08,
0x44, 0xe0, 0x34, 0x0a, 0x11, 0xe0, 0x5d, 0xfb, 0x0b, 0x91, 0x1a, 0x17, 0x80, 0x04, 0x0e, 0x27,
0x20, 0x81, 0x2b, 0x33, 0x3c, 0x6d, 0x7e, 0x4c, 0x20, 0x25, 0xa7, 0xf7, 0x92, 0xd9, 0xac, 0x9c,
0xe3, 0x68, 0xc0, 0x5e, 0x32, 0x9b, 0x97, 0x0b, 0xca, 0x73, 0xb4, 0x82, 0x19, 0x8b, 0x73, 0xb4,
0x57, 0xc0, 0xb6, 0x6d, 0xda, 0xa2, 0xbb, 0xe7, 0x03, 0xe5, 0x06, 0xed, 0x11, 0xfd, 0x98, 0x76,
0x09, 0x7e, 0xc0, 0x7a, 0xb2, 0x40, 0x1c, 0x53, 0x7e, 0x2f, 0xf9, 0xb2, 0x0c, 0x41, 0x08, 0xf6,
0x97, 0x39, 0xd1, 0x5f, 0x06, 0x50, 0x85, 0x78, 0x18, 0x55, 0x58, 0x87, 0x3c, 0xed, 0xb5, 0xc6,
0x00, 0x03, 0xdd, 0xf2, 0x00, 0x83, 0x9b, 0xb0, 0xcc, 0x12, 0x26, 0xc7, 0x1e, 0x44, 0x5a, 0x4a,
0xb2, 0xb4, 0xb4, 0x44, 0x5f, 0x70, 0xeb, 0xf0, 0xfc, 0xf4, 0x22, 0xac, 0x04, 0x78, 0xbd, 0x1e,
0x8e, 0x77, 0xcf, 0xb2, 0xc7, 0x5d, 0x15, 0xcd, 0xdc, 0x9f, 0x24, 0xdf, 0x42, 0x3e, 0xd2, 0x30,
0x0d, 0x14, 0x90, 0xbe, 0x27, 0x50, 0x20, 0xfe, 0xc8, 0xa0, 0x40, 0xb0, 0x27, 0x4d, 0x84, 0x7b,
0xd2, 0x7f, 0x48, 0xfe, 0x9e, 0x78, 0x2d, 0x7e, 0xcb, 0x6c, 0x63, 0xd1, 0x25, 0xb2, 0x67, 0x5a,
0x92, 0xf4, 0xcc, 0x33, 0xd1, 0x0b, 0xd2, 0x47, 0xca, 0xe5, 0x25, 0x9e, 0x9c, 0xc8, 0x2b, 0x5e,
0x83, 0xc9, 0x13, 0xbf, 0x68, 0x30, 0x65, 0x48, 0x3c, 0xc4, 0x1c, 0x2e, 0x2e, 0xa8, 0xf4, 0x91,
0xf2, 0x31, 0xe7, 0x13, 0x09, 0x9c, 0x0f, 0xd0, 0xab, 0x90, 0x63, 0x60, 0xbf, 0x66, 0x5a, 0x8e,
0x80, 0x88, 0x43, 0xa5, 0x0d, 0x47, 0xfc, 0x37, 0x8f, 0x28, 0xcf, 0xa1, 0xe5, 0xa8, 0x59, 0x4b,
0x3c, 0x05, 0x2a, 0x8e, 0x5c, 0xa8, 0xe2, 0xb8, 0x0e, 0x39, 0xfa, 0xf5, 0x8e, 0xa5, 0xb7, 0x70,
0x19, 0xd8, 0x87, 0xfa, 0x04, 0xe5, 0x77, 0x71, 0x58, 0x1a, 0x4b, 0x34, 0x53, 0xd7, 0xee, 0xba,
0x64, 0x3c, 0x00, 0x79, 0xcc, 0x67, 0x8f, 0x35, 0x80, 0x33, 0xdd, 0xd1, 0x3e, 0xd4, 0x07, 0x04,
0xb7, 0x85, 0x51, 0x02, 0x14, 0x54, 0x81, 0x2c, 0x1d, 0x0d, 0x1d, 0xdc, 0x16, 0xe8, 0x8b, 0x37,
0x46, 0x0d, 0x48, 0xe3, 0x73, 0x3c, 0x20, 0x4e, 0x39, 0xc3, 0xb6, 0xfd, 0xea, 0x64, 0x3b, 0x4c,
0x5f, 0xef, 0x94, 0xe9, 0x66, 0x7f, 0xfb, 0xd5, 0xba, 0xcc, 0xb9, 0x5f, 0x30, 0xfb, 0x06, 0xc1,
0x7d, 0x8b, 0x5c, 0xa8, 0x42, 0x3e, 0x6c, 0x85, 0xec, 0x98, 0x15, 0x18, 0x0e, 0x58, 0x70, 0xdb,
0x7b, 0x6a, 0x53, 0xc3, 0xb4, 0x0d, 0x72, 0xa1, 0x16, 0xfb, 0xb8, 0x6f, 0x99, 0x66, 0x4f, 0xe3,
0x67, 0xbc, 0x0a, 0xa5, 0x70, 0x5e, 0x45, 0x4f, 0x41, 0xd1, 0xc6, 0x44, 0x37, 0x06, 0x5a, 0xa8,
0x08, 0x2e, 0x70, 0x22, 0x3f, 0x53, 0x7b, 0xc9, 0xac, 0x24, 0xc7, 0xf7, 0x92, 0xd9, 0xb8, 0x9c,
0x50, 0x8e, 0xe0, 0xca, 0xd4, 0xbc, 0x8a, 0x5e, 0x81, 0x9c, 0x9f, 0x92, 0x25, 0xb6, 0xda, 0x4b,
0x90, 0x16, 0x9f, 0x57, 0xf9, 0x83, 0xe4, 0xab, 0x0c, 0x63, 0x37, 0x75, 0x48, 0xdb, 0xd8, 0x19,
0xf6, 0x38, 0x9a, 0x52, 0xda, 0x7e, 0x71, 0xbe, 0x8c, 0x4c, 0xa9, 0xc3, 0x1e, 0x51, 0x85, 0xb0,
0xf2, 0x2e, 0xa4, 0x39, 0x05, 0xe5, 0x21, 0x73, 0x72, 0x70, 0xff, 0xe0, 0xf0, 0xed, 0x03, 0x39,
0x86, 0x00, 0xd2, 0xd5, 0x5a, 0xad, 0x7e, 0xd4, 0x94, 0x25, 0x94, 0x83, 0x54, 0x75, 0xe7, 0x50,
0x6d, 0xca, 0x71, 0x4a, 0x56, 0xeb, 0x7b, 0xf5, 0x5a, 0x53, 0x4e, 0xa0, 0x65, 0x28, 0xf2, 0x67,
0xed, 0xde, 0xa1, 0xfa, 0x66, 0xb5, 0x29, 0x27, 0x03, 0xa4, 0xe3, 0xfa, 0xc1, 0xdd, 0xba, 0x2a,
0xa7, 0x94, 0xff, 0x81, 0x6b, 0x91, 0x39, 0xdc, 0x07, 0x66, 0xa4, 0x00, 0x30, 0xa3, 0x7c, 0x16,
0xa7, 0x4d, 0x4d, 0x54, 0x62, 0x46, 0x7b, 0x63, 0x0b, 0xdf, 0x5e, 0x20, 0xab, 0x8f, 0xad, 0x9e,
0xf6, 0x31, 0x36, 0xee, 0x60, 0xd2, 0xea, 0xf2, 0x42, 0x81, 0x47, 0xa0, 0xa2, 0x5a, 0x14, 0x54,
0x26, 0xe4, 0x70, 0xb6, 0xf7, 0x71, 0x8b, 0x68, 0xdc, 0x89, 0x1c, 0xd6, 0x4c, 0xe4, 0x28, 0x1b,
0xa5, 0x1e, 0x73, 0xa2, 0xf2, 0xde, 0x42, 0xb6, 0xcc, 0x41, 0x4a, 0xad, 0x37, 0xd5, 0x77, 0xe4,
0x04, 0x42, 0x50, 0x62, 0x8f, 0xda, 0xf1, 0x41, 0xf5, 0xe8, 0xb8, 0x71, 0x48, 0x6d, 0xb9, 0x02,
0x4b, 0xae, 0x2d, 0x5d, 0x62, 0x4a, 0x79, 0x1e, 0x1e, 0x8b, 0xa8, 0x2a, 0x26, 0x5b, 0x2a, 0xe5,
0x37, 0x52, 0x90, 0x3b, 0x5c, 0x19, 0x1c, 0x42, 0xda, 0x21, 0x3a, 0x19, 0x3a, 0xc2, 0x88, 0xaf,
0xcc, 0x5b, 0x66, 0x6c, 0xba, 0x0f, 0xc7, 0x4c, 0x5c, 0x15, 0x6a, 0x94, 0xdb, 0x50, 0x0a, 0xbf,
0x89, 0xb6, 0x81, 0xef, 0x44, 0x71, 0xe5, 0x0e, 0xa0, 0xc9, 0xea, 0x63, 0x4a, 0x7b, 0x29, 0x4d,
0x6b, 0x2f, 0x7f, 0x2b, 0xc1, 0xe3, 0x97, 0x54, 0x1a, 0xe8, 0xad, 0xb1, 0x45, 0xbe, 0xb6, 0x48,
0x9d, 0xb2, 0xc9, 0x69, 0x63, 0xcb, 0xbc, 0x05, 0x85, 0x20, 0x7d, 0xbe, 0x45, 0x7e, 0x1b, 0xf7,
0x0f, 0x71, 0xb8, 0x0f, 0xf6, 0x43, 0xa0, 0xf4, 0x1d, 0x43, 0xe0, 0xeb, 0x00, 0x64, 0xa4, 0x71,
0xb7, 0x76, 0xf3, 0xe8, 0x13, 0x53, 0xf0, 0x45, 0xdc, 0x6a, 0x8e, 0xc4, 0x21, 0xc8, 0x11, 0xf1,
0xe4, 0xa0, 0xe3, 0x20, 0x28, 0x30, 0x64, 0x39, 0xd6, 0x11, 0x0d, 0xf3, 0xbc, 0xc9, 0xd8, 0x07,
0x0f, 0x38, 0xd9, 0x41, 0xef, 0xc0, 0x63, 0x63, 0x85, 0x82, 0xa7, 0x3a, 0x39, 0x6f, 0xbd, 0x70,
0x25, 0x5c, 0x2f, 0xb8, 0xaa, 0x83, 0xd9, 0x3e, 0x15, 0xce, 0xf6, 0xef, 0x00, 0xf8, 0xe0, 0x00,
0x8d, 0x30, 0xb6, 0x39, 0x1c, 0xb4, 0x99, 0x07, 0xa4, 0x54, 0x3e, 0x40, 0xb7, 0x21, 0x45, 0x3d,
0xc9, 0xb5, 0xd3, 0x64, 0x28, 0xa6, 0x9e, 0x10, 0x00, 0x17, 0x38, 0xb7, 0x62, 0x00, 0x9a, 0x04,
0x68, 0x23, 0xa6, 0x78, 0x23, 0x3c, 0xc5, 0x93, 0x91, 0x50, 0xef, 0xf4, 0xa9, 0x3e, 0x82, 0x14,
0xdb, 0x79, 0x9a, 0x74, 0xd9, 0x5f, 0x01, 0x51, 0x2d, 0xd2, 0x67, 0xf4, 0x63, 0x00, 0x9d, 0x10,
0xdb, 0x38, 0x1d, 0xfa, 0x13, 0xac, 0x4f, 0xf7, 0x9c, 0xaa, 0xcb, 0xb7, 0x73, 0x5d, 0xb8, 0xd0,
0xaa, 0x2f, 0x1a, 0x70, 0xa3, 0x80, 0x42, 0xe5, 0x00, 0x4a, 0x61, 0x59, 0xb7, 0xbe, 0xe1, 0xdf,
0x10, 0xae, 0x6f, 0x78, 0xb9, 0x2a, 0xea, 0x1b, 0xaf, 0x3a, 0x4a, 0xf0, 0x5f, 0x1f, 0x6c, 0xa0,
0xfc, 0x24, 0x0e, 0x85, 0xa0, 0xe3, 0xfd, 0xe7, 0x95, 0x20, 0xca, 0xcf, 0x25, 0xc8, 0x7a, 0xcb,
0x0f, 0xff, 0x07, 0x09, 0xfd, 0x38, 0xe2, 0xd6, 0x8b, 0x07, 0x7f, 0x5e, 0xf0, 0xdf, 0x44, 0x09,
0xef, 0x37, 0xd1, 0x1d, 0x2f, 0xfd, 0x45, 0x01, 0x22, 0x41, 0x5b, 0x0b, 0xaf, 0x72, 0xb3, 0xfd,
0x1d, 0xc8, 0x79, 0xa7, 0x97, 0x36, 0x1d, 0x2e, 0x70, 0x24, 0x89, 0x33, 0x24, 0x60, 0xbf, 0x55,
0x48, 0x59, 0xe6, 0x87, 0xe2, 0xcf, 0x48, 0x42, 0xe5, 0x03, 0xa5, 0x0d, 0x4b, 0x63, 0x47, 0x1f,
0xdd, 0x81, 0x8c, 0x35, 0x3c, 0xd5, 0x5c, 0xe7, 0x18, 0x83, 0xd7, 0xdc, 0x72, 0x76, 0x78, 0xda,
0x33, 0x5a, 0xf7, 0xf1, 0x85, 0xfb, 0x31, 0xd6, 0xf0, 0xf4, 0x3e, 0xf7, 0x21, 0x3e, 0x4b, 0x3c,
0x38, 0xcb, 0x2f, 0x25, 0xc8, 0xba, 0x67, 0x02, 0xfd, 0x1f, 0xe4, 0xbc, 0xb0, 0xe2, 0xfd, 0xda,
0x8c, 0x8c, 0x47, 0x42, 0xbf, 0x2f, 0x82, 0xaa, 0xee, 0x3f, 0x59, 0xa3, 0xad, 0x75, 0x7a, 0x3a,
0xf7, 0xa5, 0x52, 0xd8, 0x66, 0x3c, 0xf0, 0xb0, 0x78, 0xbc, 0x7b, 0xf7, 0x5e, 0x4f, 0x3f, 0x53,
0xf3, 0x4c, 0x66, 0xb7, 0x4d, 0x07, 0xa2, 0xb2, 0xfb, 0xbb, 0x04, 0xf2, 0xf8, 0x89, 0xfd, 0xce,
0x5f, 0x37, 0x99, 0xe6, 0x12, 0x53, 0xd2, 0x1c, 0xda, 0x82, 0x15, 0x8f, 0x43, 0x73, 0x8c, 0xb3,
0x81, 0x4e, 0x86, 0x36, 0x16, 0x80, 0x24, 0xf2, 0x5e, 0x1d, 0xbb, 0x6f, 0x26, 0x57, 0x9d, 0x7a,
0xc4, 0x55, 0x7f, 0x1c, 0x87, 0x7c, 0x00, 0x1e, 0x45, 0xff, 0x1b, 0x08, 0x46, 0xa5, 0x29, 0x99,
0x21, 0xc0, 0xeb, 0xff, 0xa6, 0x0c, 0x9b, 0x29, 0xbe, 0xb8, 0x99, 0xa2, 0x40, 0x68, 0x17, 0x6d,
0x4d, 0x2e, 0x8c, 0xb6, 0xbe, 0x00, 0x88, 0x98, 0x44, 0xef, 0x69, 0xe7, 0x26, 0x31, 0x06, 0x67,
0x1a, 0x77, 0x43, 0x1e, 0x3a, 0x64, 0xf6, 0xe6, 0x01, 0x7b, 0x71, 0xc4, 0x3c, 0xf2, 0xa7, 0x12,
0x64, 0xbd, 0xb2, 0x7b, 0xd1, 0x9f, 0x98, 0x57, 0x21, 0x2d, 0x2a, 0x4b, 0xfe, 0x17, 0x53, 0x8c,
0xa6, 0xc2, 0xca, 0x15, 0xc8, 0xf6, 0x31, 0xd1, 0x59, 0x1c, 0xe4, 0x59, 0xcd, 0x1b, 0xdf, 0x7c,
0x0d, 0xf2, 0x81, 0x1f, 0xc0, 0x34, 0x34, 0x1e, 0xd4, 0xdf, 0x96, 0x63, 0x95, 0xcc, 0x27, 0x9f,
0x6f, 0x24, 0x0e, 0xf0, 0x87, 0xf4, 0x34, 0xab, 0xf5, 0x5a, 0xa3, 0x5e, 0xbb, 0x2f, 0x4b, 0x95,
0xfc, 0x27, 0x9f, 0x6f, 0x64, 0x54, 0xcc, 0x10, 0xc5, 0x9b, 0xf7, 0x61, 0x69, 0x6c, 0x63, 0xc2,
0x65, 0x0b, 0x82, 0xd2, 0xdd, 0x93, 0xa3, 0xfd, 0xdd, 0x5a, 0xb5, 0x59, 0xd7, 0x1e, 0x1c, 0x36,
0xeb, 0xb2, 0x84, 0x1e, 0x83, 0x95, 0xfd, 0xdd, 0xff, 0x6f, 0x34, 0xb5, 0xda, 0xfe, 0x6e, 0xfd,
0xa0, 0xa9, 0x55, 0x9b, 0xcd, 0x6a, 0xed, 0xbe, 0x1c, 0xdf, 0xfe, 0x3c, 0x0f, 0xc9, 0xea, 0x4e,
0x6d, 0x17, 0xd5, 0x20, 0xc9, 0xa0, 0x90, 0x4b, 0x6f, 0x80, 0x55, 0x2e, 0xc7, 0x86, 0xd1, 0x3d,
0x48, 0x31, 0x94, 0x04, 0x5d, 0x7e, 0x25, 0xac, 0x32, 0x03, 0x2c, 0xa6, 0x1f, 0xc3, 0x4e, 0xe4,
0xa5, 0x77, 0xc4, 0x2a, 0x97, 0x63, 0xc7, 0x68, 0x1f, 0x32, 0x6e, 0x93, 0x3c, 0xeb, 0xe2, 0x56,
0x65, 0x26, 0xa0, 0x4b, 0x97, 0xc6, 0xc1, 0x86, 0xcb, 0xaf, 0x8f, 0x55, 0x66, 0xa0, 0xca, 0x68,
0x17, 0xd2, 0xa2, 0x1d, 0x9d, 0x71, 0x23, 0xac, 0x32, 0x0b, 0x27, 0x46, 0x2a, 0xe4, 0x7c, 0x18,
0x67, 0xf6, 0xa5, 0xb8, 0xca, 0x1c, 0x80, 0x39, 0x7a, 0x17, 0x8a, 0xe1, 0x56, 0x77, 0xbe, 0x5b,
0x67, 0x95, 0x39, 0x11, 0x69, 0xaa, 0x3f, 0xdc, 0xf7, 0xce, 0x77, 0x0b, 0xad, 0x32, 0x27, 0x40,
0x8d, 0xde, 0x87, 0xe5, 0xc9, 0xbe, 0x74, 0xfe, 0x4b, 0x69, 0x95, 0x05, 0x20, 0x6b, 0xd4, 0x07,
0x34, 0xa5, 0x9f, 0x5d, 0xe0, 0x8e, 0x5a, 0x65, 0x11, 0x04, 0x1b, 0xb5, 0x61, 0x69, 0xbc, 0x49,
0x9c, 0xf7, 0xce, 0x5a, 0x65, 0x6e, 0x34, 0x9b, 0xcf, 0x12, 0x6e, 0x2e, 0xe7, 0xbd, 0xc3, 0x56,
0x99, 0x1b, 0xdc, 0x46, 0x27, 0x00, 0x81, 0xfe, 0x70, 0x8e, 0x3b, 0x6d, 0x95, 0x79, 0x60, 0x6e,
0x64, 0xc1, 0xca, 0xb4, 0xc6, 0x71, 0x91, 0x2b, 0x6e, 0x95, 0x85, 0xd0, 0x6f, 0xea, 0xcf, 0xe1,
0x16, 0x70, 0xbe, 0x2b, 0x6f, 0x95, 0x39, 0x61, 0xf0, 0x9d, 0xea, 0x17, 0x5f, 0xaf, 0x49, 0x5f,
0x7e, 0xbd, 0x26, 0xfd, 0xed, 0xeb, 0x35, 0xe9, 0xd3, 0x6f, 0xd6, 0x62, 0x5f, 0x7e, 0xb3, 0x16,
0xfb, 0xcb, 0x37, 0x6b, 0xb1, 0x1f, 0x3c, 0x7b, 0x66, 0x90, 0xee, 0xf0, 0x74, 0xb3, 0x65, 0xf6,
0xb7, 0x5a, 0x66, 0x1f, 0x93, 0xd3, 0x0e, 0xf1, 0x1f, 0xfc, 0x9b, 0xcb, 0xa7, 0x69, 0x96, 0x41,
0x6f, 0xfd, 0x33, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd0, 0x90, 0x6e, 0xd9, 0x2c, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// ABCIClient is the client API for ABCI service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type ABCIClient interface {
Echo(ctx context.Context, in *RequestEcho, opts ...grpc.CallOption) (*ResponseEcho, error)
Flush(ctx context.Context, in *RequestFlush, opts ...grpc.CallOption) (*ResponseFlush, error)
Info(ctx context.Context, in *RequestInfo, opts ...grpc.CallOption) (*ResponseInfo, error)
CheckTx(ctx context.Context, in *RequestCheckTx, opts ...grpc.CallOption) (*ResponseCheckTx, error)
Query(ctx context.Context, in *RequestQuery, opts ...grpc.CallOption) (*ResponseQuery, error)
Commit(ctx context.Context, in *RequestCommit, opts ...grpc.CallOption) (*ResponseCommit, error)
InitChain(ctx context.Context, in *RequestInitChain, opts ...grpc.CallOption) (*ResponseInitChain, error)
ListSnapshots(ctx context.Context, in *RequestListSnapshots, opts ...grpc.CallOption) (*ResponseListSnapshots, error)
OfferSnapshot(ctx context.Context, in *RequestOfferSnapshot, opts ...grpc.CallOption) (*ResponseOfferSnapshot, error)
LoadSnapshotChunk(ctx context.Context, in *RequestLoadSnapshotChunk, opts ...grpc.CallOption) (*ResponseLoadSnapshotChunk, error)
ApplySnapshotChunk(ctx context.Context, in *RequestApplySnapshotChunk, opts ...grpc.CallOption) (*ResponseApplySnapshotChunk, error)
PrepareProposal(ctx context.Context, in *RequestPrepareProposal, opts ...grpc.CallOption) (*ResponsePrepareProposal, error)
ProcessProposal(ctx context.Context, in *RequestProcessProposal, opts ...grpc.CallOption) (*ResponseProcessProposal, error)
ExtendVote(ctx context.Context, in *RequestExtendVote, opts ...grpc.CallOption) (*ResponseExtendVote, error)
VerifyVoteExtension(ctx context.Context, in *RequestVerifyVoteExtension, opts ...grpc.CallOption) (*ResponseVerifyVoteExtension, error)
FinalizeBlock(ctx context.Context, in *RequestFinalizeBlock, opts ...grpc.CallOption) (*ResponseFinalizeBlock, error)
}
type aBCIClient struct {
cc grpc1.ClientConn
}
func NewABCIClient(cc grpc1.ClientConn) ABCIClient {
return &aBCIClient{cc}
}
func (c *aBCIClient) Echo(ctx context.Context, in *RequestEcho, opts ...grpc.CallOption) (*ResponseEcho, error) {
out := new(ResponseEcho)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Echo", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) Flush(ctx context.Context, in *RequestFlush, opts ...grpc.CallOption) (*ResponseFlush, error) {
out := new(ResponseFlush)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Flush", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) Info(ctx context.Context, in *RequestInfo, opts ...grpc.CallOption) (*ResponseInfo, error) {
out := new(ResponseInfo)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Info", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) CheckTx(ctx context.Context, in *RequestCheckTx, opts ...grpc.CallOption) (*ResponseCheckTx, error) {
out := new(ResponseCheckTx)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/CheckTx", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) Query(ctx context.Context, in *RequestQuery, opts ...grpc.CallOption) (*ResponseQuery, error) {
out := new(ResponseQuery)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Query", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) Commit(ctx context.Context, in *RequestCommit, opts ...grpc.CallOption) (*ResponseCommit, error) {
out := new(ResponseCommit)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/Commit", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) InitChain(ctx context.Context, in *RequestInitChain, opts ...grpc.CallOption) (*ResponseInitChain, error) {
out := new(ResponseInitChain)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/InitChain", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) ListSnapshots(ctx context.Context, in *RequestListSnapshots, opts ...grpc.CallOption) (*ResponseListSnapshots, error) {
out := new(ResponseListSnapshots)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/ListSnapshots", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) OfferSnapshot(ctx context.Context, in *RequestOfferSnapshot, opts ...grpc.CallOption) (*ResponseOfferSnapshot, error) {
out := new(ResponseOfferSnapshot)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/OfferSnapshot", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) LoadSnapshotChunk(ctx context.Context, in *RequestLoadSnapshotChunk, opts ...grpc.CallOption) (*ResponseLoadSnapshotChunk, error) {
out := new(ResponseLoadSnapshotChunk)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/LoadSnapshotChunk", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) ApplySnapshotChunk(ctx context.Context, in *RequestApplySnapshotChunk, opts ...grpc.CallOption) (*ResponseApplySnapshotChunk, error) {
out := new(ResponseApplySnapshotChunk)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/ApplySnapshotChunk", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) PrepareProposal(ctx context.Context, in *RequestPrepareProposal, opts ...grpc.CallOption) (*ResponsePrepareProposal, error) {
out := new(ResponsePrepareProposal)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/PrepareProposal", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) ProcessProposal(ctx context.Context, in *RequestProcessProposal, opts ...grpc.CallOption) (*ResponseProcessProposal, error) {
out := new(ResponseProcessProposal)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/ProcessProposal", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) ExtendVote(ctx context.Context, in *RequestExtendVote, opts ...grpc.CallOption) (*ResponseExtendVote, error) {
out := new(ResponseExtendVote)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/ExtendVote", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) VerifyVoteExtension(ctx context.Context, in *RequestVerifyVoteExtension, opts ...grpc.CallOption) (*ResponseVerifyVoteExtension, error) {
out := new(ResponseVerifyVoteExtension)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/VerifyVoteExtension", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBCIClient) FinalizeBlock(ctx context.Context, in *RequestFinalizeBlock, opts ...grpc.CallOption) (*ResponseFinalizeBlock, error) {
out := new(ResponseFinalizeBlock)
err := c.cc.Invoke(ctx, "/tendermint.abci.ABCI/FinalizeBlock", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// ABCIServer is the server API for ABCI service.
type ABCIServer interface {
Echo(context.Context, *RequestEcho) (*ResponseEcho, error)
Flush(context.Context, *RequestFlush) (*ResponseFlush, error)
Info(context.Context, *RequestInfo) (*ResponseInfo, error)
CheckTx(context.Context, *RequestCheckTx) (*ResponseCheckTx, error)
Query(context.Context, *RequestQuery) (*ResponseQuery, error)
Commit(context.Context, *RequestCommit) (*ResponseCommit, error)
InitChain(context.Context, *RequestInitChain) (*ResponseInitChain, error)
ListSnapshots(context.Context, *RequestListSnapshots) (*ResponseListSnapshots, error)
OfferSnapshot(context.Context, *RequestOfferSnapshot) (*ResponseOfferSnapshot, error)
LoadSnapshotChunk(context.Context, *RequestLoadSnapshotChunk) (*ResponseLoadSnapshotChunk, error)
ApplySnapshotChunk(context.Context, *RequestApplySnapshotChunk) (*ResponseApplySnapshotChunk, error)
PrepareProposal(context.Context, *RequestPrepareProposal) (*ResponsePrepareProposal, error)
ProcessProposal(context.Context, *RequestProcessProposal) (*ResponseProcessProposal, error)
ExtendVote(context.Context, *RequestExtendVote) (*ResponseExtendVote, error)
VerifyVoteExtension(context.Context, *RequestVerifyVoteExtension) (*ResponseVerifyVoteExtension, error)
FinalizeBlock(context.Context, *RequestFinalizeBlock) (*ResponseFinalizeBlock, error)
}
// UnimplementedABCIServer can be embedded to have forward compatible implementations.
type UnimplementedABCIServer struct {
}
func (*UnimplementedABCIServer) Echo(ctx context.Context, req *RequestEcho) (*ResponseEcho, error) {
return nil, status.Errorf(codes.Unimplemented, "method Echo not implemented")
}
func (*UnimplementedABCIServer) Flush(ctx context.Context, req *RequestFlush) (*ResponseFlush, error) {
return nil, status.Errorf(codes.Unimplemented, "method Flush not implemented")
}
func (*UnimplementedABCIServer) Info(ctx context.Context, req *RequestInfo) (*ResponseInfo, error) {
return nil, status.Errorf(codes.Unimplemented, "method Info not implemented")
}
func (*UnimplementedABCIServer) CheckTx(ctx context.Context, req *RequestCheckTx) (*ResponseCheckTx, error) {
return nil, status.Errorf(codes.Unimplemented, "method CheckTx not implemented")
}
func (*UnimplementedABCIServer) Query(ctx context.Context, req *RequestQuery) (*ResponseQuery, error) {
return nil, status.Errorf(codes.Unimplemented, "method Query not implemented")
}
func (*UnimplementedABCIServer) Commit(ctx context.Context, req *RequestCommit) (*ResponseCommit, error) {
return nil, status.Errorf(codes.Unimplemented, "method Commit not implemented")
}
func (*UnimplementedABCIServer) InitChain(ctx context.Context, req *RequestInitChain) (*ResponseInitChain, error) {
return nil, status.Errorf(codes.Unimplemented, "method InitChain not implemented")
}
func (*UnimplementedABCIServer) ListSnapshots(ctx context.Context, req *RequestListSnapshots) (*ResponseListSnapshots, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListSnapshots not implemented")
}
func (*UnimplementedABCIServer) OfferSnapshot(ctx context.Context, req *RequestOfferSnapshot) (*ResponseOfferSnapshot, error) {
return nil, status.Errorf(codes.Unimplemented, "method OfferSnapshot not implemented")
}
func (*UnimplementedABCIServer) LoadSnapshotChunk(ctx context.Context, req *RequestLoadSnapshotChunk) (*ResponseLoadSnapshotChunk, error) {
return nil, status.Errorf(codes.Unimplemented, "method LoadSnapshotChunk not implemented")
}
func (*UnimplementedABCIServer) ApplySnapshotChunk(ctx context.Context, req *RequestApplySnapshotChunk) (*ResponseApplySnapshotChunk, error) {
return nil, status.Errorf(codes.Unimplemented, "method ApplySnapshotChunk not implemented")
}
func (*UnimplementedABCIServer) PrepareProposal(ctx context.Context, req *RequestPrepareProposal) (*ResponsePrepareProposal, error) {
return nil, status.Errorf(codes.Unimplemented, "method PrepareProposal not implemented")
}
func (*UnimplementedABCIServer) ProcessProposal(ctx context.Context, req *RequestProcessProposal) (*ResponseProcessProposal, error) {
return nil, status.Errorf(codes.Unimplemented, "method ProcessProposal not implemented")
}
func (*UnimplementedABCIServer) ExtendVote(ctx context.Context, req *RequestExtendVote) (*ResponseExtendVote, error) {
return nil, status.Errorf(codes.Unimplemented, "method ExtendVote not implemented")
}
func (*UnimplementedABCIServer) VerifyVoteExtension(ctx context.Context, req *RequestVerifyVoteExtension) (*ResponseVerifyVoteExtension, error) {
return nil, status.Errorf(codes.Unimplemented, "method VerifyVoteExtension not implemented")
}
func (*UnimplementedABCIServer) FinalizeBlock(ctx context.Context, req *RequestFinalizeBlock) (*ResponseFinalizeBlock, error) {
return nil, status.Errorf(codes.Unimplemented, "method FinalizeBlock not implemented")
}
func RegisterABCIServer(s grpc1.Server, srv ABCIServer) {
s.RegisterService(&_ABCI_serviceDesc, srv)
}
func _ABCI_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestEcho)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).Echo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/Echo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).Echo(ctx, req.(*RequestEcho))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_Flush_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestFlush)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).Flush(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/Flush",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).Flush(ctx, req.(*RequestFlush))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_Info_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestInfo)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).Info(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/Info",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).Info(ctx, req.(*RequestInfo))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_CheckTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestCheckTx)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).CheckTx(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/CheckTx",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).CheckTx(ctx, req.(*RequestCheckTx))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_Query_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestQuery)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).Query(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/Query",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).Query(ctx, req.(*RequestQuery))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_Commit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestCommit)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).Commit(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/Commit",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).Commit(ctx, req.(*RequestCommit))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_InitChain_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestInitChain)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).InitChain(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/InitChain",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).InitChain(ctx, req.(*RequestInitChain))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_ListSnapshots_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestListSnapshots)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).ListSnapshots(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/ListSnapshots",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).ListSnapshots(ctx, req.(*RequestListSnapshots))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_OfferSnapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestOfferSnapshot)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).OfferSnapshot(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/OfferSnapshot",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).OfferSnapshot(ctx, req.(*RequestOfferSnapshot))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_LoadSnapshotChunk_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestLoadSnapshotChunk)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).LoadSnapshotChunk(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/LoadSnapshotChunk",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).LoadSnapshotChunk(ctx, req.(*RequestLoadSnapshotChunk))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_ApplySnapshotChunk_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestApplySnapshotChunk)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).ApplySnapshotChunk(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/ApplySnapshotChunk",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).ApplySnapshotChunk(ctx, req.(*RequestApplySnapshotChunk))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_PrepareProposal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestPrepareProposal)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).PrepareProposal(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/PrepareProposal",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).PrepareProposal(ctx, req.(*RequestPrepareProposal))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_ProcessProposal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestProcessProposal)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).ProcessProposal(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/ProcessProposal",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).ProcessProposal(ctx, req.(*RequestProcessProposal))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_ExtendVote_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestExtendVote)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).ExtendVote(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/ExtendVote",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).ExtendVote(ctx, req.(*RequestExtendVote))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_VerifyVoteExtension_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestVerifyVoteExtension)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).VerifyVoteExtension(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/VerifyVoteExtension",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).VerifyVoteExtension(ctx, req.(*RequestVerifyVoteExtension))
}
return interceptor(ctx, in, info, handler)
}
func _ABCI_FinalizeBlock_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestFinalizeBlock)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABCIServer).FinalizeBlock(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/tendermint.abci.ABCI/FinalizeBlock",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABCIServer).FinalizeBlock(ctx, req.(*RequestFinalizeBlock))
}
return interceptor(ctx, in, info, handler)
}
var ABCI_serviceDesc = _ABCI_serviceDesc
var _ABCI_serviceDesc = grpc.ServiceDesc{
ServiceName: "tendermint.abci.ABCI",
HandlerType: (*ABCIServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Echo",
Handler: _ABCI_Echo_Handler,
},
{
MethodName: "Flush",
Handler: _ABCI_Flush_Handler,
},
{
MethodName: "Info",
Handler: _ABCI_Info_Handler,
},
{
MethodName: "CheckTx",
Handler: _ABCI_CheckTx_Handler,
},
{
MethodName: "Query",
Handler: _ABCI_Query_Handler,
},
{
MethodName: "Commit",
Handler: _ABCI_Commit_Handler,
},
{
MethodName: "InitChain",
Handler: _ABCI_InitChain_Handler,
},
{
MethodName: "ListSnapshots",
Handler: _ABCI_ListSnapshots_Handler,
},
{
MethodName: "OfferSnapshot",
Handler: _ABCI_OfferSnapshot_Handler,
},
{
MethodName: "LoadSnapshotChunk",
Handler: _ABCI_LoadSnapshotChunk_Handler,
},
{
MethodName: "ApplySnapshotChunk",
Handler: _ABCI_ApplySnapshotChunk_Handler,
},
{
MethodName: "PrepareProposal",
Handler: _ABCI_PrepareProposal_Handler,
},
{
MethodName: "ProcessProposal",
Handler: _ABCI_ProcessProposal_Handler,
},
{
MethodName: "ExtendVote",
Handler: _ABCI_ExtendVote_Handler,
},
{
MethodName: "VerifyVoteExtension",
Handler: _ABCI_VerifyVoteExtension_Handler,
},
{
MethodName: "FinalizeBlock",
Handler: _ABCI_FinalizeBlock_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "tendermint/abci/types.proto",
}
func (m *Request) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Request) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Value != nil {
{
size := m.Value.Size()
i -= size
if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
}
}
return len(dAtA) - i, nil
}
func (m *Request_Echo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_Echo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Echo != nil {
{
size, err := m.Echo.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *Request_Flush) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_Flush) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Flush != nil {
{
size, err := m.Flush.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
return len(dAtA) - i, nil
}
func (m *Request_Info) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_Info) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Info != nil {
{
size, err := m.Info.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
return len(dAtA) - i, nil
}
func (m *Request_InitChain) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_InitChain) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.InitChain != nil {
{
size, err := m.InitChain.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x2a
}
return len(dAtA) - i, nil
}
func (m *Request_Query) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_Query) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Query != nil {
{
size, err := m.Query.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x32
}
return len(dAtA) - i, nil
}
func (m *Request_CheckTx) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_CheckTx) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.CheckTx != nil {
{
size, err := m.CheckTx.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x42
}
return len(dAtA) - i, nil
}
func (m *Request_Commit) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_Commit) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Commit != nil {
{
size, err := m.Commit.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x5a
}
return len(dAtA) - i, nil
}
func (m *Request_ListSnapshots) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_ListSnapshots) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.ListSnapshots != nil {
{
size, err := m.ListSnapshots.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x62
}
return len(dAtA) - i, nil
}
func (m *Request_OfferSnapshot) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_OfferSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.OfferSnapshot != nil {
{
size, err := m.OfferSnapshot.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x6a
}
return len(dAtA) - i, nil
}
func (m *Request_LoadSnapshotChunk) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_LoadSnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.LoadSnapshotChunk != nil {
{
size, err := m.LoadSnapshotChunk.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x72
}
return len(dAtA) - i, nil
}
func (m *Request_ApplySnapshotChunk) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_ApplySnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.ApplySnapshotChunk != nil {
{
size, err := m.ApplySnapshotChunk.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x7a
}
return len(dAtA) - i, nil
}
func (m *Request_PrepareProposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_PrepareProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.PrepareProposal != nil {
{
size, err := m.PrepareProposal.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0x82
}
return len(dAtA) - i, nil
}
func (m *Request_ProcessProposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_ProcessProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.ProcessProposal != nil {
{
size, err := m.ProcessProposal.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0x8a
}
return len(dAtA) - i, nil
}
func (m *Request_ExtendVote) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_ExtendVote) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.ExtendVote != nil {
{
size, err := m.ExtendVote.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0x92
}
return len(dAtA) - i, nil
}
func (m *Request_VerifyVoteExtension) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_VerifyVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.VerifyVoteExtension != nil {
{
size, err := m.VerifyVoteExtension.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0x9a
}
return len(dAtA) - i, nil
}
func (m *Request_FinalizeBlock) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Request_FinalizeBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.FinalizeBlock != nil {
{
size, err := m.FinalizeBlock.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0xa2
}
return len(dAtA) - i, nil
}
func (m *RequestEcho) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestEcho) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestEcho) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Message) > 0 {
i -= len(m.Message)
copy(dAtA[i:], m.Message)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Message)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *RequestFlush) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestFlush) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestFlush) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *RequestInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestInfo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AbciVersion) > 0 {
i -= len(m.AbciVersion)
copy(dAtA[i:], m.AbciVersion)
i = encodeVarintTypes(dAtA, i, uint64(len(m.AbciVersion)))
i--
dAtA[i] = 0x22
}
if m.P2PVersion != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.P2PVersion))
i--
dAtA[i] = 0x18
}
if m.BlockVersion != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.BlockVersion))
i--
dAtA[i] = 0x10
}
if len(m.Version) > 0 {
i -= len(m.Version)
copy(dAtA[i:], m.Version)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Version)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *RequestInitChain) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestInitChain) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestInitChain) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.InitialHeight != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.InitialHeight))
i--
dAtA[i] = 0x30
}
if len(m.AppStateBytes) > 0 {
i -= len(m.AppStateBytes)
copy(dAtA[i:], m.AppStateBytes)
i = encodeVarintTypes(dAtA, i, uint64(len(m.AppStateBytes)))
i--
dAtA[i] = 0x2a
}
if len(m.Validators) > 0 {
for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Validators[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
}
if m.ConsensusParams != nil {
{
size, err := m.ConsensusParams.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
if len(m.ChainId) > 0 {
i -= len(m.ChainId)
copy(dAtA[i:], m.ChainId)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainId)))
i--
dAtA[i] = 0x12
}
n18, err18 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):])
if err18 != nil {
return 0, err18
}
i -= n18
i = encodeVarintTypes(dAtA, i, uint64(n18))
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *RequestQuery) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestQuery) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestQuery) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Prove {
i--
if m.Prove {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x20
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x18
}
if len(m.Path) > 0 {
i -= len(m.Path)
copy(dAtA[i:], m.Path)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Path)))
i--
dAtA[i] = 0x12
}
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *RequestCheckTx) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestCheckTx) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestCheckTx) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Type != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Type))
i--
dAtA[i] = 0x10
}
if len(m.Tx) > 0 {
i -= len(m.Tx)
copy(dAtA[i:], m.Tx)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Tx)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *RequestCommit) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestCommit) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestCommit) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *RequestListSnapshots) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestListSnapshots) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestListSnapshots) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *RequestOfferSnapshot) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestOfferSnapshot) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestOfferSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AppHash) > 0 {
i -= len(m.AppHash)
copy(dAtA[i:], m.AppHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash)))
i--
dAtA[i] = 0x12
}
if m.Snapshot != nil {
{
size, err := m.Snapshot.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *RequestLoadSnapshotChunk) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestLoadSnapshotChunk) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestLoadSnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Chunk != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Chunk))
i--
dAtA[i] = 0x18
}
if m.Format != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Format))
i--
dAtA[i] = 0x10
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *RequestApplySnapshotChunk) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestApplySnapshotChunk) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestApplySnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Sender) > 0 {
i -= len(m.Sender)
copy(dAtA[i:], m.Sender)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Sender)))
i--
dAtA[i] = 0x1a
}
if len(m.Chunk) > 0 {
i -= len(m.Chunk)
copy(dAtA[i:], m.Chunk)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Chunk)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *RequestPrepareProposal) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestPrepareProposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestPrepareProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.ProposerAddress) > 0 {
i -= len(m.ProposerAddress)
copy(dAtA[i:], m.ProposerAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress)))
i--
dAtA[i] = 0x42
}
if len(m.NextValidatorsHash) > 0 {
i -= len(m.NextValidatorsHash)
copy(dAtA[i:], m.NextValidatorsHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash)))
i--
dAtA[i] = 0x3a
}
n20, err20 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):])
if err20 != nil {
return 0, err20
}
i -= n20
i = encodeVarintTypes(dAtA, i, uint64(n20))
i--
dAtA[i] = 0x32
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x28
}
if len(m.Misbehavior) > 0 {
for iNdEx := len(m.Misbehavior) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Misbehavior[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
}
{
size, err := m.LocalLastCommit.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Txs[iNdEx])
copy(dAtA[i:], m.Txs[iNdEx])
i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx])))
i--
dAtA[i] = 0x12
}
}
if m.MaxTxBytes != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.MaxTxBytes))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *RequestProcessProposal) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestProcessProposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestProcessProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.ProposerAddress) > 0 {
i -= len(m.ProposerAddress)
copy(dAtA[i:], m.ProposerAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress)))
i--
dAtA[i] = 0x42
}
if len(m.NextValidatorsHash) > 0 {
i -= len(m.NextValidatorsHash)
copy(dAtA[i:], m.NextValidatorsHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash)))
i--
dAtA[i] = 0x3a
}
n22, err22 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):])
if err22 != nil {
return 0, err22
}
i -= n22
i = encodeVarintTypes(dAtA, i, uint64(n22))
i--
dAtA[i] = 0x32
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x28
}
if len(m.Hash) > 0 {
i -= len(m.Hash)
copy(dAtA[i:], m.Hash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash)))
i--
dAtA[i] = 0x22
}
if len(m.Misbehavior) > 0 {
for iNdEx := len(m.Misbehavior) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Misbehavior[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
{
size, err := m.ProposedLastCommit.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Txs[iNdEx])
copy(dAtA[i:], m.Txs[iNdEx])
i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *RequestExtendVote) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestExtendVote) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestExtendVote) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.ProposerAddress) > 0 {
i -= len(m.ProposerAddress)
copy(dAtA[i:], m.ProposerAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress)))
i--
dAtA[i] = 0x42
}
if len(m.NextValidatorsHash) > 0 {
i -= len(m.NextValidatorsHash)
copy(dAtA[i:], m.NextValidatorsHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash)))
i--
dAtA[i] = 0x3a
}
if len(m.Misbehavior) > 0 {
for iNdEx := len(m.Misbehavior) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Misbehavior[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x32
}
}
{
size, err := m.ProposedLastCommit.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x2a
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Txs[iNdEx])
copy(dAtA[i:], m.Txs[iNdEx])
i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx])))
i--
dAtA[i] = 0x22
}
}
n25, err25 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):])
if err25 != nil {
return 0, err25
}
i -= n25
i = encodeVarintTypes(dAtA, i, uint64(n25))
i--
dAtA[i] = 0x1a
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x10
}
if len(m.Hash) > 0 {
i -= len(m.Hash)
copy(dAtA[i:], m.Hash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *RequestVerifyVoteExtension) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestVerifyVoteExtension) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestVerifyVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.VoteExtension) > 0 {
i -= len(m.VoteExtension)
copy(dAtA[i:], m.VoteExtension)
i = encodeVarintTypes(dAtA, i, uint64(len(m.VoteExtension)))
i--
dAtA[i] = 0x22
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x18
}
if len(m.ValidatorAddress) > 0 {
i -= len(m.ValidatorAddress)
copy(dAtA[i:], m.ValidatorAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorAddress)))
i--
dAtA[i] = 0x12
}
if len(m.Hash) > 0 {
i -= len(m.Hash)
copy(dAtA[i:], m.Hash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *RequestFinalizeBlock) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RequestFinalizeBlock) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RequestFinalizeBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.ProposerAddress) > 0 {
i -= len(m.ProposerAddress)
copy(dAtA[i:], m.ProposerAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress)))
i--
dAtA[i] = 0x42
}
if len(m.NextValidatorsHash) > 0 {
i -= len(m.NextValidatorsHash)
copy(dAtA[i:], m.NextValidatorsHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash)))
i--
dAtA[i] = 0x3a
}
n26, err26 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):])
if err26 != nil {
return 0, err26
}
i -= n26
i = encodeVarintTypes(dAtA, i, uint64(n26))
i--
dAtA[i] = 0x32
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x28
}
if len(m.Hash) > 0 {
i -= len(m.Hash)
copy(dAtA[i:], m.Hash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash)))
i--
dAtA[i] = 0x22
}
if len(m.Misbehavior) > 0 {
for iNdEx := len(m.Misbehavior) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Misbehavior[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
{
size, err := m.DecidedLastCommit.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Txs[iNdEx])
copy(dAtA[i:], m.Txs[iNdEx])
i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *Response) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Response) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Value != nil {
{
size := m.Value.Size()
i -= size
if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
}
}
return len(dAtA) - i, nil
}
func (m *Response_Exception) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_Exception) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Exception != nil {
{
size, err := m.Exception.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *Response_Echo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_Echo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Echo != nil {
{
size, err := m.Echo.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
return len(dAtA) - i, nil
}
func (m *Response_Flush) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_Flush) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Flush != nil {
{
size, err := m.Flush.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
return len(dAtA) - i, nil
}
func (m *Response_Info) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_Info) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Info != nil {
{
size, err := m.Info.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
return len(dAtA) - i, nil
}
func (m *Response_InitChain) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_InitChain) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.InitChain != nil {
{
size, err := m.InitChain.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x32
}
return len(dAtA) - i, nil
}
func (m *Response_Query) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_Query) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Query != nil {
{
size, err := m.Query.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x3a
}
return len(dAtA) - i, nil
}
func (m *Response_CheckTx) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_CheckTx) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.CheckTx != nil {
{
size, err := m.CheckTx.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x4a
}
return len(dAtA) - i, nil
}
func (m *Response_Commit) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_Commit) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Commit != nil {
{
size, err := m.Commit.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x62
}
return len(dAtA) - i, nil
}
func (m *Response_ListSnapshots) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_ListSnapshots) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.ListSnapshots != nil {
{
size, err := m.ListSnapshots.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x6a
}
return len(dAtA) - i, nil
}
func (m *Response_OfferSnapshot) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_OfferSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.OfferSnapshot != nil {
{
size, err := m.OfferSnapshot.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x72
}
return len(dAtA) - i, nil
}
func (m *Response_LoadSnapshotChunk) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_LoadSnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.LoadSnapshotChunk != nil {
{
size, err := m.LoadSnapshotChunk.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x7a
}
return len(dAtA) - i, nil
}
func (m *Response_ApplySnapshotChunk) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_ApplySnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.ApplySnapshotChunk != nil {
{
size, err := m.ApplySnapshotChunk.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0x82
}
return len(dAtA) - i, nil
}
func (m *Response_PrepareProposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_PrepareProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.PrepareProposal != nil {
{
size, err := m.PrepareProposal.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0x8a
}
return len(dAtA) - i, nil
}
func (m *Response_ProcessProposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_ProcessProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.ProcessProposal != nil {
{
size, err := m.ProcessProposal.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0x92
}
return len(dAtA) - i, nil
}
func (m *Response_ExtendVote) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_ExtendVote) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.ExtendVote != nil {
{
size, err := m.ExtendVote.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0x9a
}
return len(dAtA) - i, nil
}
func (m *Response_VerifyVoteExtension) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_VerifyVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.VerifyVoteExtension != nil {
{
size, err := m.VerifyVoteExtension.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0xa2
}
return len(dAtA) - i, nil
}
func (m *Response_FinalizeBlock) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Response_FinalizeBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.FinalizeBlock != nil {
{
size, err := m.FinalizeBlock.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1
i--
dAtA[i] = 0xaa
}
return len(dAtA) - i, nil
}
func (m *ResponseException) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseException) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseException) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Error) > 0 {
i -= len(m.Error)
copy(dAtA[i:], m.Error)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Error)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *ResponseEcho) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseEcho) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseEcho) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Message) > 0 {
i -= len(m.Message)
copy(dAtA[i:], m.Message)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Message)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *ResponseFlush) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseFlush) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseFlush) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *ResponseInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseInfo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.LastBlockAppHash) > 0 {
i -= len(m.LastBlockAppHash)
copy(dAtA[i:], m.LastBlockAppHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.LastBlockAppHash)))
i--
dAtA[i] = 0x2a
}
if m.LastBlockHeight != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.LastBlockHeight))
i--
dAtA[i] = 0x20
}
if m.AppVersion != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.AppVersion))
i--
dAtA[i] = 0x18
}
if len(m.Version) > 0 {
i -= len(m.Version)
copy(dAtA[i:], m.Version)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Version)))
i--
dAtA[i] = 0x12
}
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *ResponseInitChain) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseInitChain) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseInitChain) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AppHash) > 0 {
i -= len(m.AppHash)
copy(dAtA[i:], m.AppHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash)))
i--
dAtA[i] = 0x1a
}
if len(m.Validators) > 0 {
for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Validators[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if m.ConsensusParams != nil {
{
size, err := m.ConsensusParams.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *ResponseQuery) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseQuery) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseQuery) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Codespace) > 0 {
i -= len(m.Codespace)
copy(dAtA[i:], m.Codespace)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Codespace)))
i--
dAtA[i] = 0x52
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x48
}
if m.ProofOps != nil {
{
size, err := m.ProofOps.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x42
}
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x3a
}
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0x32
}
if m.Index != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x28
}
if len(m.Info) > 0 {
i -= len(m.Info)
copy(dAtA[i:], m.Info)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Info)))
i--
dAtA[i] = 0x22
}
if len(m.Log) > 0 {
i -= len(m.Log)
copy(dAtA[i:], m.Log)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Log)))
i--
dAtA[i] = 0x1a
}
if m.Code != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Code))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ResponseCheckTx) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseCheckTx) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseCheckTx) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Codespace) > 0 {
i -= len(m.Codespace)
copy(dAtA[i:], m.Codespace)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Codespace)))
i--
dAtA[i] = 0x42
}
if len(m.Events) > 0 {
for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x3a
}
}
if m.GasUsed != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.GasUsed))
i--
dAtA[i] = 0x30
}
if m.GasWanted != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.GasWanted))
i--
dAtA[i] = 0x28
}
if len(m.Info) > 0 {
i -= len(m.Info)
copy(dAtA[i:], m.Info)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Info)))
i--
dAtA[i] = 0x22
}
if len(m.Log) > 0 {
i -= len(m.Log)
copy(dAtA[i:], m.Log)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Log)))
i--
dAtA[i] = 0x1a
}
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0x12
}
if m.Code != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Code))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ResponseCommit) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseCommit) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseCommit) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.RetainHeight != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.RetainHeight))
i--
dAtA[i] = 0x18
}
return len(dAtA) - i, nil
}
func (m *ResponseListSnapshots) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseListSnapshots) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseListSnapshots) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Snapshots) > 0 {
for iNdEx := len(m.Snapshots) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Snapshots[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *ResponseOfferSnapshot) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseOfferSnapshot) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseOfferSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Result != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Result))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ResponseLoadSnapshotChunk) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseLoadSnapshotChunk) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseLoadSnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Chunk) > 0 {
i -= len(m.Chunk)
copy(dAtA[i:], m.Chunk)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Chunk)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *ResponseApplySnapshotChunk) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseApplySnapshotChunk) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseApplySnapshotChunk) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.RejectSenders) > 0 {
for iNdEx := len(m.RejectSenders) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.RejectSenders[iNdEx])
copy(dAtA[i:], m.RejectSenders[iNdEx])
i = encodeVarintTypes(dAtA, i, uint64(len(m.RejectSenders[iNdEx])))
i--
dAtA[i] = 0x1a
}
}
if len(m.RefetchChunks) > 0 {
dAtA48 := make([]byte, len(m.RefetchChunks)*10)
var j47 int
for _, num := range m.RefetchChunks {
for num >= 1<<7 {
dAtA48[j47] = uint8(uint64(num)&0x7f | 0x80)
num >>= 7
j47++
}
dAtA48[j47] = uint8(num)
j47++
}
i -= j47
copy(dAtA[i:], dAtA48[:j47])
i = encodeVarintTypes(dAtA, i, uint64(j47))
i--
dAtA[i] = 0x12
}
if m.Result != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Result))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ResponsePrepareProposal) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponsePrepareProposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponsePrepareProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Txs[iNdEx])
copy(dAtA[i:], m.Txs[iNdEx])
i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *ResponseProcessProposal) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseProcessProposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseProcessProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Status != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Status))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ResponseExtendVote) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseExtendVote) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseExtendVote) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.VoteExtension) > 0 {
i -= len(m.VoteExtension)
copy(dAtA[i:], m.VoteExtension)
i = encodeVarintTypes(dAtA, i, uint64(len(m.VoteExtension)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *ResponseVerifyVoteExtension) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseVerifyVoteExtension) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseVerifyVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Status != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Status))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ResponseFinalizeBlock) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ResponseFinalizeBlock) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ResponseFinalizeBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AppHash) > 0 {
i -= len(m.AppHash)
copy(dAtA[i:], m.AppHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash)))
i--
dAtA[i] = 0x2a
}
if m.ConsensusParamUpdates != nil {
{
size, err := m.ConsensusParamUpdates.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
if len(m.ValidatorUpdates) > 0 {
for iNdEx := len(m.ValidatorUpdates) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.ValidatorUpdates[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
if len(m.TxResults) > 0 {
for iNdEx := len(m.TxResults) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.TxResults[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if len(m.Events) > 0 {
for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *CommitInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *CommitInfo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *CommitInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Votes) > 0 {
for iNdEx := len(m.Votes) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Votes[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if m.Round != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Round))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ExtendedCommitInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ExtendedCommitInfo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ExtendedCommitInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Votes) > 0 {
for iNdEx := len(m.Votes) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Votes[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if m.Round != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Round))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Event) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Event) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Event) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Attributes) > 0 {
for iNdEx := len(m.Attributes) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Attributes[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if len(m.Type) > 0 {
i -= len(m.Type)
copy(dAtA[i:], m.Type)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Type)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *EventAttribute) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *EventAttribute) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *EventAttribute) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Index {
i--
if m.Index {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x18
}
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *ExecTxResult) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ExecTxResult) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ExecTxResult) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Codespace) > 0 {
i -= len(m.Codespace)
copy(dAtA[i:], m.Codespace)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Codespace)))
i--
dAtA[i] = 0x42
}
if len(m.Events) > 0 {
for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x3a
}
}
if m.GasUsed != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.GasUsed))
i--
dAtA[i] = 0x30
}
if m.GasWanted != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.GasWanted))
i--
dAtA[i] = 0x28
}
if len(m.Info) > 0 {
i -= len(m.Info)
copy(dAtA[i:], m.Info)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Info)))
i--
dAtA[i] = 0x22
}
if len(m.Log) > 0 {
i -= len(m.Log)
copy(dAtA[i:], m.Log)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Log)))
i--
dAtA[i] = 0x1a
}
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0x12
}
if m.Code != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Code))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *TxResult) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxResult) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxResult) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.Result.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
if len(m.Tx) > 0 {
i -= len(m.Tx)
copy(dAtA[i:], m.Tx)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Tx)))
i--
dAtA[i] = 0x1a
}
if m.Index != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x10
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Validator) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Validator) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Validator) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Power != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Power))
i--
dAtA[i] = 0x18
}
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *ValidatorUpdate) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ValidatorUpdate) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ValidatorUpdate) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Power != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Power))
i--
dAtA[i] = 0x10
}
{
size, err := m.PubKey.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *VoteInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *VoteInfo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *VoteInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.BlockIdFlag != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.BlockIdFlag))
i--
dAtA[i] = 0x18
}
{
size, err := m.Validator.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *ExtendedVoteInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ExtendedVoteInfo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ExtendedVoteInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.BlockIdFlag != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.BlockIdFlag))
i--
dAtA[i] = 0x28
}
if len(m.ExtensionSignature) > 0 {
i -= len(m.ExtensionSignature)
copy(dAtA[i:], m.ExtensionSignature)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ExtensionSignature)))
i--
dAtA[i] = 0x22
}
if len(m.VoteExtension) > 0 {
i -= len(m.VoteExtension)
copy(dAtA[i:], m.VoteExtension)
i = encodeVarintTypes(dAtA, i, uint64(len(m.VoteExtension)))
i--
dAtA[i] = 0x1a
}
{
size, err := m.Validator.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *Misbehavior) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Misbehavior) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Misbehavior) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.TotalVotingPower != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.TotalVotingPower))
i--
dAtA[i] = 0x28
}
n54, err54 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):])
if err54 != nil {
return 0, err54
}
i -= n54
i = encodeVarintTypes(dAtA, i, uint64(n54))
i--
dAtA[i] = 0x22
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x18
}
{
size, err := m.Validator.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
if m.Type != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Type))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Snapshot) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Snapshot) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Snapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Metadata) > 0 {
i -= len(m.Metadata)
copy(dAtA[i:], m.Metadata)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Metadata)))
i--
dAtA[i] = 0x2a
}
if len(m.Hash) > 0 {
i -= len(m.Hash)
copy(dAtA[i:], m.Hash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash)))
i--
dAtA[i] = 0x22
}
if m.Chunks != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Chunks))
i--
dAtA[i] = 0x18
}
if m.Format != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Format))
i--
dAtA[i] = 0x10
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func encodeVarintTypes(dAtA []byte, offset int, v uint64) int {
offset -= sovTypes(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *Request) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Value != nil {
n += m.Value.Size()
}
return n
}
func (m *Request_Echo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Echo != nil {
l = m.Echo.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_Flush) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Flush != nil {
l = m.Flush.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_Info) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Info != nil {
l = m.Info.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_InitChain) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.InitChain != nil {
l = m.InitChain.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_Query) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Query != nil {
l = m.Query.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_CheckTx) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.CheckTx != nil {
l = m.CheckTx.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_Commit) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Commit != nil {
l = m.Commit.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_ListSnapshots) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ListSnapshots != nil {
l = m.ListSnapshots.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_OfferSnapshot) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.OfferSnapshot != nil {
l = m.OfferSnapshot.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_LoadSnapshotChunk) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.LoadSnapshotChunk != nil {
l = m.LoadSnapshotChunk.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_ApplySnapshotChunk) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ApplySnapshotChunk != nil {
l = m.ApplySnapshotChunk.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_PrepareProposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.PrepareProposal != nil {
l = m.PrepareProposal.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_ProcessProposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ProcessProposal != nil {
l = m.ProcessProposal.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_ExtendVote) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ExtendVote != nil {
l = m.ExtendVote.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_VerifyVoteExtension) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.VerifyVoteExtension != nil {
l = m.VerifyVoteExtension.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Request_FinalizeBlock) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.FinalizeBlock != nil {
l = m.FinalizeBlock.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestEcho) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Message)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestFlush) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *RequestInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Version)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.BlockVersion != 0 {
n += 1 + sovTypes(uint64(m.BlockVersion))
}
if m.P2PVersion != 0 {
n += 1 + sovTypes(uint64(m.P2PVersion))
}
l = len(m.AbciVersion)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestInitChain) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time)
n += 1 + l + sovTypes(uint64(l))
l = len(m.ChainId)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.ConsensusParams != nil {
l = m.ConsensusParams.Size()
n += 1 + l + sovTypes(uint64(l))
}
if len(m.Validators) > 0 {
for _, e := range m.Validators {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
l = len(m.AppStateBytes)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.InitialHeight != 0 {
n += 1 + sovTypes(uint64(m.InitialHeight))
}
return n
}
func (m *RequestQuery) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Data)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Path)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
if m.Prove {
n += 2
}
return n
}
func (m *RequestCheckTx) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Tx)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Type != 0 {
n += 1 + sovTypes(uint64(m.Type))
}
return n
}
func (m *RequestCommit) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *RequestListSnapshots) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *RequestOfferSnapshot) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Snapshot != nil {
l = m.Snapshot.Size()
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.AppHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestLoadSnapshotChunk) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
if m.Format != 0 {
n += 1 + sovTypes(uint64(m.Format))
}
if m.Chunk != 0 {
n += 1 + sovTypes(uint64(m.Chunk))
}
return n
}
func (m *RequestApplySnapshotChunk) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovTypes(uint64(m.Index))
}
l = len(m.Chunk)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Sender)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestPrepareProposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.MaxTxBytes != 0 {
n += 1 + sovTypes(uint64(m.MaxTxBytes))
}
if len(m.Txs) > 0 {
for _, b := range m.Txs {
l = len(b)
n += 1 + l + sovTypes(uint64(l))
}
}
l = m.LocalLastCommit.Size()
n += 1 + l + sovTypes(uint64(l))
if len(m.Misbehavior) > 0 {
for _, e := range m.Misbehavior {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time)
n += 1 + l + sovTypes(uint64(l))
l = len(m.NextValidatorsHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ProposerAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestProcessProposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Txs) > 0 {
for _, b := range m.Txs {
l = len(b)
n += 1 + l + sovTypes(uint64(l))
}
}
l = m.ProposedLastCommit.Size()
n += 1 + l + sovTypes(uint64(l))
if len(m.Misbehavior) > 0 {
for _, e := range m.Misbehavior {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
l = len(m.Hash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time)
n += 1 + l + sovTypes(uint64(l))
l = len(m.NextValidatorsHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ProposerAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestExtendVote) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Hash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time)
n += 1 + l + sovTypes(uint64(l))
if len(m.Txs) > 0 {
for _, b := range m.Txs {
l = len(b)
n += 1 + l + sovTypes(uint64(l))
}
}
l = m.ProposedLastCommit.Size()
n += 1 + l + sovTypes(uint64(l))
if len(m.Misbehavior) > 0 {
for _, e := range m.Misbehavior {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
l = len(m.NextValidatorsHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ProposerAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestVerifyVoteExtension) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Hash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ValidatorAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
l = len(m.VoteExtension)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *RequestFinalizeBlock) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Txs) > 0 {
for _, b := range m.Txs {
l = len(b)
n += 1 + l + sovTypes(uint64(l))
}
}
l = m.DecidedLastCommit.Size()
n += 1 + l + sovTypes(uint64(l))
if len(m.Misbehavior) > 0 {
for _, e := range m.Misbehavior {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
l = len(m.Hash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time)
n += 1 + l + sovTypes(uint64(l))
l = len(m.NextValidatorsHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ProposerAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Value != nil {
n += m.Value.Size()
}
return n
}
func (m *Response_Exception) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Exception != nil {
l = m.Exception.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_Echo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Echo != nil {
l = m.Echo.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_Flush) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Flush != nil {
l = m.Flush.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_Info) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Info != nil {
l = m.Info.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_InitChain) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.InitChain != nil {
l = m.InitChain.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_Query) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Query != nil {
l = m.Query.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_CheckTx) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.CheckTx != nil {
l = m.CheckTx.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_Commit) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Commit != nil {
l = m.Commit.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_ListSnapshots) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ListSnapshots != nil {
l = m.ListSnapshots.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_OfferSnapshot) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.OfferSnapshot != nil {
l = m.OfferSnapshot.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_LoadSnapshotChunk) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.LoadSnapshotChunk != nil {
l = m.LoadSnapshotChunk.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_ApplySnapshotChunk) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ApplySnapshotChunk != nil {
l = m.ApplySnapshotChunk.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_PrepareProposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.PrepareProposal != nil {
l = m.PrepareProposal.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_ProcessProposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ProcessProposal != nil {
l = m.ProcessProposal.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_ExtendVote) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ExtendVote != nil {
l = m.ExtendVote.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_VerifyVoteExtension) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.VerifyVoteExtension != nil {
l = m.VerifyVoteExtension.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *Response_FinalizeBlock) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.FinalizeBlock != nil {
l = m.FinalizeBlock.Size()
n += 2 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseException) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Error)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseEcho) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Message)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseFlush) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *ResponseInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Data)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Version)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.AppVersion != 0 {
n += 1 + sovTypes(uint64(m.AppVersion))
}
if m.LastBlockHeight != 0 {
n += 1 + sovTypes(uint64(m.LastBlockHeight))
}
l = len(m.LastBlockAppHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseInitChain) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ConsensusParams != nil {
l = m.ConsensusParams.Size()
n += 1 + l + sovTypes(uint64(l))
}
if len(m.Validators) > 0 {
for _, e := range m.Validators {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
l = len(m.AppHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseQuery) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Code != 0 {
n += 1 + sovTypes(uint64(m.Code))
}
l = len(m.Log)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Info)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Index != 0 {
n += 1 + sovTypes(uint64(m.Index))
}
l = len(m.Key)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.ProofOps != nil {
l = m.ProofOps.Size()
n += 1 + l + sovTypes(uint64(l))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
l = len(m.Codespace)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseCheckTx) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Code != 0 {
n += 1 + sovTypes(uint64(m.Code))
}
l = len(m.Data)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Log)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Info)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.GasWanted != 0 {
n += 1 + sovTypes(uint64(m.GasWanted))
}
if m.GasUsed != 0 {
n += 1 + sovTypes(uint64(m.GasUsed))
}
if len(m.Events) > 0 {
for _, e := range m.Events {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
l = len(m.Codespace)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseCommit) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.RetainHeight != 0 {
n += 1 + sovTypes(uint64(m.RetainHeight))
}
return n
}
func (m *ResponseListSnapshots) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Snapshots) > 0 {
for _, e := range m.Snapshots {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *ResponseOfferSnapshot) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Result != 0 {
n += 1 + sovTypes(uint64(m.Result))
}
return n
}
func (m *ResponseLoadSnapshotChunk) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Chunk)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseApplySnapshotChunk) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Result != 0 {
n += 1 + sovTypes(uint64(m.Result))
}
if len(m.RefetchChunks) > 0 {
l = 0
for _, e := range m.RefetchChunks {
l += sovTypes(uint64(e))
}
n += 1 + sovTypes(uint64(l)) + l
}
if len(m.RejectSenders) > 0 {
for _, s := range m.RejectSenders {
l = len(s)
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *ResponsePrepareProposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Txs) > 0 {
for _, b := range m.Txs {
l = len(b)
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *ResponseProcessProposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Status != 0 {
n += 1 + sovTypes(uint64(m.Status))
}
return n
}
func (m *ResponseExtendVote) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.VoteExtension)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ResponseVerifyVoteExtension) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Status != 0 {
n += 1 + sovTypes(uint64(m.Status))
}
return n
}
func (m *ResponseFinalizeBlock) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Events) > 0 {
for _, e := range m.Events {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
if len(m.TxResults) > 0 {
for _, e := range m.TxResults {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
if len(m.ValidatorUpdates) > 0 {
for _, e := range m.ValidatorUpdates {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
if m.ConsensusParamUpdates != nil {
l = m.ConsensusParamUpdates.Size()
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.AppHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *CommitInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Round != 0 {
n += 1 + sovTypes(uint64(m.Round))
}
if len(m.Votes) > 0 {
for _, e := range m.Votes {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *ExtendedCommitInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Round != 0 {
n += 1 + sovTypes(uint64(m.Round))
}
if len(m.Votes) > 0 {
for _, e := range m.Votes {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *Event) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Type)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if len(m.Attributes) > 0 {
for _, e := range m.Attributes {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *EventAttribute) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Key)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Index {
n += 2
}
return n
}
func (m *ExecTxResult) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Code != 0 {
n += 1 + sovTypes(uint64(m.Code))
}
l = len(m.Data)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Log)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Info)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.GasWanted != 0 {
n += 1 + sovTypes(uint64(m.GasWanted))
}
if m.GasUsed != 0 {
n += 1 + sovTypes(uint64(m.GasUsed))
}
if len(m.Events) > 0 {
for _, e := range m.Events {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
l = len(m.Codespace)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *TxResult) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
if m.Index != 0 {
n += 1 + sovTypes(uint64(m.Index))
}
l = len(m.Tx)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = m.Result.Size()
n += 1 + l + sovTypes(uint64(l))
return n
}
func (m *Validator) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Power != 0 {
n += 1 + sovTypes(uint64(m.Power))
}
return n
}
func (m *ValidatorUpdate) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.PubKey.Size()
n += 1 + l + sovTypes(uint64(l))
if m.Power != 0 {
n += 1 + sovTypes(uint64(m.Power))
}
return n
}
func (m *VoteInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.Validator.Size()
n += 1 + l + sovTypes(uint64(l))
if m.BlockIdFlag != 0 {
n += 1 + sovTypes(uint64(m.BlockIdFlag))
}
return n
}
func (m *ExtendedVoteInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.Validator.Size()
n += 1 + l + sovTypes(uint64(l))
l = len(m.VoteExtension)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ExtensionSignature)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.BlockIdFlag != 0 {
n += 1 + sovTypes(uint64(m.BlockIdFlag))
}
return n
}
func (m *Misbehavior) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Type != 0 {
n += 1 + sovTypes(uint64(m.Type))
}
l = m.Validator.Size()
n += 1 + l + sovTypes(uint64(l))
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time)
n += 1 + l + sovTypes(uint64(l))
if m.TotalVotingPower != 0 {
n += 1 + sovTypes(uint64(m.TotalVotingPower))
}
return n
}
func (m *Snapshot) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
if m.Format != 0 {
n += 1 + sovTypes(uint64(m.Format))
}
if m.Chunks != 0 {
n += 1 + sovTypes(uint64(m.Chunks))
}
l = len(m.Hash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Metadata)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func sovTypes(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozTypes(x uint64) (n int) {
return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *Request) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Request: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Request: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Echo", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestEcho{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_Echo{v}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Flush", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestFlush{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_Flush{v}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestInfo{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_Info{v}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field InitChain", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestInitChain{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_InitChain{v}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Query", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestQuery{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_Query{v}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CheckTx", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestCheckTx{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_CheckTx{v}
iNdEx = postIndex
case 11:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Commit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestCommit{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_Commit{v}
iNdEx = postIndex
case 12:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ListSnapshots", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestListSnapshots{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_ListSnapshots{v}
iNdEx = postIndex
case 13:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field OfferSnapshot", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestOfferSnapshot{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_OfferSnapshot{v}
iNdEx = postIndex
case 14:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LoadSnapshotChunk", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestLoadSnapshotChunk{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_LoadSnapshotChunk{v}
iNdEx = postIndex
case 15:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ApplySnapshotChunk", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestApplySnapshotChunk{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_ApplySnapshotChunk{v}
iNdEx = postIndex
case 16:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field PrepareProposal", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestPrepareProposal{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_PrepareProposal{v}
iNdEx = postIndex
case 17:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProcessProposal", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestProcessProposal{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_ProcessProposal{v}
iNdEx = postIndex
case 18:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ExtendVote", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestExtendVote{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_ExtendVote{v}
iNdEx = postIndex
case 19:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field VerifyVoteExtension", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestVerifyVoteExtension{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_VerifyVoteExtension{v}
iNdEx = postIndex
case 20:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field FinalizeBlock", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &RequestFinalizeBlock{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Request_FinalizeBlock{v}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestEcho) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestEcho: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestEcho: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Message = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestFlush) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestFlush: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestFlush: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Version = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockVersion", wireType)
}
m.BlockVersion = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BlockVersion |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field P2PVersion", wireType)
}
m.P2PVersion = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.P2PVersion |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AbciVersion", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AbciVersion = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestInitChain) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestInitChain: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestInitChain: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ChainId = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParams", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.ConsensusParams == nil {
m.ConsensusParams = &types1.ConsensusParams{}
}
if err := m.ConsensusParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Validators = append(m.Validators, ValidatorUpdate{})
if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AppStateBytes", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AppStateBytes = append(m.AppStateBytes[:0], dAtA[iNdEx:postIndex]...)
if m.AppStateBytes == nil {
m.AppStateBytes = []byte{}
}
iNdEx = postIndex
case 6:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field InitialHeight", wireType)
}
m.InitialHeight = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.InitialHeight |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestQuery) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestQuery: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestQuery: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Path", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Path = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Prove", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Prove = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestCheckTx) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestCheckTx: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestCheckTx: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Tx = append(m.Tx[:0], dAtA[iNdEx:postIndex]...)
if m.Tx == nil {
m.Tx = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
m.Type = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Type |= CheckTxType(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestCommit) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestCommit: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestCommit: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestListSnapshots) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestListSnapshots: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestListSnapshots: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestOfferSnapshot) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestOfferSnapshot: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestOfferSnapshot: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Snapshot", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Snapshot == nil {
m.Snapshot = &Snapshot{}
}
if err := m.Snapshot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...)
if m.AppHash == nil {
m.AppHash = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestLoadSnapshotChunk) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestLoadSnapshotChunk: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestLoadSnapshotChunk: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType)
}
m.Format = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Format |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Chunk", wireType)
}
m.Chunk = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Chunk |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestApplySnapshotChunk) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestApplySnapshotChunk: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestApplySnapshotChunk: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Chunk", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Chunk = append(m.Chunk[:0], dAtA[iNdEx:postIndex]...)
if m.Chunk == nil {
m.Chunk = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Sender = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestPrepareProposal) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestPrepareProposal: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestPrepareProposal: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxTxBytes", wireType)
}
m.MaxTxBytes = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.MaxTxBytes |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx))
copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LocalLastCommit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.LocalLastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Misbehavior", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Misbehavior = append(m.Misbehavior, Misbehavior{})
if err := m.Misbehavior[len(m.Misbehavior)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...)
if m.NextValidatorsHash == nil {
m.NextValidatorsHash = []byte{}
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ProposerAddress == nil {
m.ProposerAddress = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestProcessProposal) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestProcessProposal: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestProcessProposal: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx))
copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposedLastCommit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ProposedLastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Misbehavior", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Misbehavior = append(m.Misbehavior, Misbehavior{})
if err := m.Misbehavior[len(m.Misbehavior)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...)
if m.Hash == nil {
m.Hash = []byte{}
}
iNdEx = postIndex
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...)
if m.NextValidatorsHash == nil {
m.NextValidatorsHash = []byte{}
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ProposerAddress == nil {
m.ProposerAddress = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestExtendVote) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestExtendVote: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestExtendVote: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...)
if m.Hash == nil {
m.Hash = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx))
copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposedLastCommit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ProposedLastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Misbehavior", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Misbehavior = append(m.Misbehavior, Misbehavior{})
if err := m.Misbehavior[len(m.Misbehavior)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...)
if m.NextValidatorsHash == nil {
m.NextValidatorsHash = []byte{}
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ProposerAddress == nil {
m.ProposerAddress = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestVerifyVoteExtension) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestVerifyVoteExtension: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestVerifyVoteExtension: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...)
if m.Hash == nil {
m.Hash = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ValidatorAddress = append(m.ValidatorAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ValidatorAddress == nil {
m.ValidatorAddress = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field VoteExtension", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.VoteExtension = append(m.VoteExtension[:0], dAtA[iNdEx:postIndex]...)
if m.VoteExtension == nil {
m.VoteExtension = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RequestFinalizeBlock) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RequestFinalizeBlock: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RequestFinalizeBlock: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx))
copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DecidedLastCommit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.DecidedLastCommit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Misbehavior", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Misbehavior = append(m.Misbehavior, Misbehavior{})
if err := m.Misbehavior[len(m.Misbehavior)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...)
if m.Hash == nil {
m.Hash = []byte{}
}
iNdEx = postIndex
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...)
if m.NextValidatorsHash == nil {
m.NextValidatorsHash = []byte{}
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ProposerAddress == nil {
m.ProposerAddress = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Response) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Response: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Response: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Exception", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseException{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_Exception{v}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Echo", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseEcho{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_Echo{v}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Flush", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseFlush{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_Flush{v}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseInfo{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_Info{v}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field InitChain", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseInitChain{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_InitChain{v}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Query", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseQuery{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_Query{v}
iNdEx = postIndex
case 9:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CheckTx", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseCheckTx{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_CheckTx{v}
iNdEx = postIndex
case 12:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Commit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseCommit{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_Commit{v}
iNdEx = postIndex
case 13:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ListSnapshots", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseListSnapshots{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_ListSnapshots{v}
iNdEx = postIndex
case 14:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field OfferSnapshot", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseOfferSnapshot{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_OfferSnapshot{v}
iNdEx = postIndex
case 15:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LoadSnapshotChunk", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseLoadSnapshotChunk{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_LoadSnapshotChunk{v}
iNdEx = postIndex
case 16:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ApplySnapshotChunk", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseApplySnapshotChunk{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_ApplySnapshotChunk{v}
iNdEx = postIndex
case 17:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field PrepareProposal", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponsePrepareProposal{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_PrepareProposal{v}
iNdEx = postIndex
case 18:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProcessProposal", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseProcessProposal{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_ProcessProposal{v}
iNdEx = postIndex
case 19:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ExtendVote", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseExtendVote{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_ExtendVote{v}
iNdEx = postIndex
case 20:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field VerifyVoteExtension", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseVerifyVoteExtension{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_VerifyVoteExtension{v}
iNdEx = postIndex
case 21:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field FinalizeBlock", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &ResponseFinalizeBlock{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Value = &Response_FinalizeBlock{v}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseException) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseException: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseException: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Error = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseEcho) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseEcho: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseEcho: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Message = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseFlush) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseFlush: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseFlush: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Version = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field AppVersion", wireType)
}
m.AppVersion = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.AppVersion |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field LastBlockHeight", wireType)
}
m.LastBlockHeight = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.LastBlockHeight |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LastBlockAppHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.LastBlockAppHash = append(m.LastBlockAppHash[:0], dAtA[iNdEx:postIndex]...)
if m.LastBlockAppHash == nil {
m.LastBlockAppHash = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseInitChain) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseInitChain: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseInitChain: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParams", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.ConsensusParams == nil {
m.ConsensusParams = &types1.ConsensusParams{}
}
if err := m.ConsensusParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Validators = append(m.Validators, ValidatorUpdate{})
if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...)
if m.AppHash == nil {
m.AppHash = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseQuery) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseQuery: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseQuery: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType)
}
m.Code = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Code |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Log = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Info = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...)
if m.Key == nil {
m.Key = []byte{}
}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProofOps", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.ProofOps == nil {
m.ProofOps = &crypto.ProofOps{}
}
if err := m.ProofOps.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 9:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 10:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Codespace", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Codespace = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseCheckTx) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseCheckTx: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseCheckTx: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType)
}
m.Code = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Code |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Log = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Info = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType)
}
m.GasWanted = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.GasWanted |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType)
}
m.GasUsed = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.GasUsed |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Events = append(m.Events, Event{})
if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Codespace", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Codespace = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseCommit) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseCommit: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseCommit: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field RetainHeight", wireType)
}
m.RetainHeight = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.RetainHeight |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseListSnapshots) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseListSnapshots: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseListSnapshots: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Snapshots", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Snapshots = append(m.Snapshots, &Snapshot{})
if err := m.Snapshots[len(m.Snapshots)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseOfferSnapshot) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseOfferSnapshot: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseOfferSnapshot: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType)
}
m.Result = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Result |= ResponseOfferSnapshot_Result(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseLoadSnapshotChunk) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseLoadSnapshotChunk: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseLoadSnapshotChunk: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Chunk", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Chunk = append(m.Chunk[:0], dAtA[iNdEx:postIndex]...)
if m.Chunk == nil {
m.Chunk = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseApplySnapshotChunk) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseApplySnapshotChunk: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseApplySnapshotChunk: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType)
}
m.Result = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Result |= ResponseApplySnapshotChunk_Result(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType == 0 {
var v uint32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.RefetchChunks = append(m.RefetchChunks, v)
} else if wireType == 2 {
var packedLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
packedLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if packedLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + packedLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
var elementCount int
var count int
for _, integer := range dAtA[iNdEx:postIndex] {
if integer < 128 {
count++
}
}
elementCount = count
if elementCount != 0 && len(m.RefetchChunks) == 0 {
m.RefetchChunks = make([]uint32, 0, elementCount)
}
for iNdEx < postIndex {
var v uint32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.RefetchChunks = append(m.RefetchChunks, v)
}
} else {
return fmt.Errorf("proto: wrong wireType = %d for field RefetchChunks", wireType)
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field RejectSenders", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.RejectSenders = append(m.RejectSenders, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponsePrepareProposal) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponsePrepareProposal: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponsePrepareProposal: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx))
copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseProcessProposal) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseProcessProposal: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseProcessProposal: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
}
m.Status = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Status |= ResponseProcessProposal_ProposalStatus(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseExtendVote) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseExtendVote: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseExtendVote: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field VoteExtension", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.VoteExtension = append(m.VoteExtension[:0], dAtA[iNdEx:postIndex]...)
if m.VoteExtension == nil {
m.VoteExtension = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseVerifyVoteExtension) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseVerifyVoteExtension: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseVerifyVoteExtension: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
}
m.Status = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Status |= ResponseVerifyVoteExtension_VerifyStatus(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ResponseFinalizeBlock) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ResponseFinalizeBlock: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ResponseFinalizeBlock: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Events = append(m.Events, Event{})
if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxResults", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TxResults = append(m.TxResults, &ExecTxResult{})
if err := m.TxResults[len(m.TxResults)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidatorUpdates", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ValidatorUpdates = append(m.ValidatorUpdates, ValidatorUpdate{})
if err := m.ValidatorUpdates[len(m.ValidatorUpdates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ConsensusParamUpdates", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.ConsensusParamUpdates == nil {
m.ConsensusParamUpdates = &types1.ConsensusParams{}
}
if err := m.ConsensusParamUpdates.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...)
if m.AppHash == nil {
m.AppHash = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *CommitInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: CommitInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: CommitInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType)
}
m.Round = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Round |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Votes", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Votes = append(m.Votes, VoteInfo{})
if err := m.Votes[len(m.Votes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ExtendedCommitInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ExtendedCommitInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ExtendedCommitInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType)
}
m.Round = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Round |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Votes", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Votes = append(m.Votes, ExtendedVoteInfo{})
if err := m.Votes[len(m.Votes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Event) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Event: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Event: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Type = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Attributes = append(m.Attributes, EventAttribute{})
if err := m.Attributes[len(m.Attributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *EventAttribute) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: EventAttribute: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: EventAttribute: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Index = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ExecTxResult) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ExecTxResult: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ExecTxResult: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType)
}
m.Code = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Code |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Log = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Info = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType)
}
m.GasWanted = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.GasWanted |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType)
}
m.GasUsed = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.GasUsed |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Events = append(m.Events, Event{})
if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Codespace", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Codespace = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxResult) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxResult: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxResult: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Tx = append(m.Tx[:0], dAtA[iNdEx:postIndex]...)
if m.Tx == nil {
m.Tx = []byte{}
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Validator) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Validator: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Validator: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...)
if m.Address == nil {
m.Address = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType)
}
m.Power = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Power |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ValidatorUpdate) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ValidatorUpdate: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ValidatorUpdate: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field PubKey", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.PubKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType)
}
m.Power = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Power |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *VoteInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: VoteInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: VoteInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Validator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockIdFlag", wireType)
}
m.BlockIdFlag = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BlockIdFlag |= types1.BlockIDFlag(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ExtendedVoteInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ExtendedVoteInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ExtendedVoteInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Validator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field VoteExtension", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.VoteExtension = append(m.VoteExtension[:0], dAtA[iNdEx:postIndex]...)
if m.VoteExtension == nil {
m.VoteExtension = []byte{}
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ExtensionSignature", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ExtensionSignature = append(m.ExtensionSignature[:0], dAtA[iNdEx:postIndex]...)
if m.ExtensionSignature == nil {
m.ExtensionSignature = []byte{}
}
iNdEx = postIndex
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockIdFlag", wireType)
}
m.BlockIdFlag = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BlockIdFlag |= types1.BlockIDFlag(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Misbehavior) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Misbehavior: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Misbehavior: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
m.Type = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Type |= MisbehaviorType(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Validator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field TotalVotingPower", wireType)
}
m.TotalVotingPower = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.TotalVotingPower |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Snapshot) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Snapshot: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Snapshot: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Format", wireType)
}
m.Format = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Format |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Chunks", wireType)
}
m.Chunks = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Chunks |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...)
if m.Hash == nil {
m.Hash = []byte{}
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Metadata = append(m.Metadata[:0], dAtA[iNdEx:postIndex]...)
if m.Metadata == nil {
m.Metadata = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipTypes(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthTypes
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupTypes
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthTypes
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group")
)
package consensus
import (
"errors"
"fmt"
"reflect"
"sync"
"time"
cstypes "github.com/cometbft/cometbft/consensus/types"
"github.com/cometbft/cometbft/libs/bits"
cmtevents "github.com/cometbft/cometbft/libs/events"
cmtjson "github.com/cometbft/cometbft/libs/json"
"github.com/cometbft/cometbft/libs/log"
cmtsync "github.com/cometbft/cometbft/libs/sync"
"github.com/cometbft/cometbft/p2p"
cmtcons "github.com/cometbft/cometbft/proto/tendermint/consensus"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
sm "github.com/cometbft/cometbft/state"
"github.com/cometbft/cometbft/types"
cmttime "github.com/cometbft/cometbft/types/time"
)
const (
StateChannel = byte(0x20)
DataChannel = byte(0x21)
VoteChannel = byte(0x22)
VoteSetBitsChannel = byte(0x23)
maxMsgSize = 1048576 // 1MB; NOTE/TODO: keep in sync with types.PartSet sizes.
blocksToContributeToBecomeGoodPeer = 10000
votesToContributeToBecomeGoodPeer = 10000
)
//-----------------------------------------------------------------------------
// Reactor defines a reactor for the consensus service.
type Reactor struct {
p2p.BaseReactor // BaseService + p2p.Switch
conS *State
mtx cmtsync.RWMutex
waitSync bool
eventBus *types.EventBus
rs *cstypes.RoundState
Metrics *Metrics
}
type ReactorOption func(*Reactor)
// NewReactor returns a new Reactor with the given
// consensusState.
func NewReactor(consensusState *State, waitSync bool, options ...ReactorOption) *Reactor {
conR := &Reactor{
conS: consensusState,
waitSync: waitSync,
rs: consensusState.GetRoundState(),
Metrics: NopMetrics(),
}
conR.BaseReactor = *p2p.NewBaseReactor("Consensus", conR)
for _, option := range options {
option(conR)
}
return conR
}
// OnStart implements BaseService by subscribing to events, which later will be
// broadcasted to other peers and starting state if we're not in block sync.
func (conR *Reactor) OnStart() error {
conR.Logger.Info("Reactor ", "waitSync", conR.WaitSync())
// start routine that computes peer statistics for evaluating peer quality
go conR.peerStatsRoutine()
conR.subscribeToBroadcastEvents()
go conR.updateRoundStateRoutine()
if !conR.WaitSync() {
err := conR.conS.Start()
if err != nil {
return err
}
}
return nil
}
// OnStop implements BaseService by unsubscribing from events and stopping
// state.
func (conR *Reactor) OnStop() {
conR.unsubscribeFromBroadcastEvents()
if err := conR.conS.Stop(); err != nil {
conR.Logger.Error("Error stopping consensus state", "err", err)
}
if !conR.WaitSync() {
conR.conS.Wait()
}
}
// SwitchToConsensus switches from block_sync mode to consensus mode.
// It resets the state, turns off block_sync, and starts the consensus state-machine
func (conR *Reactor) SwitchToConsensus(state sm.State, skipWAL bool) {
conR.Logger.Info("SwitchToConsensus")
func() {
// We need to lock, as we are not entering consensus state from State's `handleMsg` or `handleTimeout`
conR.conS.mtx.Lock()
defer conR.conS.mtx.Unlock()
// We have no votes, so reconstruct LastCommit from SeenCommit
if state.LastBlockHeight > 0 {
conR.conS.reconstructLastCommit(state)
}
// NOTE: The line below causes broadcastNewRoundStepRoutine() to broadcast a
// NewRoundStepMessage.
conR.conS.updateToState(state)
}()
conR.mtx.Lock()
conR.waitSync = false
conR.mtx.Unlock()
if skipWAL {
conR.conS.doWALCatchup = false
}
err := conR.conS.Start()
if err != nil {
panic(fmt.Sprintf(`Failed to start consensus state: %v
conS:
%+v
conR:
%+v`, err, conR.conS, conR))
}
}
// GetChannels implements Reactor
func (conR *Reactor) GetChannels() []*p2p.ChannelDescriptor {
// TODO optimize
return []*p2p.ChannelDescriptor{
{
ID: StateChannel,
Priority: 6,
SendQueueCapacity: 100,
RecvMessageCapacity: maxMsgSize,
MessageType: &cmtcons.Message{},
},
{
ID: DataChannel, // maybe split between gossiping current block and catchup stuff
// once we gossip the whole block there's nothing left to send until next height or round
Priority: 10,
SendQueueCapacity: 100,
RecvBufferCapacity: 50 * 4096,
RecvMessageCapacity: maxMsgSize,
MessageType: &cmtcons.Message{},
},
{
ID: VoteChannel,
Priority: 7,
SendQueueCapacity: 100,
RecvBufferCapacity: 100 * 100,
RecvMessageCapacity: maxMsgSize,
MessageType: &cmtcons.Message{},
},
{
ID: VoteSetBitsChannel,
Priority: 1,
SendQueueCapacity: 2,
RecvBufferCapacity: 1024,
RecvMessageCapacity: maxMsgSize,
MessageType: &cmtcons.Message{},
},
}
}
// InitPeer implements Reactor by creating a state for the peer.
func (conR *Reactor) InitPeer(peer p2p.Peer) p2p.Peer {
peerState := NewPeerState(peer).SetLogger(conR.Logger)
peer.Set(types.PeerStateKey, peerState)
return peer
}
// AddPeer implements Reactor by spawning multiple gossiping goroutines for the
// peer.
func (conR *Reactor) AddPeer(peer p2p.Peer) {
if !conR.IsRunning() {
return
}
peerState, ok := peer.Get(types.PeerStateKey).(*PeerState)
if !ok {
panic(fmt.Sprintf("peer %v has no state", peer))
}
// Begin routines for this peer.
go conR.gossipDataRoutine(peer, peerState)
go conR.gossipVotesRoutine(peer, peerState)
go conR.queryMaj23Routine(peer, peerState)
// Send our state to peer.
// If we're block_syncing, broadcast a RoundStepMessage later upon SwitchToConsensus().
if !conR.WaitSync() {
conR.sendNewRoundStepMessage(peer)
}
}
// RemovePeer is a noop.
func (conR *Reactor) RemovePeer(p2p.Peer, interface{}) {
if !conR.IsRunning() {
return
}
// TODO
// ps, ok := peer.Get(PeerStateKey).(*PeerState)
// if !ok {
// panic(fmt.Sprintf("Peer %v has no state", peer))
// }
// ps.Disconnect()
}
// Receive implements Reactor
// NOTE: We process these messages even when we're block_syncing.
// Messages affect either a peer state or the consensus state.
// Peer state updates can happen in parallel, but processing of
// proposals, block parts, and votes are ordered by the receiveRoutine
// NOTE: blocks on consensus state for proposals, block parts, and votes
func (conR *Reactor) Receive(e p2p.Envelope) {
if !conR.IsRunning() {
conR.Logger.Debug("Receive", "src", e.Src, "chId", e.ChannelID)
return
}
msg, err := MsgFromProto(e.Message)
if err != nil {
conR.Logger.Error("Error decoding message", "src", e.Src, "chId", e.ChannelID, "err", err)
conR.Switch.StopPeerForError(e.Src, err)
return
}
if err = msg.ValidateBasic(); err != nil {
conR.Logger.Error("Peer sent us invalid msg", "peer", e.Src, "msg", e.Message, "err", err)
conR.Switch.StopPeerForError(e.Src, err)
return
}
conR.Logger.Debug("Receive", "src", e.Src, "chId", e.ChannelID, "msg", msg)
// Get peer states
ps, ok := e.Src.Get(types.PeerStateKey).(*PeerState)
if !ok {
panic(fmt.Sprintf("Peer %v has no state", e.Src))
}
switch e.ChannelID {
case StateChannel:
switch msg := msg.(type) {
case *NewRoundStepMessage:
conR.conS.mtx.Lock()
initialHeight := conR.conS.state.InitialHeight
conR.conS.mtx.Unlock()
if err = msg.ValidateHeight(initialHeight); err != nil {
conR.Logger.Error("Peer sent us invalid msg", "peer", e.Src, "msg", msg, "err", err)
conR.Switch.StopPeerForError(e.Src, err)
return
}
ps.ApplyNewRoundStepMessage(msg)
case *NewValidBlockMessage:
ps.ApplyNewValidBlockMessage(msg)
case *HasVoteMessage:
ps.ApplyHasVoteMessage(msg)
case *VoteSetMaj23Message:
cs := conR.conS
cs.mtx.Lock()
height, votes := cs.Height, cs.Votes
cs.mtx.Unlock()
if height != msg.Height {
return
}
// Peer claims to have a maj23 for some BlockID at H,R,S,
err := votes.SetPeerMaj23(msg.Round, msg.Type, ps.peer.ID(), msg.BlockID)
if err != nil {
conR.Switch.StopPeerForError(e.Src, err)
return
}
// Respond with a VoteSetBitsMessage showing which votes we have.
// (and consequently shows which we don't have)
var ourVotes *bits.BitArray
switch msg.Type {
case cmtproto.PrevoteType:
ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(msg.BlockID)
case cmtproto.PrecommitType:
ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID)
default:
panic("Bad VoteSetBitsMessage field Type. Forgot to add a check in ValidateBasic?")
}
eMsg := &cmtcons.VoteSetBits{
Height: msg.Height,
Round: msg.Round,
Type: msg.Type,
BlockID: msg.BlockID.ToProto(),
}
if votes := ourVotes.ToProto(); votes != nil {
eMsg.Votes = *votes
}
e.Src.TrySend(p2p.Envelope{
ChannelID: VoteSetBitsChannel,
Message: eMsg,
})
default:
conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
}
case DataChannel:
if conR.WaitSync() {
conR.Logger.Info("Ignoring message received during sync", "msg", msg)
return
}
switch msg := msg.(type) {
case *ProposalMessage:
ps.SetHasProposal(msg.Proposal)
conR.conS.peerMsgQueue <- msgInfo{msg, e.Src.ID()}
case *ProposalPOLMessage:
ps.ApplyProposalPOLMessage(msg)
case *BlockPartMessage:
ps.SetHasProposalBlockPart(msg.Height, msg.Round, int(msg.Part.Index))
conR.Metrics.BlockParts.With("peer_id", string(e.Src.ID())).Add(1)
conR.conS.peerMsgQueue <- msgInfo{msg, e.Src.ID()}
default:
conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
}
case VoteChannel:
if conR.WaitSync() {
conR.Logger.Info("Ignoring message received during sync", "msg", msg)
return
}
switch msg := msg.(type) {
case *VoteMessage:
cs := conR.conS
cs.mtx.RLock()
height, valSize, lastCommitSize := cs.Height, cs.Validators.Size(), cs.LastCommit.Size()
cs.mtx.RUnlock()
ps.EnsureVoteBitArrays(height, valSize)
ps.EnsureVoteBitArrays(height-1, lastCommitSize)
ps.SetHasVote(msg.Vote)
cs.peerMsgQueue <- msgInfo{msg, e.Src.ID()}
default:
// don't punish (leave room for soft upgrades)
conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
}
case VoteSetBitsChannel:
if conR.WaitSync() {
conR.Logger.Info("Ignoring message received during sync", "msg", msg)
return
}
switch msg := msg.(type) {
case *VoteSetBitsMessage:
cs := conR.conS
cs.mtx.Lock()
height, votes := cs.Height, cs.Votes
cs.mtx.Unlock()
if height == msg.Height {
var ourVotes *bits.BitArray
switch msg.Type {
case cmtproto.PrevoteType:
ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(msg.BlockID)
case cmtproto.PrecommitType:
ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID)
default:
panic("Bad VoteSetBitsMessage field Type. Forgot to add a check in ValidateBasic?")
}
ps.ApplyVoteSetBitsMessage(msg, ourVotes)
} else {
ps.ApplyVoteSetBitsMessage(msg, nil)
}
default:
// don't punish (leave room for soft upgrades)
conR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
}
default:
conR.Logger.Error(fmt.Sprintf("Unknown chId %X", e.ChannelID))
}
}
// SetEventBus sets event bus.
func (conR *Reactor) SetEventBus(b *types.EventBus) {
conR.eventBus = b
conR.conS.SetEventBus(b)
}
// WaitSync returns whether the consensus reactor is waiting for state/block sync.
func (conR *Reactor) WaitSync() bool {
conR.mtx.RLock()
defer conR.mtx.RUnlock()
return conR.waitSync
}
//--------------------------------------
// subscribeToBroadcastEvents subscribes for new round steps and votes
// using internal pubsub defined on state to broadcast
// them to peers upon receiving.
func (conR *Reactor) subscribeToBroadcastEvents() {
const subscriber = "consensus-reactor"
if err := conR.conS.evsw.AddListenerForEvent(subscriber, types.EventNewRoundStep,
func(data cmtevents.EventData) {
conR.broadcastNewRoundStepMessage(data.(*cstypes.RoundState))
}); err != nil {
conR.Logger.Error("Error adding listener for events", "err", err)
}
if err := conR.conS.evsw.AddListenerForEvent(subscriber, types.EventValidBlock,
func(data cmtevents.EventData) {
conR.broadcastNewValidBlockMessage(data.(*cstypes.RoundState))
}); err != nil {
conR.Logger.Error("Error adding listener for events", "err", err)
}
if err := conR.conS.evsw.AddListenerForEvent(subscriber, types.EventVote,
func(data cmtevents.EventData) {
conR.broadcastHasVoteMessage(data.(*types.Vote))
}); err != nil {
conR.Logger.Error("Error adding listener for events", "err", err)
}
}
func (conR *Reactor) unsubscribeFromBroadcastEvents() {
const subscriber = "consensus-reactor"
conR.conS.evsw.RemoveListener(subscriber)
}
func (conR *Reactor) broadcastNewRoundStepMessage(rs *cstypes.RoundState) {
nrsMsg := makeRoundStepMessage(rs)
conR.Switch.Broadcast(p2p.Envelope{
ChannelID: StateChannel,
Message: nrsMsg,
})
}
func (conR *Reactor) broadcastNewValidBlockMessage(rs *cstypes.RoundState) {
psh := rs.ProposalBlockParts.Header()
csMsg := &cmtcons.NewValidBlock{
Height: rs.Height,
Round: rs.Round,
BlockPartSetHeader: psh.ToProto(),
BlockParts: rs.ProposalBlockParts.BitArray().ToProto(),
IsCommit: rs.Step == cstypes.RoundStepCommit,
}
conR.Switch.Broadcast(p2p.Envelope{
ChannelID: StateChannel,
Message: csMsg,
})
}
// Broadcasts HasVoteMessage to peers that care.
func (conR *Reactor) broadcastHasVoteMessage(vote *types.Vote) {
msg := &cmtcons.HasVote{
Height: vote.Height,
Round: vote.Round,
Type: vote.Type,
Index: vote.ValidatorIndex,
}
conR.Switch.Broadcast(p2p.Envelope{
ChannelID: StateChannel,
Message: msg,
})
/*
// TODO: Make this broadcast more selective.
for _, peer := range conR.Switch.Peers().List() {
ps, ok := peer.Get(PeerStateKey).(*PeerState)
if !ok {
panic(fmt.Sprintf("Peer %v has no state", peer))
}
prs := ps.GetRoundState()
if prs.Height == vote.Height {
// TODO: Also filter on round?
e := p2p.Envelope{
ChannelID: StateChannel, struct{ ConsensusMessage }{msg},
Message: p,
}
peer.TrySend(e)
} else {
// Height doesn't match
// TODO: check a field, maybe CatchupCommitRound?
// TODO: But that requires changing the struct field comment.
}
}
*/
}
func makeRoundStepMessage(rs *cstypes.RoundState) (nrsMsg *cmtcons.NewRoundStep) {
nrsMsg = &cmtcons.NewRoundStep{
Height: rs.Height,
Round: rs.Round,
Step: uint32(rs.Step),
SecondsSinceStartTime: int64(time.Since(rs.StartTime).Seconds()),
LastCommitRound: rs.LastCommit.GetRound(),
}
return
}
func (conR *Reactor) sendNewRoundStepMessage(peer p2p.Peer) {
rs := conR.getRoundState()
nrsMsg := makeRoundStepMessage(rs)
peer.Send(p2p.Envelope{
ChannelID: StateChannel,
Message: nrsMsg,
})
}
func (conR *Reactor) updateRoundStateRoutine() {
t := time.NewTicker(100 * time.Microsecond)
defer t.Stop()
for range t.C {
if !conR.IsRunning() {
return
}
rs := conR.conS.GetRoundState()
conR.mtx.Lock()
conR.rs = rs
conR.mtx.Unlock()
}
}
func (conR *Reactor) getRoundState() *cstypes.RoundState {
conR.mtx.RLock()
defer conR.mtx.RUnlock()
return conR.rs
}
func (conR *Reactor) gossipDataRoutine(peer p2p.Peer, ps *PeerState) {
logger := conR.Logger.With("peer", peer)
OUTER_LOOP:
for {
// Manage disconnects from self or peer.
if !peer.IsRunning() || !conR.IsRunning() {
return
}
rs := conR.getRoundState()
prs := ps.GetRoundState()
// Send proposal Block parts?
if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartSetHeader) {
if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok {
part := rs.ProposalBlockParts.GetPart(index)
parts, err := part.ToProto()
if err != nil {
panic(err)
}
logger.Debug("Sending block part", "height", prs.Height, "round", prs.Round)
if peer.Send(p2p.Envelope{
ChannelID: DataChannel,
Message: &cmtcons.BlockPart{
Height: rs.Height, // This tells peer that this part applies to us.
Round: rs.Round, // This tells peer that this part applies to us.
Part: *parts,
},
}) {
ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
}
continue OUTER_LOOP
}
}
// If the peer is on a previous height that we have, help catch up.
blockStoreBase := conR.conS.blockStore.Base()
if blockStoreBase > 0 && 0 < prs.Height && prs.Height < rs.Height && prs.Height >= blockStoreBase {
heightLogger := logger.With("height", prs.Height)
// if we never received the commit message from the peer, the block parts wont be initialized
if prs.ProposalBlockParts == nil {
blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height)
if blockMeta == nil {
heightLogger.Error("Failed to load block meta",
"blockstoreBase", blockStoreBase, "blockstoreHeight", conR.conS.blockStore.Height())
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
} else {
ps.InitProposalBlockParts(blockMeta.BlockID.PartSetHeader)
}
// continue the loop since prs is a copy and not effected by this initialization
continue OUTER_LOOP
}
conR.gossipDataForCatchup(heightLogger, rs, prs, ps, peer)
continue OUTER_LOOP
}
// If height and round don't match, sleep.
if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
// logger.Info("Peer Height|Round mismatch, sleeping",
// "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer)
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
continue OUTER_LOOP
}
// By here, height and round match.
// Proposal block parts were already matched and sent if any were wanted.
// (These can match on hash so the round doesn't matter)
// Now consider sending other things, like the Proposal itself.
// Send Proposal && ProposalPOL BitArray?
if rs.Proposal != nil && !prs.Proposal {
// Proposal: share the proposal metadata with peer.
{
logger.Debug("Sending proposal", "height", prs.Height, "round", prs.Round)
if peer.Send(p2p.Envelope{
ChannelID: DataChannel,
Message: &cmtcons.Proposal{Proposal: *rs.Proposal.ToProto()},
}) {
// NOTE[ZM]: A peer might have received different proposal msg so this Proposal msg will be rejected!
ps.SetHasProposal(rs.Proposal)
}
}
// ProposalPOL: lets peer know which POL votes we have so far.
// Peer must receive ProposalMessage first.
// rs.Proposal was validated, so rs.Proposal.POLRound <= rs.Round,
// so we definitely have rs.Votes.Prevotes(rs.Proposal.POLRound).
if 0 <= rs.Proposal.POLRound {
logger.Debug("Sending POL", "height", prs.Height, "round", prs.Round)
peer.Send(p2p.Envelope{
ChannelID: DataChannel,
Message: &cmtcons.ProposalPOL{
Height: rs.Height,
ProposalPolRound: rs.Proposal.POLRound,
ProposalPol: *rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray().ToProto(),
},
})
}
continue OUTER_LOOP
}
// Nothing to do. Sleep.
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
continue OUTER_LOOP
}
}
func (conR *Reactor) gossipDataForCatchup(logger log.Logger, rs *cstypes.RoundState,
prs *cstypes.PeerRoundState, ps *PeerState, peer p2p.Peer,
) {
if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok {
// Ensure that the peer's PartSetHeader is correct
blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height)
if blockMeta == nil {
logger.Error("Failed to load block meta", "ourHeight", rs.Height,
"blockstoreBase", conR.conS.blockStore.Base(), "blockstoreHeight", conR.conS.blockStore.Height())
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
return
} else if !blockMeta.BlockID.PartSetHeader.Equals(prs.ProposalBlockPartSetHeader) {
logger.Info("Peer ProposalBlockPartSetHeader mismatch, sleeping",
"blockPartSetHeader", blockMeta.BlockID.PartSetHeader, "peerBlockPartSetHeader", prs.ProposalBlockPartSetHeader)
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
return
}
// Load the part
part := conR.conS.blockStore.LoadBlockPart(prs.Height, index)
if part == nil {
logger.Error("Could not load part", "index", index,
"blockPartSetHeader", blockMeta.BlockID.PartSetHeader, "peerBlockPartSetHeader", prs.ProposalBlockPartSetHeader)
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
return
}
// Send the part
logger.Debug("Sending block part for catchup", "round", prs.Round, "index", index)
pp, err := part.ToProto()
if err != nil {
logger.Error("Could not convert part to proto", "index", index, "error", err)
return
}
if peer.Send(p2p.Envelope{
ChannelID: DataChannel,
Message: &cmtcons.BlockPart{
Height: prs.Height, // Not our height, so it doesn't matter.
Round: prs.Round, // Not our height, so it doesn't matter.
Part: *pp,
},
}) {
ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
} else {
logger.Debug("Sending block part for catchup failed")
// sleep to avoid retrying too fast
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
}
return
}
// logger.Info("No parts to send in catch-up, sleeping")
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
}
func (conR *Reactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) {
logger := conR.Logger.With("peer", peer)
// Simple hack to throttle logs upon sleep.
sleeping := 0
OUTER_LOOP:
for {
// Manage disconnects from self or peer.
if !peer.IsRunning() || !conR.IsRunning() {
return
}
rs := conR.getRoundState()
prs := ps.GetRoundState()
switch sleeping {
case 1: // First sleep
sleeping = 2
case 2: // No more sleep
sleeping = 0
}
// logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round,
// "prsHeight", prs.Height, "prsRound", prs.Round, "prsStep", prs.Step)
// If height matches, then send LastCommit, Prevotes, Precommits.
if rs.Height == prs.Height {
heightLogger := logger.With("height", prs.Height)
if conR.gossipVotesForHeight(heightLogger, rs, prs, ps) {
continue OUTER_LOOP
}
}
// Special catchup logic.
// If peer is lagging by height 1, send LastCommit.
if prs.Height != 0 && rs.Height == prs.Height+1 {
if ps.PickSendVote(rs.LastCommit) {
logger.Debug("Picked rs.LastCommit to send", "height", prs.Height)
continue OUTER_LOOP
}
}
// Catchup logic
// If peer is lagging by more than 1, send Commit.
blockStoreBase := conR.conS.blockStore.Base()
if blockStoreBase > 0 && prs.Height != 0 && rs.Height >= prs.Height+2 && prs.Height >= blockStoreBase {
// Load the block's extended commit for prs.Height,
// which contains precommit signatures for prs.Height.
var ec *types.ExtendedCommit
var veEnabled bool
func() {
conR.conS.mtx.RLock()
defer conR.conS.mtx.RUnlock()
veEnabled = conR.conS.state.ConsensusParams.ABCI.VoteExtensionsEnabled(prs.Height)
}()
if veEnabled {
ec = conR.conS.blockStore.LoadBlockExtendedCommit(prs.Height)
} else {
c := conR.conS.blockStore.LoadBlockCommit(prs.Height)
if c == nil {
continue
}
ec = c.WrappedExtendedCommit()
}
if ec == nil {
continue
}
if ps.PickSendVote(ec) {
logger.Debug("Picked Catchup commit to send", "height", prs.Height)
continue OUTER_LOOP
}
}
if sleeping == 0 {
// We sent nothing. Sleep...
sleeping = 1
logger.Debug("No votes to send, sleeping", "rs.Height", rs.Height, "prs.Height", prs.Height,
"localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
"localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits)
} else if sleeping == 2 {
// Continued sleep...
sleeping = 1
}
time.Sleep(conR.conS.config.PeerGossipSleepDuration)
continue OUTER_LOOP
}
}
func (conR *Reactor) gossipVotesForHeight(
logger log.Logger,
rs *cstypes.RoundState,
prs *cstypes.PeerRoundState,
ps *PeerState,
) bool {
// If there are lastCommits to send...
if prs.Step == cstypes.RoundStepNewHeight {
if ps.PickSendVote(rs.LastCommit) {
logger.Debug("Picked rs.LastCommit to send")
return true
}
}
// If there are POL prevotes to send...
if prs.Step <= cstypes.RoundStepPropose && prs.Round != -1 && prs.Round <= rs.Round && prs.ProposalPOLRound != -1 {
if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
if ps.PickSendVote(polPrevotes) {
logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send",
"round", prs.ProposalPOLRound)
return true
}
}
}
// If there are prevotes to send...
if prs.Step <= cstypes.RoundStepPrevoteWait && prs.Round != -1 && prs.Round <= rs.Round {
if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) {
logger.Debug("Picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
return true
}
}
// If there are precommits to send...
if prs.Step <= cstypes.RoundStepPrecommitWait && prs.Round != -1 && prs.Round <= rs.Round {
if ps.PickSendVote(rs.Votes.Precommits(prs.Round)) {
logger.Debug("Picked rs.Precommits(prs.Round) to send", "round", prs.Round)
return true
}
}
// If there are prevotes to send...Needed because of validBlock mechanism
if prs.Round != -1 && prs.Round <= rs.Round {
if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) {
logger.Debug("Picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
return true
}
}
// If there are POLPrevotes to send...
if prs.ProposalPOLRound != -1 {
if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
if ps.PickSendVote(polPrevotes) {
logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send",
"round", prs.ProposalPOLRound)
return true
}
}
}
return false
}
// NOTE: `queryMaj23Routine` has a simple crude design since it only comes
// into play for liveness when there's a signature DDoS attack happening.
func (conR *Reactor) queryMaj23Routine(peer p2p.Peer, ps *PeerState) {
OUTER_LOOP:
for {
// Manage disconnects from self or peer.
if !peer.IsRunning() || !conR.IsRunning() {
return
}
// Maybe send Height/Round/Prevotes
{
rs := conR.getRoundState()
prs := ps.GetRoundState()
if rs.Height == prs.Height {
if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
peer.TrySend(p2p.Envelope{
ChannelID: StateChannel,
Message: &cmtcons.VoteSetMaj23{
Height: prs.Height,
Round: prs.Round,
Type: cmtproto.PrevoteType,
BlockID: maj23.ToProto(),
},
})
time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration)
}
}
}
// Maybe send Height/Round/Precommits
{
rs := conR.getRoundState()
prs := ps.GetRoundState()
if rs.Height == prs.Height {
if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
peer.TrySend(p2p.Envelope{
ChannelID: StateChannel,
Message: &cmtcons.VoteSetMaj23{
Height: prs.Height,
Round: prs.Round,
Type: cmtproto.PrecommitType,
BlockID: maj23.ToProto(),
},
})
time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration)
}
}
}
// Maybe send Height/Round/ProposalPOL
{
rs := conR.getRoundState()
prs := ps.GetRoundState()
if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 {
if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
peer.TrySend(p2p.Envelope{
ChannelID: StateChannel,
Message: &cmtcons.VoteSetMaj23{
Height: prs.Height,
Round: prs.ProposalPOLRound,
Type: cmtproto.PrevoteType,
BlockID: maj23.ToProto(),
},
})
time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration)
}
}
}
// Little point sending LastCommitRound/LastCommit,
// These are fleeting and non-blocking.
// Maybe send Height/CatchupCommitRound/CatchupCommit.
{
prs := ps.GetRoundState()
if prs.CatchupCommitRound != -1 && prs.Height > 0 && prs.Height <= conR.conS.blockStore.Height() &&
prs.Height >= conR.conS.blockStore.Base() {
if commit := conR.conS.LoadCommit(prs.Height); commit != nil {
peer.TrySend(p2p.Envelope{
ChannelID: StateChannel,
Message: &cmtcons.VoteSetMaj23{
Height: prs.Height,
Round: commit.Round,
Type: cmtproto.PrecommitType,
BlockID: commit.BlockID.ToProto(),
},
})
time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration)
}
}
}
time.Sleep(conR.conS.config.PeerQueryMaj23SleepDuration)
continue OUTER_LOOP
}
}
func (conR *Reactor) peerStatsRoutine() {
for {
if !conR.IsRunning() {
conR.Logger.Info("Stopping peerStatsRoutine")
return
}
select {
case msg := <-conR.conS.statsMsgQueue:
// Get peer
peer := conR.Switch.Peers().Get(msg.PeerID)
if peer == nil {
conR.Logger.Debug("Attempt to update stats for non-existent peer",
"peer", msg.PeerID)
continue
}
// Get peer state
ps, ok := peer.Get(types.PeerStateKey).(*PeerState)
if !ok {
panic(fmt.Sprintf("Peer %v has no state", peer))
}
switch msg.Msg.(type) {
case *VoteMessage:
if numVotes := ps.RecordVote(); numVotes%votesToContributeToBecomeGoodPeer == 0 {
conR.Switch.MarkPeerAsGood(peer)
}
case *BlockPartMessage:
if numParts := ps.RecordBlockPart(); numParts%blocksToContributeToBecomeGoodPeer == 0 {
conR.Switch.MarkPeerAsGood(peer)
}
}
case <-conR.conS.Quit():
return
case <-conR.Quit():
return
}
}
}
// String returns a string representation of the Reactor.
// NOTE: For now, it is just a hard-coded string to avoid accessing unprotected shared variables.
// TODO: improve!
func (conR *Reactor) String() string {
// better not to access shared variables
return "ConsensusReactor" // conR.StringIndented("")
}
// StringIndented returns an indented string representation of the Reactor
func (conR *Reactor) StringIndented(indent string) string {
s := "ConsensusReactor{\n"
s += indent + " " + conR.conS.StringIndented(indent+" ") + "\n"
for _, peer := range conR.Switch.Peers().List() {
ps, ok := peer.Get(types.PeerStateKey).(*PeerState)
if !ok {
panic(fmt.Sprintf("Peer %v has no state", peer))
}
s += indent + " " + ps.StringIndented(indent+" ") + "\n"
}
s += indent + "}"
return s
}
// ReactorMetrics sets the metrics
func ReactorMetrics(metrics *Metrics) ReactorOption {
return func(conR *Reactor) { conR.Metrics = metrics }
}
//-----------------------------------------------------------------------------
var (
ErrPeerStateHeightRegression = errors.New("error peer state height regression")
ErrPeerStateInvalidStartTime = errors.New("error peer state invalid startTime")
)
// PeerState contains the known state of a peer, including its connection and
// threadsafe access to its PeerRoundState.
// NOTE: THIS GETS DUMPED WITH rpc/core/consensus.go.
// Be mindful of what you Expose.
type PeerState struct {
peer p2p.Peer
logger log.Logger
mtx sync.Mutex // NOTE: Modify below using setters, never directly.
PRS cstypes.PeerRoundState `json:"round_state"` // Exposed.
Stats *peerStateStats `json:"stats"` // Exposed.
}
// peerStateStats holds internal statistics for a peer.
type peerStateStats struct {
Votes int `json:"votes"`
BlockParts int `json:"block_parts"`
}
func (pss peerStateStats) String() string {
return fmt.Sprintf("peerStateStats{votes: %d, blockParts: %d}",
pss.Votes, pss.BlockParts)
}
// NewPeerState returns a new PeerState for the given Peer
func NewPeerState(peer p2p.Peer) *PeerState {
return &PeerState{
peer: peer,
logger: log.NewNopLogger(),
PRS: cstypes.PeerRoundState{
Round: -1,
ProposalPOLRound: -1,
LastCommitRound: -1,
CatchupCommitRound: -1,
},
Stats: &peerStateStats{},
}
}
// SetLogger allows to set a logger on the peer state. Returns the peer state
// itself.
func (ps *PeerState) SetLogger(logger log.Logger) *PeerState {
ps.logger = logger
return ps
}
// GetRoundState returns an shallow copy of the PeerRoundState.
// There's no point in mutating it since it won't change PeerState.
func (ps *PeerState) GetRoundState() *cstypes.PeerRoundState {
ps.mtx.Lock()
defer ps.mtx.Unlock()
prs := ps.PRS // copy
return &prs
}
// MarshalJSON implements the json.Marshaler interface.
func (ps *PeerState) MarshalJSON() ([]byte, error) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
type jsonPeerState PeerState
return cmtjson.Marshal((*jsonPeerState)(ps))
}
// GetHeight returns an atomic snapshot of the PeerRoundState's height
// used by the mempool to ensure peers are caught up before broadcasting new txs
func (ps *PeerState) GetHeight() int64 {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return ps.PRS.Height
}
// SetHasProposal sets the given proposal as known for the peer.
func (ps *PeerState) SetHasProposal(proposal *types.Proposal) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
if ps.PRS.Height != proposal.Height || ps.PRS.Round != proposal.Round {
return
}
if ps.PRS.Proposal {
return
}
ps.PRS.Proposal = true
// ps.PRS.ProposalBlockParts is set due to NewValidBlockMessage
if ps.PRS.ProposalBlockParts != nil {
return
}
ps.PRS.ProposalBlockPartSetHeader = proposal.BlockID.PartSetHeader
ps.PRS.ProposalBlockParts = bits.NewBitArray(int(proposal.BlockID.PartSetHeader.Total))
ps.PRS.ProposalPOLRound = proposal.POLRound
ps.PRS.ProposalPOL = nil // Nil until ProposalPOLMessage received.
}
// InitProposalBlockParts initializes the peer's proposal block parts header and bit array.
func (ps *PeerState) InitProposalBlockParts(partSetHeader types.PartSetHeader) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
if ps.PRS.ProposalBlockParts != nil {
return
}
ps.PRS.ProposalBlockPartSetHeader = partSetHeader
ps.PRS.ProposalBlockParts = bits.NewBitArray(int(partSetHeader.Total))
}
// SetHasProposalBlockPart sets the given block part index as known for the peer.
func (ps *PeerState) SetHasProposalBlockPart(height int64, round int32, index int) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
if ps.PRS.Height != height || ps.PRS.Round != round {
return
}
ps.PRS.ProposalBlockParts.SetIndex(index, true)
}
// PickSendVote picks a vote and sends it to the peer.
// Returns true if vote was sent.
func (ps *PeerState) PickSendVote(votes types.VoteSetReader) bool {
if vote, ok := ps.PickVoteToSend(votes); ok {
ps.logger.Debug("Sending vote message", "ps", ps, "vote", vote)
if ps.peer.Send(p2p.Envelope{
ChannelID: VoteChannel,
Message: &cmtcons.Vote{
Vote: vote.ToProto(),
},
}) {
ps.SetHasVote(vote)
return true
}
return false
}
return false
}
// PickVoteToSend picks a vote to send to the peer.
// Returns true if a vote was picked.
// NOTE: `votes` must be the correct Size() for the Height().
func (ps *PeerState) PickVoteToSend(votes types.VoteSetReader) (vote *types.Vote, ok bool) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
if votes.Size() == 0 {
return nil, false
}
height, round, votesType, size := votes.GetHeight(), votes.GetRound(), cmtproto.SignedMsgType(votes.Type()), votes.Size()
// Lazily set data using 'votes'.
if votes.IsCommit() {
ps.ensureCatchupCommitRound(height, round, size)
}
ps.ensureVoteBitArrays(height, size)
psVotes := ps.getVoteBitArray(height, round, votesType)
if psVotes == nil {
return nil, false // Not something worth sending
}
if index, ok := votes.BitArray().Sub(psVotes).PickRandom(); ok {
return votes.GetByIndex(int32(index)), true
}
return nil, false
}
func (ps *PeerState) getVoteBitArray(height int64, round int32, votesType cmtproto.SignedMsgType) *bits.BitArray {
if !types.IsVoteTypeValid(votesType) {
return nil
}
if ps.PRS.Height == height {
if ps.PRS.Round == round {
switch votesType {
case cmtproto.PrevoteType:
return ps.PRS.Prevotes
case cmtproto.PrecommitType:
return ps.PRS.Precommits
}
}
if ps.PRS.CatchupCommitRound == round {
switch votesType {
case cmtproto.PrevoteType:
return nil
case cmtproto.PrecommitType:
return ps.PRS.CatchupCommit
}
}
if ps.PRS.ProposalPOLRound == round {
switch votesType {
case cmtproto.PrevoteType:
return ps.PRS.ProposalPOL
case cmtproto.PrecommitType:
return nil
}
}
return nil
}
if ps.PRS.Height == height+1 {
if ps.PRS.LastCommitRound == round {
switch votesType {
case cmtproto.PrevoteType:
return nil
case cmtproto.PrecommitType:
return ps.PRS.LastCommit
}
}
return nil
}
return nil
}
// 'round': A round for which we have a +2/3 commit.
func (ps *PeerState) ensureCatchupCommitRound(height int64, round int32, numValidators int) {
if ps.PRS.Height != height {
return
}
/*
NOTE: This is wrong, 'round' could change.
e.g. if orig round is not the same as block LastCommit round.
if ps.CatchupCommitRound != -1 && ps.CatchupCommitRound != round {
panic(fmt.Sprintf(
"Conflicting CatchupCommitRound. Height: %v,
Orig: %v,
New: %v",
height,
ps.CatchupCommitRound,
round))
}
*/
if ps.PRS.CatchupCommitRound == round {
return // Nothing to do!
}
ps.PRS.CatchupCommitRound = round
if round == ps.PRS.Round {
ps.PRS.CatchupCommit = ps.PRS.Precommits
} else {
ps.PRS.CatchupCommit = bits.NewBitArray(numValidators)
}
}
// EnsureVoteBitArrays ensures the bit-arrays have been allocated for tracking
// what votes this peer has received.
// NOTE: It's important to make sure that numValidators actually matches
// what the node sees as the number of validators for height.
func (ps *PeerState) EnsureVoteBitArrays(height int64, numValidators int) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
ps.ensureVoteBitArrays(height, numValidators)
}
func (ps *PeerState) ensureVoteBitArrays(height int64, numValidators int) {
if ps.PRS.Height == height {
if ps.PRS.Prevotes == nil {
ps.PRS.Prevotes = bits.NewBitArray(numValidators)
}
if ps.PRS.Precommits == nil {
ps.PRS.Precommits = bits.NewBitArray(numValidators)
}
if ps.PRS.CatchupCommit == nil {
ps.PRS.CatchupCommit = bits.NewBitArray(numValidators)
}
if ps.PRS.ProposalPOL == nil {
ps.PRS.ProposalPOL = bits.NewBitArray(numValidators)
}
} else if ps.PRS.Height == height+1 {
if ps.PRS.LastCommit == nil {
ps.PRS.LastCommit = bits.NewBitArray(numValidators)
}
}
}
// RecordVote increments internal votes related statistics for this peer.
// It returns the total number of added votes.
func (ps *PeerState) RecordVote() int {
ps.mtx.Lock()
defer ps.mtx.Unlock()
ps.Stats.Votes++
return ps.Stats.Votes
}
// VotesSent returns the number of blocks for which peer has been sending us
// votes.
func (ps *PeerState) VotesSent() int {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return ps.Stats.Votes
}
// RecordBlockPart increments internal block part related statistics for this peer.
// It returns the total number of added block parts.
func (ps *PeerState) RecordBlockPart() int {
ps.mtx.Lock()
defer ps.mtx.Unlock()
ps.Stats.BlockParts++
return ps.Stats.BlockParts
}
// BlockPartsSent returns the number of useful block parts the peer has sent us.
func (ps *PeerState) BlockPartsSent() int {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return ps.Stats.BlockParts
}
// SetHasVote sets the given vote as known by the peer
func (ps *PeerState) SetHasVote(vote *types.Vote) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
ps.setHasVote(vote.Height, vote.Round, vote.Type, vote.ValidatorIndex)
}
func (ps *PeerState) setHasVote(height int64, round int32, voteType cmtproto.SignedMsgType, index int32) {
ps.logger.Debug("setHasVote",
"peerH/R",
log.NewLazySprintf("%d/%d", ps.PRS.Height, ps.PRS.Round),
"H/R",
log.NewLazySprintf("%d/%d", height, round),
"type", voteType, "index", index)
// NOTE: some may be nil BitArrays -> no side effects.
psVotes := ps.getVoteBitArray(height, round, voteType)
if psVotes != nil {
psVotes.SetIndex(int(index), true)
}
}
// ApplyNewRoundStepMessage updates the peer state for the new round.
func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
// Ignore duplicates or decreases
if CompareHRS(msg.Height, msg.Round, msg.Step, ps.PRS.Height, ps.PRS.Round, ps.PRS.Step) <= 0 {
return
}
// Just remember these values.
psHeight := ps.PRS.Height
psRound := ps.PRS.Round
psCatchupCommitRound := ps.PRS.CatchupCommitRound
psCatchupCommit := ps.PRS.CatchupCommit
lastPrecommits := ps.PRS.Precommits
startTime := cmttime.Now().Add(-1 * time.Duration(msg.SecondsSinceStartTime) * time.Second)
ps.PRS.Height = msg.Height
ps.PRS.Round = msg.Round
ps.PRS.Step = msg.Step
ps.PRS.StartTime = startTime
if psHeight != msg.Height || psRound != msg.Round {
ps.PRS.Proposal = false
ps.PRS.ProposalBlockPartSetHeader = types.PartSetHeader{}
ps.PRS.ProposalBlockParts = nil
ps.PRS.ProposalPOLRound = -1
ps.PRS.ProposalPOL = nil
// We'll update the BitArray capacity later.
ps.PRS.Prevotes = nil
ps.PRS.Precommits = nil
}
if psHeight == msg.Height && psRound != msg.Round && msg.Round == psCatchupCommitRound {
// Peer caught up to CatchupCommitRound.
// Preserve psCatchupCommit!
// NOTE: We prefer to use prs.Precommits if
// pr.Round matches pr.CatchupCommitRound.
ps.PRS.Precommits = psCatchupCommit
}
if psHeight != msg.Height {
// Shift Precommits to LastCommit.
if psHeight+1 == msg.Height && psRound == msg.LastCommitRound {
ps.PRS.LastCommitRound = msg.LastCommitRound
ps.PRS.LastCommit = lastPrecommits
} else {
ps.PRS.LastCommitRound = msg.LastCommitRound
ps.PRS.LastCommit = nil
}
// We'll update the BitArray capacity later.
ps.PRS.CatchupCommitRound = -1
ps.PRS.CatchupCommit = nil
}
}
// ApplyNewValidBlockMessage updates the peer state for the new valid block.
func (ps *PeerState) ApplyNewValidBlockMessage(msg *NewValidBlockMessage) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
if ps.PRS.Height != msg.Height {
return
}
if ps.PRS.Round != msg.Round && !msg.IsCommit {
return
}
ps.PRS.ProposalBlockPartSetHeader = msg.BlockPartSetHeader
ps.PRS.ProposalBlockParts = msg.BlockParts
}
// ApplyProposalPOLMessage updates the peer state for the new proposal POL.
func (ps *PeerState) ApplyProposalPOLMessage(msg *ProposalPOLMessage) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
if ps.PRS.Height != msg.Height {
return
}
if ps.PRS.ProposalPOLRound != msg.ProposalPOLRound {
return
}
// TODO: Merge onto existing ps.PRS.ProposalPOL?
// We might have sent some prevotes in the meantime.
ps.PRS.ProposalPOL = msg.ProposalPOL
}
// ApplyHasVoteMessage updates the peer state for the new vote.
func (ps *PeerState) ApplyHasVoteMessage(msg *HasVoteMessage) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
if ps.PRS.Height != msg.Height {
return
}
ps.setHasVote(msg.Height, msg.Round, msg.Type, msg.Index)
}
// ApplyVoteSetBitsMessage updates the peer state for the bit-array of votes
// it claims to have for the corresponding BlockID.
// `ourVotes` is a BitArray of votes we have for msg.BlockID
// NOTE: if ourVotes is nil (e.g. msg.Height < rs.Height),
// we conservatively overwrite ps's votes w/ msg.Votes.
func (ps *PeerState) ApplyVoteSetBitsMessage(msg *VoteSetBitsMessage, ourVotes *bits.BitArray) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
votes := ps.getVoteBitArray(msg.Height, msg.Round, msg.Type)
if votes != nil {
if ourVotes == nil {
votes.Update(msg.Votes)
} else {
otherVotes := votes.Sub(ourVotes)
hasVotes := otherVotes.Or(msg.Votes)
votes.Update(hasVotes)
}
}
}
// String returns a string representation of the PeerState
func (ps *PeerState) String() string {
return ps.StringIndented("")
}
// StringIndented returns a string representation of the PeerState
func (ps *PeerState) StringIndented(indent string) string {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return fmt.Sprintf(`PeerState{
%s Key %v
%s RoundState %v
%s Stats %v
%s}`,
indent, ps.peer.ID(),
indent, ps.PRS.StringIndented(indent+" "),
indent, ps.Stats,
indent)
}
//-----------------------------------------------------------------------------
// Messages
// Message is a message that can be sent and received on the Reactor
type Message interface {
ValidateBasic() error
}
func init() {
cmtjson.RegisterType(&NewRoundStepMessage{}, "tendermint/NewRoundStepMessage")
cmtjson.RegisterType(&NewValidBlockMessage{}, "tendermint/NewValidBlockMessage")
cmtjson.RegisterType(&ProposalMessage{}, "tendermint/Proposal")
cmtjson.RegisterType(&ProposalPOLMessage{}, "tendermint/ProposalPOL")
cmtjson.RegisterType(&BlockPartMessage{}, "tendermint/BlockPart")
cmtjson.RegisterType(&VoteMessage{}, "tendermint/Vote")
cmtjson.RegisterType(&HasVoteMessage{}, "tendermint/HasVote")
cmtjson.RegisterType(&VoteSetMaj23Message{}, "tendermint/VoteSetMaj23")
cmtjson.RegisterType(&VoteSetBitsMessage{}, "tendermint/VoteSetBits")
}
//-------------------------------------
// NewRoundStepMessage is sent for every step taken in the ConsensusState.
// For every height/round/step transition
type NewRoundStepMessage struct {
Height int64
Round int32
Step cstypes.RoundStepType
SecondsSinceStartTime int64
LastCommitRound int32
}
// ValidateBasic performs basic validation.
func (m *NewRoundStepMessage) ValidateBasic() error {
if m.Height < 0 {
return errors.New("negative Height")
}
if m.Round < 0 {
return errors.New("negative Round")
}
if !m.Step.IsValid() {
return errors.New("invalid Step")
}
// NOTE: SecondsSinceStartTime may be negative
// LastCommitRound will be -1 for the initial height, but we don't know what height this is
// since it can be specified in genesis. The reactor will have to validate this via
// ValidateHeight().
if m.LastCommitRound < -1 {
return errors.New("invalid LastCommitRound (cannot be < -1)")
}
return nil
}
// ValidateHeight validates the height given the chain's initial height.
func (m *NewRoundStepMessage) ValidateHeight(initialHeight int64) error {
if m.Height < initialHeight {
return fmt.Errorf("invalid Height %v (lower than initial height %v)",
m.Height, initialHeight)
}
if m.Height == initialHeight && m.LastCommitRound != -1 {
return fmt.Errorf("invalid LastCommitRound %v (must be -1 for initial height %v)",
m.LastCommitRound, initialHeight)
}
if m.Height > initialHeight && m.LastCommitRound < 0 {
return fmt.Errorf("LastCommitRound can only be negative for initial height %v",
initialHeight)
}
return nil
}
// String returns a string representation.
func (m *NewRoundStepMessage) String() string {
return fmt.Sprintf("[NewRoundStep H:%v R:%v S:%v LCR:%v]",
m.Height, m.Round, m.Step, m.LastCommitRound)
}
//-------------------------------------
// NewValidBlockMessage is sent when a validator observes a valid block B in some round r,
// i.e., there is a Proposal for block B and 2/3+ prevotes for the block B in the round r.
// In case the block is also committed, then IsCommit flag is set to true.
type NewValidBlockMessage struct {
Height int64
Round int32
BlockPartSetHeader types.PartSetHeader
BlockParts *bits.BitArray
IsCommit bool
}
// ValidateBasic performs basic validation.
func (m *NewValidBlockMessage) ValidateBasic() error {
if m.Height < 0 {
return errors.New("negative Height")
}
if m.Round < 0 {
return errors.New("negative Round")
}
if err := m.BlockPartSetHeader.ValidateBasic(); err != nil {
return fmt.Errorf("wrong BlockPartSetHeader: %v", err)
}
if m.BlockParts.Size() == 0 {
return errors.New("empty blockParts")
}
if m.BlockParts.Size() != int(m.BlockPartSetHeader.Total) {
return fmt.Errorf("blockParts bit array size %d not equal to BlockPartSetHeader.Total %d",
m.BlockParts.Size(),
m.BlockPartSetHeader.Total)
}
if m.BlockParts.Size() > int(types.MaxBlockPartsCount) {
return fmt.Errorf("blockParts bit array is too big: %d, max: %d", m.BlockParts.Size(), types.MaxBlockPartsCount)
}
return nil
}
// String returns a string representation.
func (m *NewValidBlockMessage) String() string {
return fmt.Sprintf("[ValidBlockMessage H:%v R:%v BP:%v BA:%v IsCommit:%v]",
m.Height, m.Round, m.BlockPartSetHeader, m.BlockParts, m.IsCommit)
}
//-------------------------------------
// ProposalMessage is sent when a new block is proposed.
type ProposalMessage struct {
Proposal *types.Proposal
}
// ValidateBasic performs basic validation.
func (m *ProposalMessage) ValidateBasic() error {
return m.Proposal.ValidateBasic()
}
// String returns a string representation.
func (m *ProposalMessage) String() string {
return fmt.Sprintf("[Proposal %v]", m.Proposal)
}
//-------------------------------------
// ProposalPOLMessage is sent when a previous proposal is re-proposed.
type ProposalPOLMessage struct {
Height int64
ProposalPOLRound int32
ProposalPOL *bits.BitArray
}
// ValidateBasic performs basic validation.
func (m *ProposalPOLMessage) ValidateBasic() error {
if m.Height < 0 {
return errors.New("negative Height")
}
if m.ProposalPOLRound < 0 {
return errors.New("negative ProposalPOLRound")
}
if m.ProposalPOL.Size() == 0 {
return errors.New("empty ProposalPOL bit array")
}
if m.ProposalPOL.Size() > types.MaxVotesCount {
return fmt.Errorf("proposalPOL bit array is too big: %d, max: %d", m.ProposalPOL.Size(), types.MaxVotesCount)
}
return nil
}
// String returns a string representation.
func (m *ProposalPOLMessage) String() string {
return fmt.Sprintf("[ProposalPOL H:%v POLR:%v POL:%v]", m.Height, m.ProposalPOLRound, m.ProposalPOL)
}
//-------------------------------------
// BlockPartMessage is sent when gossipping a piece of the proposed block.
type BlockPartMessage struct {
Height int64
Round int32
Part *types.Part
}
// ValidateBasic performs basic validation.
func (m *BlockPartMessage) ValidateBasic() error {
if m.Height < 0 {
return errors.New("negative Height")
}
if m.Round < 0 {
return errors.New("negative Round")
}
if err := m.Part.ValidateBasic(); err != nil {
return fmt.Errorf("wrong Part: %v", err)
}
return nil
}
// String returns a string representation.
func (m *BlockPartMessage) String() string {
return fmt.Sprintf("[BlockPart H:%v R:%v P:%v]", m.Height, m.Round, m.Part)
}
//-------------------------------------
// VoteMessage is sent when voting for a proposal (or lack thereof).
type VoteMessage struct {
Vote *types.Vote
}
// ValidateBasic checks whether the vote within the message is well-formed.
func (m *VoteMessage) ValidateBasic() error {
return m.Vote.ValidateBasic()
}
// String returns a string representation.
func (m *VoteMessage) String() string {
return fmt.Sprintf("[Vote %v]", m.Vote)
}
//-------------------------------------
// HasVoteMessage is sent to indicate that a particular vote has been received.
type HasVoteMessage struct {
Height int64
Round int32
Type cmtproto.SignedMsgType
Index int32
}
// ValidateBasic performs basic validation.
func (m *HasVoteMessage) ValidateBasic() error {
if m.Height < 0 {
return errors.New("negative Height")
}
if m.Round < 0 {
return errors.New("negative Round")
}
if !types.IsVoteTypeValid(m.Type) {
return errors.New("invalid Type")
}
if m.Index < 0 {
return errors.New("negative Index")
}
return nil
}
// String returns a string representation.
func (m *HasVoteMessage) String() string {
return fmt.Sprintf("[HasVote VI:%v V:{%v/%02d/%v}]", m.Index, m.Height, m.Round, m.Type)
}
//-------------------------------------
// VoteSetMaj23Message is sent to indicate that a given BlockID has seen +2/3 votes.
type VoteSetMaj23Message struct {
Height int64
Round int32
Type cmtproto.SignedMsgType
BlockID types.BlockID
}
// ValidateBasic performs basic validation.
func (m *VoteSetMaj23Message) ValidateBasic() error {
if m.Height < 0 {
return errors.New("negative Height")
}
if m.Round < 0 {
return errors.New("negative Round")
}
if !types.IsVoteTypeValid(m.Type) {
return errors.New("invalid Type")
}
if err := m.BlockID.ValidateBasic(); err != nil {
return fmt.Errorf("wrong BlockID: %v", err)
}
return nil
}
// String returns a string representation.
func (m *VoteSetMaj23Message) String() string {
return fmt.Sprintf("[VSM23 %v/%02d/%v %v]", m.Height, m.Round, m.Type, m.BlockID)
}
//-------------------------------------
// VoteSetBitsMessage is sent to communicate the bit-array of votes seen for the BlockID.
type VoteSetBitsMessage struct {
Height int64
Round int32
Type cmtproto.SignedMsgType
BlockID types.BlockID
Votes *bits.BitArray
}
// ValidateBasic performs basic validation.
func (m *VoteSetBitsMessage) ValidateBasic() error {
if m.Height < 0 {
return errors.New("negative Height")
}
if !types.IsVoteTypeValid(m.Type) {
return errors.New("invalid Type")
}
if err := m.BlockID.ValidateBasic(); err != nil {
return fmt.Errorf("wrong BlockID: %v", err)
}
// NOTE: Votes.Size() can be zero if the node does not have any
if m.Votes.Size() > types.MaxVotesCount {
return fmt.Errorf("votes bit array is too big: %d, max: %d", m.Votes.Size(), types.MaxVotesCount)
}
return nil
}
// String returns a string representation.
func (m *VoteSetBitsMessage) String() string {
return fmt.Sprintf("[VSB %v/%02d/%v %v %v]", m.Height, m.Round, m.Type, m.BlockID, m.Votes)
}
//-------------------------------------
package autofile
import (
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
cmtrand "github.com/cometbft/cometbft/libs/rand"
)
/* AutoFile usage
// Create/Append to ./autofile_test
af, err := OpenAutoFile("autofile_test")
if err != nil {
panic(err)
}
// Stream of writes.
// During this time, the file may be moved e.g. by logRotate.
for i := 0; i < 60; i++ {
af.Write([]byte(Fmt("LOOP(%v)", i)))
time.Sleep(time.Second)
}
// Close the AutoFile
err = af.Close()
if err != nil {
panic(err)
}
*/
const (
autoFileClosePeriod = 1000 * time.Millisecond
autoFilePerms = os.FileMode(0600)
)
// AutoFile automatically closes and re-opens file for writing. The file is
// automatically setup to close itself every 1s and upon receiving SIGHUP.
//
// This is useful for using a log file with the logrotate tool.
type AutoFile struct {
ID string
Path string
closeTicker *time.Ticker
closeTickerStopc chan struct{} // closed when closeTicker is stopped
hupc chan os.Signal
mtx sync.Mutex
file *os.File
}
// OpenAutoFile creates an AutoFile in the path (with random ID). If there is
// an error, it will be of type *PathError or *ErrPermissionsChanged (if file's
// permissions got changed (should be 0600)).
func OpenAutoFile(path string) (*AutoFile, error) {
var err error
path, err = filepath.Abs(path)
if err != nil {
return nil, err
}
af := &AutoFile{
ID: cmtrand.Str(12) + ":" + path,
Path: path,
closeTicker: time.NewTicker(autoFileClosePeriod),
closeTickerStopc: make(chan struct{}),
}
if err := af.openFile(); err != nil {
af.Close()
return nil, err
}
// Close file on SIGHUP.
af.hupc = make(chan os.Signal, 1)
signal.Notify(af.hupc, syscall.SIGHUP)
go func() {
for range af.hupc {
_ = af.closeFile()
}
}()
go af.closeFileRoutine()
return af, nil
}
// Close shuts down the closing goroutine, SIGHUP handler and closes the
// AutoFile.
func (af *AutoFile) Close() error {
af.closeTicker.Stop()
close(af.closeTickerStopc)
if af.hupc != nil {
close(af.hupc)
}
return af.closeFile()
}
func (af *AutoFile) closeFileRoutine() {
for {
select {
case <-af.closeTicker.C:
_ = af.closeFile()
case <-af.closeTickerStopc:
return
}
}
}
func (af *AutoFile) closeFile() (err error) {
af.mtx.Lock()
defer af.mtx.Unlock()
file := af.file
if file == nil {
return nil
}
af.file = nil
return file.Close()
}
// Write writes len(b) bytes to the AutoFile. It returns the number of bytes
// written and an error, if any. Write returns a non-nil error when n !=
// len(b).
// Opens AutoFile if needed.
func (af *AutoFile) Write(b []byte) (n int, err error) {
af.mtx.Lock()
defer af.mtx.Unlock()
if af.file == nil {
if err = af.openFile(); err != nil {
return
}
}
n, err = af.file.Write(b)
return
}
// Sync commits the current contents of the file to stable storage. Typically,
// this means flushing the file system's in-memory copy of recently written
// data to disk.
// Opens AutoFile if needed.
func (af *AutoFile) Sync() error {
af.mtx.Lock()
defer af.mtx.Unlock()
if af.file == nil {
if err := af.openFile(); err != nil {
return err
}
}
return af.file.Sync()
}
func (af *AutoFile) openFile() error {
file, err := os.OpenFile(af.Path, os.O_RDWR|os.O_CREATE|os.O_APPEND, autoFilePerms)
if err != nil {
return err
}
// fileInfo, err := file.Stat()
// if err != nil {
// return err
// }
// if fileInfo.Mode() != autoFilePerms {
// return errors.NewErrPermissionsChanged(file.Name(), fileInfo.Mode(), autoFilePerms)
// }
af.file = file
return nil
}
// Size returns the size of the AutoFile. It returns -1 and an error if fails
// get stats or open file.
// Opens AutoFile if needed.
func (af *AutoFile) Size() (int64, error) {
af.mtx.Lock()
defer af.mtx.Unlock()
if af.file == nil {
if err := af.openFile(); err != nil {
return -1, err
}
}
stat, err := af.file.Stat()
if err != nil {
return -1, err
}
return stat.Size(), nil
}
package bits
import (
"encoding/binary"
"fmt"
"math/bits"
"regexp"
"strings"
"sync"
cmtmath "github.com/cometbft/cometbft/libs/math"
cmtrand "github.com/cometbft/cometbft/libs/rand"
cmtprotobits "github.com/cometbft/cometbft/proto/tendermint/libs/bits"
)
// BitArray is a thread-safe implementation of a bit array.
type BitArray struct {
mtx sync.Mutex
Bits int `json:"bits"` // NOTE: persisted via reflect, must be exported
Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported
}
// NewBitArray returns a new bit array.
// It returns nil if the number of bits is zero.
func NewBitArray(bits int) *BitArray {
if bits <= 0 {
return nil
}
return &BitArray{
Bits: bits,
Elems: make([]uint64, (bits+63)/64),
}
}
// NewBitArrayFromFn returns a new bit array.
// It returns nil if the number of bits is zero.
// It initializes the `i`th bit to the value of `fn(i)`.
func NewBitArrayFromFn(bits int, fn func(int) bool) *BitArray {
if bits <= 0 {
return nil
}
bA := &BitArray{
Bits: bits,
Elems: make([]uint64, (bits+63)/64),
}
for i := 0; i < bits; i++ {
v := fn(i)
if v {
bA.Elems[i/64] |= (uint64(1) << uint(i%64))
}
}
return bA
}
// Size returns the number of bits in the bitarray.
func (bA *BitArray) Size() int {
if bA == nil {
return 0
}
return bA.Bits
}
// GetIndex returns the bit at index i within the bit array.
// The behavior is undefined if i >= bA.Bits
func (bA *BitArray) GetIndex(i int) bool {
if bA == nil {
return false
}
bA.mtx.Lock()
defer bA.mtx.Unlock()
return bA.getIndex(i)
}
func (bA *BitArray) getIndex(i int) bool {
if i >= bA.Bits {
return false
}
return bA.Elems[i/64]&(uint64(1)<<uint(i%64)) > 0
}
// SetIndex sets the bit at index i within the bit array.
// The behavior is undefined if i >= bA.Bits
func (bA *BitArray) SetIndex(i int, v bool) bool {
if bA == nil {
return false
}
bA.mtx.Lock()
defer bA.mtx.Unlock()
return bA.setIndex(i, v)
}
func (bA *BitArray) setIndex(i int, v bool) bool {
if i >= bA.Bits {
return false
}
if v {
bA.Elems[i/64] |= (uint64(1) << uint(i%64))
} else {
bA.Elems[i/64] &= ^(uint64(1) << uint(i%64))
}
return true
}
// Copy returns a copy of the provided bit array.
func (bA *BitArray) Copy() *BitArray {
if bA == nil {
return nil
}
bA.mtx.Lock()
defer bA.mtx.Unlock()
return bA.copy()
}
func (bA *BitArray) copy() *BitArray {
c := make([]uint64, len(bA.Elems))
copy(c, bA.Elems)
return &BitArray{
Bits: bA.Bits,
Elems: c,
}
}
func (bA *BitArray) copyBits(bits int) *BitArray {
c := make([]uint64, (bits+63)/64)
copy(c, bA.Elems)
return &BitArray{
Bits: bits,
Elems: c,
}
}
// Or returns a bit array resulting from a bitwise OR of the two bit arrays.
// If the two bit-arrys have different lengths, Or right-pads the smaller of the two bit-arrays with zeroes.
// Thus the size of the return value is the maximum of the two provided bit arrays.
func (bA *BitArray) Or(o *BitArray) *BitArray {
if bA == nil && o == nil {
return nil
}
if bA == nil && o != nil {
return o.Copy()
}
if o == nil {
return bA.Copy()
}
bA.mtx.Lock()
o.mtx.Lock()
c := bA.copyBits(cmtmath.MaxInt(bA.Bits, o.Bits))
smaller := cmtmath.MinInt(len(bA.Elems), len(o.Elems))
for i := 0; i < smaller; i++ {
c.Elems[i] |= o.Elems[i]
}
bA.mtx.Unlock()
o.mtx.Unlock()
return c
}
// And returns a bit array resulting from a bitwise AND of the two bit arrays.
// If the two bit-arrys have different lengths, this truncates the larger of the two bit-arrays from the right.
// Thus the size of the return value is the minimum of the two provided bit arrays.
func (bA *BitArray) And(o *BitArray) *BitArray {
if bA == nil || o == nil {
return nil
}
bA.mtx.Lock()
o.mtx.Lock()
defer func() {
bA.mtx.Unlock()
o.mtx.Unlock()
}()
return bA.and(o)
}
func (bA *BitArray) and(o *BitArray) *BitArray {
c := bA.copyBits(cmtmath.MinInt(bA.Bits, o.Bits))
for i := 0; i < len(c.Elems); i++ {
c.Elems[i] &= o.Elems[i]
}
return c
}
// Not returns a bit array resulting from a bitwise Not of the provided bit array.
func (bA *BitArray) Not() *BitArray {
if bA == nil {
return nil // Degenerate
}
bA.mtx.Lock()
defer bA.mtx.Unlock()
return bA.not()
}
func (bA *BitArray) not() *BitArray {
c := bA.copy()
for i := 0; i < len(c.Elems); i++ {
c.Elems[i] = ^c.Elems[i]
}
return c
}
// Sub subtracts the two bit-arrays bitwise, without carrying the bits.
// Note that carryless subtraction of a - b is (a and not b).
// The output is the same as bA, regardless of o's size.
// If bA is longer than o, o is right padded with zeroes
func (bA *BitArray) Sub(o *BitArray) *BitArray {
if bA == nil || o == nil {
// TODO: Decide if we should do 1's complement here?
return nil
}
bA.mtx.Lock()
o.mtx.Lock()
// output is the same size as bA
c := bA.copyBits(bA.Bits)
// Only iterate to the minimum size between the two.
// If o is longer, those bits are ignored.
// If bA is longer, then skipping those iterations is equivalent
// to right padding with 0's
smaller := cmtmath.MinInt(len(bA.Elems), len(o.Elems))
for i := 0; i < smaller; i++ {
// &^ is and not in golang
c.Elems[i] &^= o.Elems[i]
}
bA.mtx.Unlock()
o.mtx.Unlock()
return c
}
// IsEmpty returns true iff all bits in the bit array are 0
func (bA *BitArray) IsEmpty() bool {
if bA == nil {
return true // should this be opposite?
}
bA.mtx.Lock()
defer bA.mtx.Unlock()
for _, e := range bA.Elems {
if e > 0 {
return false
}
}
return true
}
// IsFull returns true iff all bits in the bit array are 1.
func (bA *BitArray) IsFull() bool {
if bA == nil {
return true
}
bA.mtx.Lock()
defer bA.mtx.Unlock()
// Check all elements except the last
for _, elem := range bA.Elems[:len(bA.Elems)-1] {
if (^elem) != 0 {
return false
}
}
// Check that the last element has (lastElemBits) 1's
lastElemBits := (bA.Bits+63)%64 + 1
lastElem := bA.Elems[len(bA.Elems)-1]
return (lastElem+1)&((uint64(1)<<uint(lastElemBits))-1) == 0
}
// PickRandom returns a random index for a set bit in the bit array.
// If there is no such value, it returns 0, false.
// It uses the global randomness in `random.go` to get this index.
func (bA *BitArray) PickRandom() (int, bool) {
if bA == nil {
return 0, false
}
bA.mtx.Lock()
numTrueIndices := bA.getNumTrueIndices()
if numTrueIndices == 0 { // no bits set to true
bA.mtx.Unlock()
return 0, false
}
index := bA.getNthTrueIndex(cmtrand.Intn(numTrueIndices))
bA.mtx.Unlock()
if index == -1 {
return 0, false
}
return index, true
}
func (bA *BitArray) getNumTrueIndices() int {
count := 0
numElems := len(bA.Elems)
// handle all elements except the last one
for i := 0; i < numElems-1; i++ {
count += bits.OnesCount64(bA.Elems[i])
}
// handle last element
numFinalBits := bA.Bits - (numElems-1)*64
for i := 0; i < numFinalBits; i++ {
if (bA.Elems[numElems-1] & (uint64(1) << uint64(i))) > 0 {
count++
}
}
return count
}
// getNthTrueIndex returns the index of the nth true bit in the bit array.
// n is 0 indexed. (e.g. for bitarray x__x, getNthTrueIndex(0) returns 0).
// If there is no such value, it returns -1.
func (bA *BitArray) getNthTrueIndex(n int) int {
numElems := len(bA.Elems)
count := 0
// Iterate over each element
for i := 0; i < numElems; i++ {
// Count set bits in the current element
setBits := bits.OnesCount64(bA.Elems[i])
// If the count of set bits in this element plus the count so far
// is greater than or equal to n, then the nth bit must be in this element
if count+setBits >= n {
// Find the index of the nth set bit within this element
for j := 0; j < 64; j++ {
if bA.Elems[i]&(1<<uint(j)) != 0 {
if count == n {
// Calculate the absolute index of the set bit
return i*64 + j
}
count++
}
}
} else {
// If the count is not enough, continue to the next element
count += setBits
}
}
// If we reach here, it means n is out of range
return -1
}
// String returns a string representation of BitArray: BA{<bit-string>},
// where <bit-string> is a sequence of 'x' (1) and '_' (0).
// The <bit-string> includes spaces and newlines to help people.
// For a simple sequence of 'x' and '_' characters with no spaces or newlines,
// see the MarshalJSON() method.
// Example: "BA{_x_}" or "nil-BitArray" for nil.
func (bA *BitArray) String() string {
return bA.StringIndented("")
}
// StringIndented returns the same thing as String(), but applies the indent
// at every 10th bit, and twice at every 50th bit.
func (bA *BitArray) StringIndented(indent string) string {
if bA == nil {
return "nil-BitArray"
}
bA.mtx.Lock()
defer bA.mtx.Unlock()
return bA.stringIndented(indent)
}
func (bA *BitArray) stringIndented(indent string) string {
lines := []string{}
bits := ""
for i := 0; i < bA.Bits; i++ {
if bA.getIndex(i) {
bits += "x"
} else {
bits += "_"
}
if i%100 == 99 {
lines = append(lines, bits)
bits = ""
}
if i%10 == 9 {
bits += indent
}
if i%50 == 49 {
bits += indent
}
}
if len(bits) > 0 {
lines = append(lines, bits)
}
return fmt.Sprintf("BA{%v:%v}", bA.Bits, strings.Join(lines, indent))
}
// Bytes returns the byte representation of the bits within the bitarray.
func (bA *BitArray) Bytes() []byte {
bA.mtx.Lock()
defer bA.mtx.Unlock()
numBytes := (bA.Bits + 7) / 8
bytes := make([]byte, numBytes)
for i := 0; i < len(bA.Elems); i++ {
elemBytes := [8]byte{}
binary.LittleEndian.PutUint64(elemBytes[:], bA.Elems[i])
copy(bytes[i*8:], elemBytes[:])
}
return bytes
}
// Update sets the bA's bits to be that of the other bit array.
// The copying begins from the begin of both bit arrays.
func (bA *BitArray) Update(o *BitArray) {
if bA == nil || o == nil {
return
}
bA.mtx.Lock()
o.mtx.Lock()
copy(bA.Elems, o.Elems)
o.mtx.Unlock()
bA.mtx.Unlock()
}
// MarshalJSON implements json.Marshaler interface by marshaling bit array
// using a custom format: a string of '-' or 'x' where 'x' denotes the 1 bit.
func (bA *BitArray) MarshalJSON() ([]byte, error) {
if bA == nil {
return []byte("null"), nil
}
bA.mtx.Lock()
defer bA.mtx.Unlock()
bits := `"`
for i := 0; i < bA.Bits; i++ {
if bA.getIndex(i) {
bits += `x`
} else {
bits += `_`
}
}
bits += `"`
return []byte(bits), nil
}
var bitArrayJSONRegexp = regexp.MustCompile(`\A"([_x]*)"\z`)
// UnmarshalJSON implements json.Unmarshaler interface by unmarshaling a custom
// JSON description.
func (bA *BitArray) UnmarshalJSON(bz []byte) error {
b := string(bz)
if b == "null" {
// This is required e.g. for encoding/json when decoding
// into a pointer with pre-allocated BitArray.
bA.Bits = 0
bA.Elems = nil
return nil
}
// Validate 'b'.
match := bitArrayJSONRegexp.FindStringSubmatch(b)
if match == nil {
return fmt.Errorf("bitArray in JSON should be a string of format %q but got %s", bitArrayJSONRegexp.String(), b)
}
bits := match[1]
// Construct new BitArray and copy over.
numBits := len(bits)
bA2 := NewBitArray(numBits)
if bA2 == nil {
// Treat it as if we encountered the case: b == "null"
bA.Bits = 0
bA.Elems = nil
return nil
}
for i := 0; i < numBits; i++ {
if bits[i] == 'x' {
bA2.SetIndex(i, true)
}
}
*bA = *bA2 //nolint:govet
return nil
}
// ToProto converts BitArray to protobuf
func (bA *BitArray) ToProto() *cmtprotobits.BitArray {
if bA == nil || len(bA.Elems) == 0 {
return nil
}
return &cmtprotobits.BitArray{
Bits: int64(bA.Bits),
Elems: bA.Elems,
}
}
// FromProto sets a protobuf BitArray to the given pointer.
func (bA *BitArray) FromProto(protoBitArray *cmtprotobits.BitArray) {
if protoBitArray == nil {
bA = nil
return
}
bA.Bits = int(protoBitArray.Bits)
if len(protoBitArray.Elems) > 0 {
bA.Elems = protoBitArray.Elems
}
}
package json
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"strconv"
"time"
)
var (
timeType = reflect.TypeOf(time.Time{})
jsonMarshalerType = reflect.TypeOf(new(json.Marshaler)).Elem()
jsonUnmarshalerType = reflect.TypeOf(new(json.Unmarshaler)).Elem()
)
// Marshal marshals the value as JSON, using Amino-compatible JSON encoding (strings for
// 64-bit numbers, and type wrappers for registered types).
func Marshal(v interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
err := encode(buf, v)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// MarshalIndent marshals the value as JSON, using the given prefix and indentation.
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
bz, err := Marshal(v)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
err = json.Indent(buf, bz, prefix, indent)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func encode(w *bytes.Buffer, v any) error {
// Bare nil values can't be reflected, so we must handle them here.
if v == nil {
return writeStr(w, "null")
}
rv := reflect.ValueOf(v)
// If this is a registered type, defer to interface encoder regardless of whether the input is
// an interface or a bare value. This retains Amino's behavior, but is inconsistent with
// behavior in structs where an interface field will get the type wrapper while a bare value
// field will not.
if typeRegistry.name(rv.Type()) != "" {
return encodeReflectInterface(w, rv)
}
return encodeReflect(w, rv)
}
func encodeReflect(w *bytes.Buffer, rv reflect.Value) error {
if !rv.IsValid() {
return errors.New("invalid reflect value")
}
// Recursively dereference if pointer.
for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return writeStr(w, "null")
}
rv = rv.Elem()
}
// Convert times to UTC.
if rv.Type() == timeType {
rv = reflect.ValueOf(rv.Interface().(time.Time).Round(0).UTC())
}
// If the value implements json.Marshaler, defer to stdlib directly. Since we've already
// dereferenced, we try implementations with both value receiver and pointer receiver. We must
// do this after the time normalization above, and thus after dereferencing.
if rv.Type().Implements(jsonMarshalerType) {
return encodeStdlib(w, rv.Interface())
} else if rv.CanAddr() && rv.Addr().Type().Implements(jsonMarshalerType) {
return encodeStdlib(w, rv.Addr().Interface())
}
switch rv.Type().Kind() {
// Complex types must be recursively encoded.
case reflect.Interface:
return encodeReflectInterface(w, rv)
case reflect.Array, reflect.Slice:
return encodeReflectList(w, rv)
case reflect.Map:
return encodeReflectMap(w, rv)
case reflect.Struct:
return encodeReflectStruct(w, rv)
// 64-bit integers are emitted as strings, to avoid precision problems with e.g.
// Javascript which uses 64-bit floats (having 53-bit precision).
case reflect.Int64, reflect.Int:
return writeStr(w, `"`+strconv.FormatInt(rv.Int(), 10)+`"`)
case reflect.Uint64, reflect.Uint:
return writeStr(w, `"`+strconv.FormatUint(rv.Uint(), 10)+`"`)
// For everything else, defer to the stdlib encoding/json encoder
default:
return encodeStdlib(w, rv.Interface())
}
}
func encodeReflectList(w *bytes.Buffer, rv reflect.Value) error {
// Emit nil slices as null.
if rv.Kind() == reflect.Slice && rv.IsNil() {
return writeStr(w, "null")
}
// Encode byte slices as base64 with the stdlib encoder.
if rv.Type().Elem().Kind() == reflect.Uint8 {
// Stdlib does not base64-encode byte arrays, only slices, so we copy to slice.
if rv.Type().Kind() == reflect.Array {
slice := reflect.MakeSlice(reflect.SliceOf(rv.Type().Elem()), rv.Len(), rv.Len())
reflect.Copy(slice, rv)
rv = slice
}
return encodeStdlib(w, rv.Interface())
}
// Anything else we recursively encode ourselves.
length := rv.Len()
if err := writeStr(w, "["); err != nil {
return err
}
for i := 0; i < length; i++ {
if err := encodeReflect(w, rv.Index(i)); err != nil {
return err
}
if i < length-1 {
if err := writeStr(w, ","); err != nil {
return err
}
}
}
return writeStr(w, "]")
}
func encodeReflectMap(w *bytes.Buffer, rv reflect.Value) error {
if rv.Type().Key().Kind() != reflect.String {
return errors.New("map key must be string")
}
// nil maps are not emitted as nil, to retain Amino compatibility.
if err := writeStr(w, "{"); err != nil {
return err
}
writeComma := false
for _, keyrv := range rv.MapKeys() {
if writeComma {
if err := writeStr(w, ","); err != nil {
return err
}
}
if err := encodeStdlib(w, keyrv.Interface()); err != nil {
return err
}
if err := writeStr(w, ":"); err != nil {
return err
}
if err := encodeReflect(w, rv.MapIndex(keyrv)); err != nil {
return err
}
writeComma = true
}
return writeStr(w, "}")
}
func encodeReflectStruct(w *bytes.Buffer, rv reflect.Value) error {
sInfo := makeStructInfo(rv.Type())
if err := writeStr(w, "{"); err != nil {
return err
}
writeComma := false
for i, fInfo := range sInfo.fields {
frv := rv.Field(i)
if fInfo.hidden || (fInfo.omitEmpty && frv.IsZero()) {
continue
}
if writeComma {
if err := writeStr(w, ","); err != nil {
return err
}
}
if err := encodeStdlib(w, fInfo.jsonName); err != nil {
return err
}
if err := writeStr(w, ":"); err != nil {
return err
}
if err := encodeReflect(w, frv); err != nil {
return err
}
writeComma = true
}
return writeStr(w, "}")
}
func encodeReflectInterface(w *bytes.Buffer, rv reflect.Value) error {
// Get concrete value and dereference pointers.
for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
if rv.IsNil() {
return writeStr(w, "null")
}
rv = rv.Elem()
}
// Look up the name of the concrete type
name := typeRegistry.name(rv.Type())
if name == "" {
return fmt.Errorf("cannot encode unregistered type %v", rv.Type())
}
// Write value wrapped in interface envelope
if err := writeStr(w, fmt.Sprintf(`{"type":%q,"value":`, name)); err != nil {
return err
}
if err := encodeReflect(w, rv); err != nil {
return err
}
return writeStr(w, "}")
}
func encodeStdlib(w *bytes.Buffer, v any) error {
// Stream the output of the JSON marshaling directly into the buffer.
// The stdlib encoder will write a newline, so we must truncate it,
// which is why we pass in a bytes.Buffer throughout, not io.Writer.
enc := json.NewEncoder(w)
err := enc.Encode(v)
if err != nil {
return err
}
// Remove the last byte from the buffer
w.Truncate(w.Len() - 1)
return err
}
func writeStr(w io.Writer, s string) error {
_, err := w.Write([]byte(s))
return err
}
package mempool
import (
"bytes"
"context"
"fmt"
"sync"
"sync/atomic"
"time"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/libs/clist"
"github.com/cometbft/cometbft/libs/log"
cmtmath "github.com/cometbft/cometbft/libs/math"
cmtsync "github.com/cometbft/cometbft/libs/sync"
"github.com/cometbft/cometbft/proxy"
"github.com/cometbft/cometbft/types"
)
// CListMempool is an ordered in-memory pool for transactions before they are
// proposed in a consensus round. Transaction validity is checked using the
// CheckTx abci message before the transaction is added to the pool. The
// mempool uses a concurrent list structure for storing transactions that can
// be efficiently accessed by multiple concurrent readers.
type CListMempool struct {
height atomic.Int64 // the last block Update()'d to
txsBytes atomic.Int64 // total size of mempool, in bytes
// notify listeners (ie. consensus) when txs are available
notifiedTxsAvailable atomic.Bool
txsAvailable chan struct{} // fires once for each height, when the mempool is not empty
config *config.MempoolConfig
// Exclusive mutex for Update method to prevent concurrent execution of
// CheckTx or ReapMaxBytesMaxGas(ReapMaxTxs) methods.
updateMtx cmtsync.RWMutex
preCheck PreCheckFunc
postCheck PostCheckFunc
txs *clist.CList // concurrent linked-list of good txs
proxyAppConn proxy.AppConnMempool
// Keeps track of the rechecking process.
recheck *recheck
// Map for quick access to txs to record sender in CheckTx.
// txsMap: txKey -> CElement
txsMap sync.Map
// Keep a cache of already-seen txs.
// This reduces the pressure on the proxyApp.
cache TxCache
logger log.Logger
metrics *Metrics
}
var _ Mempool = &CListMempool{}
// CListMempoolOption sets an optional parameter on the mempool.
type CListMempoolOption func(*CListMempool)
// NewCListMempool returns a new mempool with the given configuration and
// connection to an application.
func NewCListMempool(
cfg *config.MempoolConfig,
proxyAppConn proxy.AppConnMempool,
height int64,
options ...CListMempoolOption,
) *CListMempool {
mp := &CListMempool{
config: cfg,
proxyAppConn: proxyAppConn,
txs: clist.New(),
recheck: newRecheck(),
logger: log.NewNopLogger(),
metrics: NopMetrics(),
}
mp.height.Store(height)
if cfg.CacheSize > 0 {
mp.cache = NewLRUTxCache(cfg.CacheSize)
} else {
mp.cache = NopTxCache{}
}
proxyAppConn.SetResponseCallback(mp.globalCb)
for _, option := range options {
option(mp)
}
return mp
}
func (mem *CListMempool) getCElement(txKey types.TxKey) (*clist.CElement, bool) {
if e, ok := mem.txsMap.Load(txKey); ok {
return e.(*clist.CElement), true
}
return nil, false
}
func (mem *CListMempool) getMemTx(txKey types.TxKey) *mempoolTx {
if e, ok := mem.getCElement(txKey); ok {
return e.Value.(*mempoolTx)
}
return nil
}
func (mem *CListMempool) removeAllTxs() {
for e := mem.txs.Front(); e != nil; e = e.Next() {
mem.txs.Remove(e)
e.DetachPrev()
}
mem.txsMap.Range(func(key, _ interface{}) bool {
mem.txsMap.Delete(key)
return true
})
}
// NOTE: not thread safe - should only be called once, on startup
func (mem *CListMempool) EnableTxsAvailable() {
mem.txsAvailable = make(chan struct{}, 1)
}
// SetLogger sets the Logger.
func (mem *CListMempool) SetLogger(l log.Logger) {
mem.logger = l
}
// WithPreCheck sets a filter for the mempool to reject a tx if f(tx) returns
// false. This is ran before CheckTx. Only applies to the first created block.
// After that, Update overwrites the existing value.
func WithPreCheck(f PreCheckFunc) CListMempoolOption {
return func(mem *CListMempool) { mem.preCheck = f }
}
// WithPostCheck sets a filter for the mempool to reject a tx if f(tx) returns
// false. This is ran after CheckTx. Only applies to the first created block.
// After that, Update overwrites the existing value.
func WithPostCheck(f PostCheckFunc) CListMempoolOption {
return func(mem *CListMempool) { mem.postCheck = f }
}
// WithMetrics sets the metrics.
func WithMetrics(metrics *Metrics) CListMempoolOption {
return func(mem *CListMempool) { mem.metrics = metrics }
}
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) Lock() {
if mem.recheck.setRecheckFull() {
mem.logger.Debug("the state of recheckFull has flipped")
}
mem.updateMtx.Lock()
}
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) Unlock() {
mem.updateMtx.Unlock()
}
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) Size() int {
return mem.txs.Len()
}
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) SizeBytes() int64 {
return mem.txsBytes.Load()
}
// Lock() must be help by the caller during execution.
func (mem *CListMempool) FlushAppConn() error {
err := mem.proxyAppConn.Flush(context.TODO())
if err != nil {
return ErrFlushAppConn{Err: err}
}
return nil
}
// XXX: Unsafe! Calling Flush may leave mempool in inconsistent state.
func (mem *CListMempool) Flush() {
mem.updateMtx.RLock()
defer mem.updateMtx.RUnlock()
mem.txsBytes.Store(0)
mem.cache.Reset()
mem.removeAllTxs()
}
// TxsFront returns the first transaction in the ordered list for peer
// goroutines to call .NextWait() on.
// FIXME: leaking implementation details!
//
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) TxsFront() *clist.CElement {
return mem.txs.Front()
}
// TxsWaitChan returns a channel to wait on transactions. It will be closed
// once the mempool is not empty (ie. the internal `mem.txs` has at least one
// element)
//
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) TxsWaitChan() <-chan struct{} {
return mem.txs.WaitChan()
}
// It blocks if we're waiting on Update() or Reap().
// cb: A callback from the CheckTx command.
//
// It gets called from another goroutine.
//
// CONTRACT: Either cb will get called, or err returned.
//
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) CheckTx(
tx types.Tx,
cb func(*abci.ResponseCheckTx),
txInfo TxInfo,
) error {
mem.updateMtx.RLock()
// use defer to unlock mutex because application (*local client*) might panic
defer mem.updateMtx.RUnlock()
txSize := len(tx)
if err := mem.isFull(txSize); err != nil {
mem.metrics.RejectedTxs.Add(1)
return err
}
if txSize > mem.config.MaxTxBytes {
return ErrTxTooLarge{
Max: mem.config.MaxTxBytes,
Actual: txSize,
}
}
if mem.preCheck != nil {
if err := mem.preCheck(tx); err != nil {
return ErrPreCheck{Err: err}
}
}
// NOTE: proxyAppConn may error if tx buffer is full
if err := mem.proxyAppConn.Error(); err != nil {
return ErrAppConnMempool{Err: err}
}
if !mem.cache.Push(tx) { // if the transaction already exists in the cache
// Record a new sender for a tx we've already seen.
// Note it's possible a tx is still in the cache but no longer in the mempool
// (eg. after committing a block, txs are removed from mempool but not cache),
// so we only record the sender for txs still in the mempool.
if memTx := mem.getMemTx(tx.Key()); memTx != nil {
memTx.addSender(txInfo.SenderID)
// TODO: consider punishing peer for dups,
// its non-trivial since invalid txs can become valid,
// but they can spam the same tx with little cost to them atm.
}
return ErrTxInCache
}
reqRes, err := mem.proxyAppConn.CheckTxAsync(context.TODO(), &abci.RequestCheckTx{Tx: tx})
if err != nil {
panic(fmt.Errorf("CheckTx request for tx %s failed: %w", log.NewLazySprintf("%v", tx.Hash()), err))
}
reqRes.SetCallback(mem.reqResCb(tx, txInfo, cb))
return nil
}
// Global callback that will be called after every ABCI response.
// Having a single global callback avoids needing to set a callback for each request.
// However, processing the checkTx response requires the peerID (so we can track which txs we heard from who),
// and peerID is not included in the ABCI request, so we have to set request-specific callbacks that
// include this information. If we're not in the midst of a recheck, this function will just return,
// so the request specific callback can do the work.
//
// When rechecking, we don't need the peerID, so the recheck callback happens
// here.
func (mem *CListMempool) globalCb(req *abci.Request, res *abci.Response) {
switch r := req.Value.(type) {
case *abci.Request_CheckTx:
// Process only Recheck responses.
if r.CheckTx.Type != abci.CheckTxType_Recheck {
return
}
default:
// ignore other type of requests
return
}
switch r := res.Value.(type) {
case *abci.Response_CheckTx:
tx := types.Tx(req.GetCheckTx().Tx)
if mem.recheck.done() {
mem.logger.Error("rechecking has finished; discard late recheck response",
"tx", log.NewLazySprintf("%v", tx.Key()))
return
}
mem.metrics.RecheckTimes.Add(1)
mem.resCbRecheck(tx, r.CheckTx)
// update metrics
mem.metrics.Size.Set(float64(mem.Size()))
default:
// ignore other messages
}
}
// Request specific callback that should be set on individual reqRes objects
// to incorporate local information when processing the response.
// This allows us to track the peer that sent us this tx, so we can avoid sending it back to them.
// NOTE: alternatively, we could include this information in the ABCI request itself.
//
// External callers of CheckTx, like the RPC, can also pass an externalCb through here that is called
// when all other response processing is complete.
//
// Used in CheckTx to record PeerID who sent us the tx.
func (mem *CListMempool) reqResCb(
tx []byte,
txInfo TxInfo,
externalCb func(*abci.ResponseCheckTx),
) func(res *abci.Response) {
return func(res *abci.Response) {
if !mem.recheck.done() {
panic(log.NewLazySprintf("rechecking has not finished; cannot check new tx %v",
types.Tx(tx).Hash()))
}
mem.resCbFirstTime(tx, txInfo, res)
// update metrics
mem.metrics.Size.Set(float64(mem.Size()))
mem.metrics.SizeBytes.Set(float64(mem.SizeBytes()))
// passed in by the caller of CheckTx, eg. the RPC
if externalCb != nil {
externalCb(res.GetCheckTx())
}
}
}
// Called from:
// - resCbFirstTime (lock not held) if tx is valid
func (mem *CListMempool) addTx(memTx *mempoolTx) {
e := mem.txs.PushBack(memTx)
mem.txsMap.Store(memTx.tx.Key(), e)
mem.txsBytes.Add(int64(len(memTx.tx)))
mem.metrics.TxSizeBytes.Observe(float64(len(memTx.tx)))
}
// RemoveTxByKey removes a transaction from the mempool by its TxKey index.
// Called from:
// - Update (lock held) if tx was committed
// - resCbRecheck (lock not held) if tx was invalidated
func (mem *CListMempool) RemoveTxByKey(txKey types.TxKey) error {
if elem, ok := mem.getCElement(txKey); ok {
mem.txs.Remove(elem)
elem.DetachPrev()
mem.txsMap.Delete(txKey)
tx := elem.Value.(*mempoolTx).tx
mem.txsBytes.Add(int64(-len(tx)))
return nil
}
return ErrTxNotFound
}
func (mem *CListMempool) isFull(txSize int) error {
memSize := mem.Size()
txsBytes := mem.SizeBytes()
if memSize >= mem.config.Size || int64(txSize)+txsBytes > mem.config.MaxTxsBytes {
return ErrMempoolIsFull{
NumTxs: memSize,
MaxTxs: mem.config.Size,
TxsBytes: txsBytes,
MaxTxsBytes: mem.config.MaxTxsBytes,
}
}
if mem.recheck.consideredFull() {
return ErrRecheckFull
}
return nil
}
// callback, which is called after the app checked the tx for the first time.
//
// The case where the app checks the tx for the second and subsequent times is
// handled by the resCbRecheck callback.
func (mem *CListMempool) resCbFirstTime(
tx []byte,
txInfo TxInfo,
res *abci.Response,
) {
switch r := res.Value.(type) {
case *abci.Response_CheckTx:
var postCheckErr error
if mem.postCheck != nil {
postCheckErr = mem.postCheck(tx, r.CheckTx)
}
if (r.CheckTx.Code == abci.CodeTypeOK) && postCheckErr == nil {
// Check mempool isn't full again to reduce the chance of exceeding the
// limits.
if err := mem.isFull(len(tx)); err != nil {
// remove from cache (mempool might have a space later)
mem.cache.Remove(tx)
// use debug level to avoid spamming logs when traffic is high
mem.logger.Debug(err.Error())
mem.metrics.RejectedTxs.Add(1)
return
}
// Check transaction not already in the mempool
if e, ok := mem.txsMap.Load(types.Tx(tx).Key()); ok {
memTx := e.(*clist.CElement).Value.(*mempoolTx)
memTx.addSender(txInfo.SenderID)
mem.logger.Debug(
"transaction already there, not adding it again",
"tx", types.Tx(tx).Hash(),
"res", r,
"height", mem.height.Load(),
"total", mem.Size(),
)
mem.metrics.RejectedTxs.Add(1)
return
}
memTx := &mempoolTx{
height: mem.height.Load(),
gasWanted: r.CheckTx.GasWanted,
tx: tx,
}
memTx.addSender(txInfo.SenderID)
mem.addTx(memTx)
mem.logger.Debug(
"added good transaction",
"tx", types.Tx(tx).Hash(),
"res", r,
"height", mem.height.Load(),
"total", mem.Size(),
)
mem.notifyTxsAvailable()
} else {
// ignore bad transaction
mem.logger.Debug(
"rejected bad transaction",
"tx", types.Tx(tx).Hash(),
"peerID", txInfo.SenderP2PID,
"res", r,
"err", postCheckErr,
)
mem.metrics.FailedTxs.Add(1)
if !mem.config.KeepInvalidTxsInCache {
// remove from cache (it might be good later)
mem.cache.Remove(tx)
}
}
default:
// ignore other messages
}
}
// callback, which is called after the app rechecked the tx.
//
// The case where the app checks the tx for the first time is handled by the
// resCbFirstTime callback.
func (mem *CListMempool) resCbRecheck(tx types.Tx, res *abci.ResponseCheckTx) {
// Check whether tx is still in the list of transactions that can be rechecked.
if !mem.recheck.findNextEntryMatching(&tx) {
// Reached the end of the list and didn't find a matching tx; rechecking has finished.
return
}
var postCheckErr error
if mem.postCheck != nil {
postCheckErr = mem.postCheck(tx, res)
}
if (res.Code != abci.CodeTypeOK) || postCheckErr != nil {
// Tx became invalidated due to newly committed block.
mem.logger.Debug("tx is no longer valid", "tx", tx.Hash(), "res", res, "postCheckErr", postCheckErr)
if err := mem.RemoveTxByKey(tx.Key()); err != nil {
mem.logger.Debug("Transaction could not be removed from mempool", "err", err)
}
if !mem.config.KeepInvalidTxsInCache {
mem.cache.Remove(tx)
mem.metrics.EvictedTxs.Add(1)
}
}
}
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) TxsAvailable() <-chan struct{} {
return mem.txsAvailable
}
func (mem *CListMempool) notifyTxsAvailable() {
if mem.Size() == 0 {
panic("notified txs available but mempool is empty!")
}
if mem.txsAvailable != nil && mem.notifiedTxsAvailable.CompareAndSwap(false, true) {
// channel cap is 1, so this will send once
select {
case mem.txsAvailable <- struct{}{}:
default:
}
}
}
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs {
mem.updateMtx.RLock()
defer mem.updateMtx.RUnlock()
var (
totalGas int64
runningSize int64
)
// TODO: we will get a performance boost if we have a good estimate of avg
// size per tx, and set the initial capacity based off of that.
// txs := make([]types.Tx, 0, cmtmath.MinInt(mem.txs.Len(), max/mem.avgTxSize))
txs := make([]types.Tx, 0, mem.txs.Len())
for e := mem.txs.Front(); e != nil; e = e.Next() {
memTx := e.Value.(*mempoolTx)
txs = append(txs, memTx.tx)
dataSize := types.ComputeProtoSizeForTxs([]types.Tx{memTx.tx})
// Check total size requirement
if maxBytes > -1 && runningSize+dataSize > maxBytes {
return txs[:len(txs)-1]
}
runningSize += dataSize
// Check total gas requirement.
// If maxGas is negative, skip this check.
// Since newTotalGas < masGas, which
// must be non-negative, it follows that this won't overflow.
newTotalGas := totalGas + memTx.gasWanted
if maxGas > -1 && newTotalGas > maxGas {
return txs[:len(txs)-1]
}
totalGas = newTotalGas
}
return txs
}
// Safe for concurrent use by multiple goroutines.
func (mem *CListMempool) ReapMaxTxs(max int) types.Txs {
mem.updateMtx.RLock()
defer mem.updateMtx.RUnlock()
if max < 0 {
max = mem.txs.Len()
}
txs := make([]types.Tx, 0, cmtmath.MinInt(mem.txs.Len(), max))
for e := mem.txs.Front(); e != nil && len(txs) <= max; e = e.Next() {
memTx := e.Value.(*mempoolTx)
txs = append(txs, memTx.tx)
}
return txs
}
// Lock() must be help by the caller during execution.
func (mem *CListMempool) Update(
height int64,
txs types.Txs,
txResults []*abci.ExecTxResult,
preCheck PreCheckFunc,
postCheck PostCheckFunc,
) error {
mem.logger.Debug("Update", "height", height, "len(txs)", len(txs))
// Set height
mem.height.Store(height)
mem.notifiedTxsAvailable.Store(false)
if preCheck != nil {
mem.preCheck = preCheck
}
if postCheck != nil {
mem.postCheck = postCheck
}
for i, tx := range txs {
if txResults[i].Code == abci.CodeTypeOK {
// Add valid committed tx to the cache (if missing).
_ = mem.cache.Push(tx)
} else if !mem.config.KeepInvalidTxsInCache {
// Allow invalid transactions to be resubmitted.
mem.cache.Remove(tx)
}
// Remove committed tx from the mempool.
//
// Note an evil proposer can drop valid txs!
// Mempool before:
// 100 -> 101 -> 102
// Block, proposed by an evil proposer:
// 101 -> 102
// Mempool after:
// 100
// https://github.com/tendermint/tendermint/issues/3322.
if err := mem.RemoveTxByKey(tx.Key()); err != nil {
mem.logger.Debug("Committed transaction not in local mempool (not an error)",
"key", tx.Key(),
"error", err.Error())
}
}
// Recheck txs left in the mempool to remove them if they became invalid in the new state.
if mem.config.Recheck {
mem.recheckTxs()
}
// Notify if there are still txs left in the mempool.
if mem.Size() > 0 {
mem.notifyTxsAvailable()
}
// Update metrics
mem.metrics.Size.Set(float64(mem.Size()))
mem.metrics.SizeBytes.Set(float64(mem.SizeBytes()))
return nil
}
// recheckTxs sends all transactions in the mempool to the app for re-validation. When the function
// returns, all recheck responses from the app have been processed.
func (mem *CListMempool) recheckTxs() {
mem.logger.Debug("recheck txs", "height", mem.height.Load(), "num-txs", mem.Size())
if mem.Size() <= 0 {
return
}
mem.recheck.init(mem.txs.Front(), mem.txs.Back())
// NOTE: globalCb may be called concurrently, but CheckTx cannot be executed concurrently
// because this function has the lock (via Update and Lock).
for e := mem.txs.Front(); e != nil; e = e.Next() {
tx := e.Value.(*mempoolTx).tx
mem.recheck.numPendingTxs.Add(1)
// Send a CheckTx request to the app. If we're using a sync client, the resCbRecheck
// callback will be called right after receiving the response.
_, err := mem.proxyAppConn.CheckTxAsync(context.TODO(), &abci.RequestCheckTx{
Tx: tx,
Type: abci.CheckTxType_Recheck,
})
if err != nil {
panic(fmt.Errorf("(re-)CheckTx request for tx %s failed: %w", log.NewLazySprintf("%v", tx.Hash()), err))
}
}
// Flush any pending asynchronous recheck requests to process.
mem.proxyAppConn.Flush(context.TODO())
// Give some time to finish processing the responses; then finish the rechecking process, even
// if not all txs were rechecked.
select {
case <-time.After(mem.config.RecheckTimeout):
mem.recheck.setDone()
mem.logger.Error("timed out waiting for recheck responses")
case <-mem.recheck.doneRechecking():
}
if n := mem.recheck.numPendingTxs.Load(); n > 0 {
mem.logger.Error("not all txs were rechecked", "not-rechecked", n)
}
mem.logger.Debug("done rechecking txs", "height", mem.height.Load(), "num-txs", mem.Size())
}
// The cursor and end pointers define a dynamic list of transactions that could be rechecked. The
// end pointer is fixed. When a recheck response for a transaction is received, cursor will point to
// the entry in the mempool corresponding to that transaction, thus narrowing the list. Transactions
// corresponding to entries between the old and current positions of cursor will be ignored for
// rechecking. This is to guarantee that recheck responses are processed in the same sequential
// order as they appear in the mempool.
type recheck struct {
cursor *clist.CElement // next expected recheck response
end *clist.CElement // last entry in the mempool to recheck
doneCh chan struct{} // to signal that rechecking has finished successfully (for async app connections)
numPendingTxs atomic.Int32 // number of transactions still pending to recheck
isRechecking atomic.Bool // true iff the rechecking process has begun and is not yet finished
recheckFull atomic.Bool // whether rechecking TXs cannot be completed before a new block is decided
}
func newRecheck() *recheck {
return &recheck{
doneCh: make(chan struct{}, 1),
}
}
func (rc *recheck) init(first, last *clist.CElement) {
if !rc.done() {
panic("Having more than one rechecking process at a time is not possible.")
}
rc.cursor = first
rc.end = last
rc.numPendingTxs.Store(0)
rc.isRechecking.Store(true)
}
// done returns true when there is no recheck response to process.
// Safe for concurrent use by multiple goroutines.
func (rc *recheck) done() bool {
return !rc.isRechecking.Load()
}
// setDone registers that rechecking has finished.
func (rc *recheck) setDone() {
rc.cursor = nil
rc.recheckFull.Store(false)
rc.isRechecking.Store(false)
}
// setNextEntry sets cursor to the next entry in the list. If there is no next, cursor will be nil.
func (rc *recheck) setNextEntry() {
rc.cursor = rc.cursor.Next()
}
// tryFinish will check if the cursor is at the end of the list and notify the channel that
// rechecking has finished. It returns true iff it's done rechecking.
func (rc *recheck) tryFinish() bool {
if rc.cursor == rc.end {
// Reached end of the list without finding a matching tx.
rc.setDone()
}
if rc.done() {
// Notify that recheck has finished.
select {
case rc.doneCh <- struct{}{}:
default:
}
return true
}
return false
}
// findNextEntryMatching searches for the next transaction matching the given transaction, which
// corresponds to the recheck response to be processed next. Then it checks if it has reached the
// end of the list, so it can finish rechecking.
//
// The goal is to guarantee that transactions are rechecked in the order in which they are in the
// mempool. Transactions whose recheck response arrive late or don't arrive at all are skipped and
// not rechecked.
func (rc *recheck) findNextEntryMatching(tx *types.Tx) bool {
found := false
for ; !rc.done(); rc.setNextEntry() {
expectedTx := rc.cursor.Value.(*mempoolTx).tx
if bytes.Equal(*tx, expectedTx) {
// Found an entry in the list of txs to recheck that matches tx.
found = true
rc.numPendingTxs.Add(-1)
break
}
}
if !rc.tryFinish() {
// Not finished yet; set the cursor for processing the next recheck response.
rc.setNextEntry()
}
return found
}
// doneRechecking returns the channel used to signal that rechecking has finished.
func (rc *recheck) doneRechecking() <-chan struct{} {
return rc.doneCh
}
// setRecheckFull sets recheckFull to true if rechecking is still in progress. It returns true iff
// the value of recheckFull has changed.
func (rc *recheck) setRecheckFull() bool {
rechecking := !rc.done()
recheckFull := rc.recheckFull.Swap(rechecking)
return rechecking != recheckFull
}
// consideredFull returns true iff the mempool should be considered as full while rechecking is in
// progress.
func (rc *recheck) consideredFull() bool {
return rc.recheckFull.Load()
}
package mempool
import (
"context"
"errors"
"time"
"fmt"
cfg "github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/libs/clist"
"github.com/cometbft/cometbft/libs/log"
"github.com/cometbft/cometbft/p2p"
protomem "github.com/cometbft/cometbft/proto/tendermint/mempool"
"github.com/cometbft/cometbft/types"
"golang.org/x/sync/semaphore"
)
// Reactor handles mempool tx broadcasting amongst peers.
// It maintains a map from peer ID to counter, to prevent gossiping txs to the
// peers you received it from.
type Reactor struct {
p2p.BaseReactor
config *cfg.MempoolConfig
mempool *CListMempool
ids *mempoolIDs
// Semaphores to keep track of how many connections to peers are active for broadcasting
// transactions. Each semaphore has a capacity that puts an upper bound on the number of
// connections for different groups of peers.
activePersistentPeersSemaphore *semaphore.Weighted
activeNonPersistentPeersSemaphore *semaphore.Weighted
}
// NewReactor returns a new Reactor with the given config and mempool.
func NewReactor(config *cfg.MempoolConfig, mempool *CListMempool) *Reactor {
memR := &Reactor{
config: config,
mempool: mempool,
ids: newMempoolIDs(),
}
memR.BaseReactor = *p2p.NewBaseReactor("Mempool", memR)
memR.activePersistentPeersSemaphore = semaphore.NewWeighted(int64(memR.config.ExperimentalMaxGossipConnectionsToPersistentPeers))
memR.activeNonPersistentPeersSemaphore = semaphore.NewWeighted(int64(memR.config.ExperimentalMaxGossipConnectionsToNonPersistentPeers))
return memR
}
// InitPeer implements Reactor by creating a state for the peer.
func (memR *Reactor) InitPeer(peer p2p.Peer) p2p.Peer {
memR.ids.ReserveForPeer(peer)
return peer
}
// SetLogger sets the Logger on the reactor and the underlying mempool.
func (memR *Reactor) SetLogger(l log.Logger) {
memR.Logger = l
memR.mempool.SetLogger(l)
}
// OnStart implements p2p.BaseReactor.
func (memR *Reactor) OnStart() error {
if !memR.config.Broadcast {
memR.Logger.Info("Tx broadcasting is disabled")
}
return nil
}
// GetChannels implements Reactor by returning the list of channels for this
// reactor.
func (memR *Reactor) GetChannels() []*p2p.ChannelDescriptor {
largestTx := make([]byte, memR.config.MaxTxBytes)
batchMsg := protomem.Message{
Sum: &protomem.Message_Txs{
Txs: &protomem.Txs{Txs: [][]byte{largestTx}},
},
}
return []*p2p.ChannelDescriptor{
{
ID: MempoolChannel,
Priority: 5,
RecvMessageCapacity: batchMsg.Size(),
MessageType: &protomem.Message{},
},
}
}
// AddPeer implements Reactor.
// It starts a broadcast routine ensuring all txs are forwarded to the given peer.
func (memR *Reactor) AddPeer(peer p2p.Peer) {
if memR.config.Broadcast {
go func() {
// Always forward transactions to unconditional peers.
if !memR.Switch.IsPeerUnconditional(peer.ID()) {
// Depending on the type of peer, we choose a semaphore to limit the gossiping peers.
var peerSemaphore *semaphore.Weighted
if peer.IsPersistent() && memR.config.ExperimentalMaxGossipConnectionsToPersistentPeers > 0 {
peerSemaphore = memR.activePersistentPeersSemaphore
} else if !peer.IsPersistent() && memR.config.ExperimentalMaxGossipConnectionsToNonPersistentPeers > 0 {
peerSemaphore = memR.activeNonPersistentPeersSemaphore
}
if peerSemaphore != nil {
for peer.IsRunning() {
// Block on the semaphore until a slot is available to start gossiping with this peer.
// Do not block indefinitely, in case the peer is disconnected before gossiping starts.
ctxTimeout, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
// Block sending transactions to peer until one of the connections become
// available in the semaphore.
err := peerSemaphore.Acquire(ctxTimeout, 1)
cancel()
if err != nil {
continue
}
// Release semaphore to allow other peer to start sending transactions.
defer peerSemaphore.Release(1)
break
}
}
}
memR.mempool.metrics.ActiveOutboundConnections.Add(1)
defer memR.mempool.metrics.ActiveOutboundConnections.Add(-1)
memR.broadcastTxRoutine(peer)
}()
}
}
// RemovePeer implements Reactor.
func (memR *Reactor) RemovePeer(peer p2p.Peer, _ interface{}) {
memR.ids.Reclaim(peer)
// broadcast routine checks if peer is gone and returns
}
// Receive implements Reactor.
// It adds any received transactions to the mempool.
func (memR *Reactor) Receive(e p2p.Envelope) {
memR.Logger.Debug("Receive", "src", e.Src, "chId", e.ChannelID, "msg", e.Message)
switch msg := e.Message.(type) {
case *protomem.Txs:
protoTxs := msg.GetTxs()
if len(protoTxs) == 0 {
memR.Logger.Error("received empty txs from peer", "src", e.Src)
return
}
txInfo := TxInfo{SenderID: memR.ids.GetForPeer(e.Src)}
if e.Src != nil {
txInfo.SenderP2PID = e.Src.ID()
}
var err error
for _, tx := range protoTxs {
ntx := types.Tx(tx)
err = memR.mempool.CheckTx(ntx, nil, txInfo)
if err != nil {
switch {
case errors.Is(err, ErrTxInCache):
memR.Logger.Debug("Tx already exists in cache", "tx", ntx.String())
case errors.As(err, &ErrMempoolIsFull{}):
// using debug level to avoid flooding when traffic is high
memR.Logger.Debug(err.Error())
default:
memR.Logger.Info("Could not check tx", "tx", ntx.String(), "err", err)
}
}
}
default:
memR.Logger.Error("unknown message type", "src", e.Src, "chId", e.ChannelID, "msg", e.Message)
memR.Switch.StopPeerForError(e.Src, fmt.Errorf("mempool cannot handle message of type: %T", e.Message))
return
}
// broadcasting happens from go routines per peer
}
// PeerState describes the state of a peer.
type PeerState interface {
GetHeight() int64
}
// Send new mempool txs to peer.
func (memR *Reactor) broadcastTxRoutine(peer p2p.Peer) {
peerID := memR.ids.GetForPeer(peer)
var next *clist.CElement
for {
// In case of both next.NextWaitChan() and peer.Quit() are variable at the same time
if !memR.IsRunning() || !peer.IsRunning() {
return
}
// This happens because the CElement we were looking at got garbage
// collected (removed). That is, .NextWait() returned nil. Go ahead and
// start from the beginning.
if next == nil {
select {
case <-memR.mempool.TxsWaitChan(): // Wait until a tx is available
if next = memR.mempool.TxsFront(); next == nil {
continue
}
case <-peer.Quit():
return
case <-memR.Quit():
return
}
}
// Make sure the peer is up to date.
peerState, ok := peer.Get(types.PeerStateKey).(PeerState)
if !ok {
// Peer does not have a state yet. We set it in the consensus reactor, but
// when we add peer in Switch, the order we call reactors#AddPeer is
// different every time due to us using a map. Sometimes other reactors
// will be initialized before the consensus reactor. We should wait a few
// milliseconds and retry.
time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond)
continue
}
// Allow for a lag of 1 block.
memTx := next.Value.(*mempoolTx)
if peerState.GetHeight() < memTx.Height()-1 {
time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond)
continue
}
// NOTE: Transaction batching was disabled due to
// https://github.com/tendermint/tendermint/issues/5796
if !memTx.isSender(peerID) {
success := peer.Send(p2p.Envelope{
ChannelID: MempoolChannel,
Message: &protomem.Txs{Txs: [][]byte{memTx.tx}},
})
if !success {
time.Sleep(PeerCatchupSleepIntervalMS * time.Millisecond)
continue
}
}
select {
case <-next.NextWaitChan():
// see the start of the for loop for nil check
next = next.Next()
case <-peer.Quit():
return
case <-memR.Quit():
return
}
}
}
// TxsMessage is a Message containing transactions.
type TxsMessage struct {
Txs []types.Tx
}
// String returns a string representation of the TxsMessage.
func (m *TxsMessage) String() string {
return fmt.Sprintf("[TxsMessage %v]", m.Txs)
}
package conn
import (
"bufio"
"errors"
"fmt"
"io"
"math"
"net"
"reflect"
"runtime/debug"
"sync/atomic"
"time"
"github.com/cosmos/gogoproto/proto"
"github.com/cometbft/cometbft/config"
flow "github.com/cometbft/cometbft/libs/flowrate"
"github.com/cometbft/cometbft/libs/log"
"github.com/cometbft/cometbft/libs/protoio"
"github.com/cometbft/cometbft/libs/service"
cmtsync "github.com/cometbft/cometbft/libs/sync"
"github.com/cometbft/cometbft/libs/timer"
tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p"
)
const (
defaultMaxPacketMsgPayloadSize = 1024
numBatchPacketMsgs = 10
minReadBufferSize = 1024
minWriteBufferSize = 65536
updateStats = 2 * time.Second
// some of these defaults are written in the user config
// flushThrottle, sendRate, recvRate
// TODO: remove values present in config
defaultFlushThrottle = 100 * time.Millisecond
defaultSendQueueCapacity = 1
defaultRecvBufferCapacity = 4096
defaultRecvMessageCapacity = 22020096 // 21MB
defaultSendRate = int64(512000) // 500KB/s
defaultRecvRate = int64(512000) // 500KB/s
defaultSendTimeout = 10 * time.Second
defaultPingInterval = 60 * time.Second
defaultPongTimeout = 45 * time.Second
)
type (
receiveCbFunc func(chID byte, msgBytes []byte)
errorCbFunc func(interface{})
)
/*
Each peer has one `MConnection` (multiplex connection) instance.
__multiplex__ *noun* a system or signal involving simultaneous transmission of
several messages along a single channel of communication.
Each `MConnection` handles message transmission on multiple abstract communication
`Channel`s. Each channel has a globally unique byte id.
The byte id and the relative priorities of each `Channel` are configured upon
initialization of the connection.
There are two methods for sending messages:
func (m MConnection) Send(chID byte, msgBytes []byte) bool {}
func (m MConnection) TrySend(chID byte, msgBytes []byte}) bool {}
`Send(chID, msgBytes)` is a blocking call that waits until `msg` is
successfully queued for the channel with the given id byte `chID`, or until the
request times out. The message `msg` is serialized using Protobuf.
`TrySend(chID, msgBytes)` is a nonblocking call that returns false if the
channel's queue is full.
Inbound message bytes are handled with an onReceive callback function.
*/
type MConnection struct {
service.BaseService
conn net.Conn
bufConnReader *bufio.Reader
bufConnWriter *bufio.Writer
sendMonitor *flow.Monitor
recvMonitor *flow.Monitor
send chan struct{}
pong chan struct{}
channels []*Channel
channelsIdx map[byte]*Channel
onReceive receiveCbFunc
onError errorCbFunc
errored uint32
config MConnConfig
// Closing quitSendRoutine will cause the sendRoutine to eventually quit.
// doneSendRoutine is closed when the sendRoutine actually quits.
quitSendRoutine chan struct{}
doneSendRoutine chan struct{}
// Closing quitRecvRouting will cause the recvRouting to eventually quit.
quitRecvRoutine chan struct{}
// used to ensure FlushStop and OnStop
// are safe to call concurrently.
stopMtx cmtsync.Mutex
flushTimer *timer.ThrottleTimer // flush writes as necessary but throttled.
pingTimer *time.Ticker // send pings periodically
// close conn if pong is not received in pongTimeout
pongTimer *time.Timer
pongTimeoutCh chan bool // true - timeout, false - peer sent pong
chStatsTimer *time.Ticker // update channel stats periodically
created time.Time // time of creation
_maxPacketMsgSize int
}
// MConnConfig is a MConnection configuration.
type MConnConfig struct {
SendRate int64 `mapstructure:"send_rate"`
RecvRate int64 `mapstructure:"recv_rate"`
// Maximum payload size
MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"`
// Interval to flush writes (throttled)
FlushThrottle time.Duration `mapstructure:"flush_throttle"`
// Interval to send pings
PingInterval time.Duration `mapstructure:"ping_interval"`
// Maximum wait time for pongs
PongTimeout time.Duration `mapstructure:"pong_timeout"`
// Fuzz connection
TestFuzz bool `mapstructure:"test_fuzz"`
TestFuzzConfig *config.FuzzConnConfig `mapstructure:"test_fuzz_config"`
}
// DefaultMConnConfig returns the default config.
func DefaultMConnConfig() MConnConfig {
return MConnConfig{
SendRate: defaultSendRate,
RecvRate: defaultRecvRate,
MaxPacketMsgPayloadSize: defaultMaxPacketMsgPayloadSize,
FlushThrottle: defaultFlushThrottle,
PingInterval: defaultPingInterval,
PongTimeout: defaultPongTimeout,
}
}
// NewMConnection wraps net.Conn and creates multiplex connection
func NewMConnection(
conn net.Conn,
chDescs []*ChannelDescriptor,
onReceive receiveCbFunc,
onError errorCbFunc,
) *MConnection {
return NewMConnectionWithConfig(
conn,
chDescs,
onReceive,
onError,
DefaultMConnConfig())
}
// NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config
func NewMConnectionWithConfig(
conn net.Conn,
chDescs []*ChannelDescriptor,
onReceive receiveCbFunc,
onError errorCbFunc,
config MConnConfig,
) *MConnection {
if config.PongTimeout >= config.PingInterval {
panic("pongTimeout must be less than pingInterval (otherwise, next ping will reset pong timer)")
}
mconn := &MConnection{
conn: conn,
bufConnReader: bufio.NewReaderSize(conn, minReadBufferSize),
bufConnWriter: bufio.NewWriterSize(conn, minWriteBufferSize),
sendMonitor: flow.New(0, 0),
recvMonitor: flow.New(0, 0),
send: make(chan struct{}, 1),
pong: make(chan struct{}, 1),
onReceive: onReceive,
onError: onError,
config: config,
created: time.Now(),
}
// Create channels
channelsIdx := map[byte]*Channel{}
channels := []*Channel{}
for _, desc := range chDescs {
channel := newChannel(mconn, *desc)
channelsIdx[channel.desc.ID] = channel
channels = append(channels, channel)
}
mconn.channels = channels
mconn.channelsIdx = channelsIdx
mconn.BaseService = *service.NewBaseService(nil, "MConnection", mconn)
// maxPacketMsgSize() is a bit heavy, so call just once
mconn._maxPacketMsgSize = mconn.maxPacketMsgSize()
return mconn
}
func (c *MConnection) SetLogger(l log.Logger) {
c.BaseService.SetLogger(l)
for _, ch := range c.channels {
ch.SetLogger(l)
}
}
// OnStart implements BaseService
func (c *MConnection) OnStart() error {
if err := c.BaseService.OnStart(); err != nil {
return err
}
c.flushTimer = timer.NewThrottleTimer("flush", c.config.FlushThrottle)
c.pingTimer = time.NewTicker(c.config.PingInterval)
c.pongTimeoutCh = make(chan bool, 1)
c.chStatsTimer = time.NewTicker(updateStats)
c.quitSendRoutine = make(chan struct{})
c.doneSendRoutine = make(chan struct{})
c.quitRecvRoutine = make(chan struct{})
go c.sendRoutine()
go c.recvRoutine()
return nil
}
// stopServices stops the BaseService and timers and closes the quitSendRoutine.
// if the quitSendRoutine was already closed, it returns true, otherwise it returns false.
// It uses the stopMtx to ensure only one of FlushStop and OnStop can do this at a time.
func (c *MConnection) stopServices() (alreadyStopped bool) {
c.stopMtx.Lock()
defer c.stopMtx.Unlock()
select {
case <-c.quitSendRoutine:
// already quit
return true
default:
}
select {
case <-c.quitRecvRoutine:
// already quit
return true
default:
}
c.BaseService.OnStop()
c.flushTimer.Stop()
c.pingTimer.Stop()
c.chStatsTimer.Stop()
// inform the recvRouting that we are shutting down
close(c.quitRecvRoutine)
close(c.quitSendRoutine)
return false
}
// FlushStop replicates the logic of OnStop.
// It additionally ensures that all successful
// .Send() calls will get flushed before closing
// the connection.
func (c *MConnection) FlushStop() {
if c.stopServices() {
return
}
// this block is unique to FlushStop
{
// wait until the sendRoutine exits
// so we dont race on calling sendSomePacketMsgs
<-c.doneSendRoutine
// Send and flush all pending msgs.
// Since sendRoutine has exited, we can call this
// safely
w := protoio.NewDelimitedWriter(c.bufConnWriter)
eof := c.sendSomePacketMsgs(w)
for !eof {
eof = c.sendSomePacketMsgs(w)
}
c.flush()
// Now we can close the connection
}
c.conn.Close()
// We can't close pong safely here because
// recvRoutine may write to it after we've stopped.
// Though it doesn't need to get closed at all,
// we close it @ recvRoutine.
// c.Stop()
}
// OnStop implements BaseService
func (c *MConnection) OnStop() {
if c.stopServices() {
return
}
c.conn.Close()
// We can't close pong safely here because
// recvRoutine may write to it after we've stopped.
// Though it doesn't need to get closed at all,
// we close it @ recvRoutine.
}
func (c *MConnection) String() string {
return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
}
func (c *MConnection) flush() {
c.Logger.Debug("Flush", "conn", c)
err := c.bufConnWriter.Flush()
if err != nil {
c.Logger.Debug("MConnection flush failed", "err", err)
}
}
// Catch panics, usually caused by remote disconnects.
func (c *MConnection) _recover() {
if r := recover(); r != nil {
c.Logger.Error("MConnection panicked", "err", r, "stack", string(debug.Stack()))
c.stopForError(fmt.Errorf("recovered from panic: %v", r))
}
}
func (c *MConnection) stopForError(r interface{}) {
if err := c.Stop(); err != nil {
c.Logger.Error("Error stopping connection", "err", err)
}
if atomic.CompareAndSwapUint32(&c.errored, 0, 1) {
if c.onError != nil {
c.onError(r)
}
}
}
// Queues a message to be sent to channel.
func (c *MConnection) Send(chID byte, msgBytes []byte) bool {
if !c.IsRunning() {
return false
}
c.Logger.Debug("Send", "channel", chID, "conn", c, "msgBytes", log.NewLazySprintf("%X", msgBytes))
// Send message to channel.
channel, ok := c.channelsIdx[chID]
if !ok {
c.Logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID))
return false
}
success := channel.sendBytes(msgBytes)
if success {
// Wake up sendRoutine if necessary
select {
case c.send <- struct{}{}:
default:
}
} else {
c.Logger.Debug("Send failed", "channel", chID, "conn", c, "msgBytes", log.NewLazySprintf("%X", msgBytes))
}
return success
}
// Queues a message to be sent to channel.
// Nonblocking, returns true if successful.
func (c *MConnection) TrySend(chID byte, msgBytes []byte) bool {
if !c.IsRunning() {
return false
}
c.Logger.Debug("TrySend", "channel", chID, "conn", c, "msgBytes", log.NewLazySprintf("%X", msgBytes))
// Send message to channel.
channel, ok := c.channelsIdx[chID]
if !ok {
c.Logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID))
return false
}
ok = channel.trySendBytes(msgBytes)
if ok {
// Wake up sendRoutine if necessary
select {
case c.send <- struct{}{}:
default:
}
}
return ok
}
// CanSend returns true if you can send more data onto the chID, false
// otherwise. Use only as a heuristic.
func (c *MConnection) CanSend(chID byte) bool {
if !c.IsRunning() {
return false
}
channel, ok := c.channelsIdx[chID]
if !ok {
c.Logger.Error(fmt.Sprintf("Unknown channel %X", chID))
return false
}
return channel.canSend()
}
// sendRoutine polls for packets to send from channels.
func (c *MConnection) sendRoutine() {
defer c._recover()
protoWriter := protoio.NewDelimitedWriter(c.bufConnWriter)
FOR_LOOP:
for {
var _n int
var err error
SELECTION:
select {
case <-c.flushTimer.Ch:
// NOTE: flushTimer.Set() must be called every time
// something is written to .bufConnWriter.
c.flush()
case <-c.chStatsTimer.C:
for _, channel := range c.channels {
channel.updateStats()
}
case <-c.pingTimer.C:
c.Logger.Debug("Send Ping")
_n, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPing{}))
if err != nil {
c.Logger.Error("Failed to send PacketPing", "err", err)
break SELECTION
}
c.sendMonitor.Update(_n)
c.Logger.Debug("Starting pong timer", "dur", c.config.PongTimeout)
c.pongTimer = time.AfterFunc(c.config.PongTimeout, func() {
select {
case c.pongTimeoutCh <- true:
default:
}
})
c.flush()
case timeout := <-c.pongTimeoutCh:
if timeout {
c.Logger.Debug("Pong timeout")
err = errors.New("pong timeout")
} else {
c.stopPongTimer()
}
case <-c.pong:
c.Logger.Debug("Send Pong")
_n, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{}))
if err != nil {
c.Logger.Error("Failed to send PacketPong", "err", err)
break SELECTION
}
c.sendMonitor.Update(_n)
c.flush()
case <-c.quitSendRoutine:
break FOR_LOOP
case <-c.send:
// Send some PacketMsgs
eof := c.sendSomePacketMsgs(protoWriter)
if !eof {
// Keep sendRoutine awake.
select {
case c.send <- struct{}{}:
default:
}
}
}
if !c.IsRunning() {
break FOR_LOOP
}
if err != nil {
c.Logger.Error("Connection failed @ sendRoutine", "conn", c, "err", err)
c.stopForError(err)
break FOR_LOOP
}
}
// Cleanup
c.stopPongTimer()
close(c.doneSendRoutine)
}
// Returns true if messages from channels were exhausted.
// Blocks in accordance to .sendMonitor throttling.
func (c *MConnection) sendSomePacketMsgs(w protoio.Writer) bool {
// Block until .sendMonitor says we can write.
// Once we're ready we send more than we asked for,
// but amortized it should even out.
c.sendMonitor.Limit(c._maxPacketMsgSize, c.config.SendRate, true)
// Now send some PacketMsgs.
return c.sendBatchPacketMsgs(w, numBatchPacketMsgs)
}
// Returns true if messages from channels were exhausted.
func (c *MConnection) sendBatchPacketMsgs(w protoio.Writer, batchSize int) bool {
// Send a batch of PacketMsgs.
totalBytesWritten := 0
defer func() {
if totalBytesWritten > 0 {
c.sendMonitor.Update(totalBytesWritten)
}
}()
for i := 0; i < batchSize; i++ {
channel := selectChannelToGossipOn(c.channels)
// nothing to send across any channel.
if channel == nil {
return true
}
bytesWritten, err := c.sendPacketMsgOnChannel(w, channel)
if err {
return true
}
totalBytesWritten += bytesWritten
}
return false
}
// selects a channel to gossip our next message on.
// TODO: Make "batchChannelToGossipOn", so we can do our proto marshaling overheads in parallel,
// and we can avoid re-checking for `isSendPending`.
// We can easily mock the recentlySent differences for the batch choosing.
func selectChannelToGossipOn(channels []*Channel) *Channel {
// Choose a channel to create a PacketMsg from.
// The chosen channel will be the one whose recentlySent/priority is the least.
var leastRatio float32 = math.MaxFloat32
var leastChannel *Channel
for _, channel := range channels {
// If nothing to send, skip this channel
// TODO: Skip continually looking for isSendPending on channels we've already skipped in this batch-send.
if !channel.isSendPending() {
continue
}
// Get ratio, and keep track of lowest ratio.
// TODO: RecentlySent right now is bytes. This should be refactored to num messages to fix
// gossip prioritization bugs.
ratio := float32(channel.recentlySent) / float32(channel.desc.Priority)
if ratio < leastRatio {
leastRatio = ratio
leastChannel = channel
}
}
return leastChannel
}
// returns (num_bytes_written, error_occurred).
func (c *MConnection) sendPacketMsgOnChannel(w protoio.Writer, sendChannel *Channel) (int, bool) {
// Make & send a PacketMsg from this channel
n, err := sendChannel.writePacketMsgTo(w)
if err != nil {
c.Logger.Error("Failed to write PacketMsg", "err", err)
c.stopForError(err)
return n, true
}
// TODO: Change this to only add flush signals at the start and end of the batch.
c.flushTimer.Set()
return n, false
}
// recvRoutine reads PacketMsgs and reconstructs the message using the channels' "recving" buffer.
// After a whole message has been assembled, it's pushed to onReceive().
// Blocks depending on how the connection is throttled.
// Otherwise, it never blocks.
func (c *MConnection) recvRoutine() {
defer c._recover()
protoReader := protoio.NewDelimitedReader(c.bufConnReader, c._maxPacketMsgSize)
FOR_LOOP:
for {
// Block until .recvMonitor says we can read.
c.recvMonitor.Limit(c._maxPacketMsgSize, atomic.LoadInt64(&c.config.RecvRate), true)
// Peek into bufConnReader for debugging
/*
if numBytes := c.bufConnReader.Buffered(); numBytes > 0 {
bz, err := c.bufConnReader.Peek(cmtmath.MinInt(numBytes, 100))
if err == nil {
// return
} else {
c.Logger.Debug("Error peeking connection buffer", "err", err)
// return nil
}
c.Logger.Info("Peek connection buffer", "numBytes", numBytes, "bz", bz)
}
*/
// Read packet type
var packet tmp2p.Packet
_n, err := protoReader.ReadMsg(&packet)
c.recvMonitor.Update(_n)
if err != nil {
// stopServices was invoked and we are shutting down
// receiving is excpected to fail since we will close the connection
select {
case <-c.quitRecvRoutine:
break FOR_LOOP
default:
}
if c.IsRunning() {
if err == io.EOF {
c.Logger.Info("Connection is closed @ recvRoutine (likely by the other side)", "conn", c)
} else {
c.Logger.Debug("Connection failed @ recvRoutine (reading byte)", "conn", c, "err", err)
}
c.stopForError(err)
}
break FOR_LOOP
}
// Read more depending on packet type.
switch pkt := packet.Sum.(type) {
case *tmp2p.Packet_PacketPing:
// TODO: prevent abuse, as they cause flush()'s.
// https://github.com/tendermint/tendermint/issues/1190
c.Logger.Debug("Receive Ping")
select {
case c.pong <- struct{}{}:
default:
// never block
}
case *tmp2p.Packet_PacketPong:
c.Logger.Debug("Receive Pong")
select {
case c.pongTimeoutCh <- false:
default:
// never block
}
case *tmp2p.Packet_PacketMsg:
channelID := byte(pkt.PacketMsg.ChannelID)
channel, ok := c.channelsIdx[channelID]
if pkt.PacketMsg.ChannelID < 0 || pkt.PacketMsg.ChannelID > math.MaxUint8 || !ok || channel == nil {
err := fmt.Errorf("unknown channel %X", pkt.PacketMsg.ChannelID)
c.Logger.Debug("Connection failed @ recvRoutine", "conn", c, "err", err)
c.stopForError(err)
break FOR_LOOP
}
msgBytes, err := channel.recvPacketMsg(*pkt.PacketMsg)
if err != nil {
if c.IsRunning() {
c.Logger.Debug("Connection failed @ recvRoutine", "conn", c, "err", err)
c.stopForError(err)
}
break FOR_LOOP
}
if msgBytes != nil {
c.Logger.Debug("Received bytes", "chID", channelID, "msgBytes", msgBytes)
// NOTE: This means the reactor.Receive runs in the same thread as the p2p recv routine
c.onReceive(channelID, msgBytes)
}
default:
err := fmt.Errorf("unknown message type %v", reflect.TypeOf(packet))
c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
c.stopForError(err)
break FOR_LOOP
}
}
// Cleanup
close(c.pong)
//nolint:revive
for range c.pong {
// Drain
}
}
// not goroutine-safe
func (c *MConnection) stopPongTimer() {
if c.pongTimer != nil {
_ = c.pongTimer.Stop()
c.pongTimer = nil
}
}
// maxPacketMsgSize returns a maximum size of PacketMsg
func (c *MConnection) maxPacketMsgSize() int {
bz, err := proto.Marshal(mustWrapPacket(&tmp2p.PacketMsg{
ChannelID: 0x01,
EOF: true,
Data: make([]byte, c.config.MaxPacketMsgPayloadSize),
}))
if err != nil {
panic(err)
}
return len(bz)
}
type ConnectionStatus struct {
Duration time.Duration
SendMonitor flow.Status
RecvMonitor flow.Status
Channels []ChannelStatus
}
type ChannelStatus struct {
ID byte
SendQueueCapacity int
SendQueueSize int
Priority int
RecentlySent int64
}
func (c *MConnection) Status() ConnectionStatus {
var status ConnectionStatus
status.Duration = time.Since(c.created)
status.SendMonitor = c.sendMonitor.Status()
status.RecvMonitor = c.recvMonitor.Status()
status.Channels = make([]ChannelStatus, len(c.channels))
for i, channel := range c.channels {
channel := channel
status.Channels[i] = ChannelStatus{
ID: channel.desc.ID,
SendQueueCapacity: cap(channel.sendQueue),
SendQueueSize: int(atomic.LoadInt32(&channel.sendQueueSize)),
Priority: channel.desc.Priority,
RecentlySent: atomic.LoadInt64(&channel.recentlySent),
}
}
return status
}
//-----------------------------------------------------------------------------
type ChannelDescriptor struct {
ID byte
Priority int
SendQueueCapacity int
RecvBufferCapacity int
RecvMessageCapacity int
MessageType proto.Message
}
func (chDesc ChannelDescriptor) FillDefaults() (filled ChannelDescriptor) {
if chDesc.SendQueueCapacity == 0 {
chDesc.SendQueueCapacity = defaultSendQueueCapacity
}
if chDesc.RecvBufferCapacity == 0 {
chDesc.RecvBufferCapacity = defaultRecvBufferCapacity
}
if chDesc.RecvMessageCapacity == 0 {
chDesc.RecvMessageCapacity = defaultRecvMessageCapacity
}
filled = chDesc
return
}
// TODO: lowercase.
// NOTE: not goroutine-safe.
type Channel struct {
conn *MConnection
desc ChannelDescriptor
sendQueue chan []byte
sendQueueSize int32 // atomic.
recving []byte
sending []byte
recentlySent int64 // exponential moving average
maxPacketMsgPayloadSize int
Logger log.Logger
}
func newChannel(conn *MConnection, desc ChannelDescriptor) *Channel {
desc = desc.FillDefaults()
if desc.Priority <= 0 {
panic("Channel default priority must be a positive integer")
}
return &Channel{
conn: conn,
desc: desc,
sendQueue: make(chan []byte, desc.SendQueueCapacity),
recving: make([]byte, 0, desc.RecvBufferCapacity),
maxPacketMsgPayloadSize: conn.config.MaxPacketMsgPayloadSize,
}
}
func (ch *Channel) SetLogger(l log.Logger) {
ch.Logger = l
}
// Queues message to send to this channel.
// Goroutine-safe
// Times out (and returns false) after defaultSendTimeout
func (ch *Channel) sendBytes(bytes []byte) bool {
select {
case ch.sendQueue <- bytes:
atomic.AddInt32(&ch.sendQueueSize, 1)
return true
case <-time.After(defaultSendTimeout):
return false
}
}
// Queues message to send to this channel.
// Nonblocking, returns true if successful.
// Goroutine-safe
func (ch *Channel) trySendBytes(bytes []byte) bool {
select {
case ch.sendQueue <- bytes:
atomic.AddInt32(&ch.sendQueueSize, 1)
return true
default:
return false
}
}
// Goroutine-safe
func (ch *Channel) loadSendQueueSize() (size int) {
return int(atomic.LoadInt32(&ch.sendQueueSize))
}
// Goroutine-safe
// Use only as a heuristic.
func (ch *Channel) canSend() bool {
return ch.loadSendQueueSize() < defaultSendQueueCapacity
}
// Returns true if any PacketMsgs are pending to be sent.
// Call before calling nextPacketMsg()
// Goroutine-safe
func (ch *Channel) isSendPending() bool {
if len(ch.sending) == 0 {
if len(ch.sendQueue) == 0 {
return false
}
ch.sending = <-ch.sendQueue
}
return true
}
// Creates a new PacketMsg to send.
// Not goroutine-safe
func (ch *Channel) nextPacketMsg() tmp2p.PacketMsg {
packet := tmp2p.PacketMsg{ChannelID: int32(ch.desc.ID)}
maxSize := ch.maxPacketMsgPayloadSize
if len(ch.sending) <= maxSize {
packet.Data = ch.sending
packet.EOF = true
ch.sending = nil
atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize
} else {
packet.Data = ch.sending[:maxSize]
packet.EOF = false
ch.sending = ch.sending[maxSize:]
}
return packet
}
// Writes next PacketMsg to w and updates c.recentlySent.
// Not goroutine-safe.
func (ch *Channel) writePacketMsgTo(w protoio.Writer) (n int, err error) {
packet := ch.nextPacketMsg()
n, err = w.WriteMsg(mustWrapPacket(&packet))
if err != nil {
return 0, err
}
atomic.AddInt64(&ch.recentlySent, int64(n))
return n, nil
}
// Handles incoming PacketMsgs. It returns a message bytes if message is
// complete. NOTE message bytes may change on next call to recvPacketMsg.
// Not goroutine-safe
func (ch *Channel) recvPacketMsg(packet tmp2p.PacketMsg) ([]byte, error) {
ch.Logger.Debug("Read PacketMsg", "conn", ch.conn, "packet", packet)
recvCap, recvReceived := ch.desc.RecvMessageCapacity, len(ch.recving)+len(packet.Data)
if recvCap < recvReceived {
return nil, fmt.Errorf("received message exceeds available capacity: %v < %v", recvCap, recvReceived)
}
ch.recving = append(ch.recving, packet.Data...)
if packet.EOF {
msgBytes := ch.recving
// clear the slice without re-allocating.
// http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go
// suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes,
// at which point the recving slice stops being used and should be garbage collected
ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity)
return msgBytes, nil
}
return nil, nil
}
// Call this periodically to update stats for throttling purposes.
// Not goroutine-safe
func (ch *Channel) updateStats() {
// Exponential decay of stats.
// TODO: optimize.
atomic.StoreInt64(&ch.recentlySent, int64(float64(atomic.LoadInt64(&ch.recentlySent))*0.8))
}
//----------------------------------------
// Packet
// mustWrapPacket takes a packet kind (oneof) and wraps it in a tmp2p.Packet message.
func mustWrapPacket(pb proto.Message) *tmp2p.Packet {
var msg tmp2p.Packet
switch pb := pb.(type) {
case *tmp2p.Packet: // already a packet
msg = *pb
case *tmp2p.PacketPing:
msg = tmp2p.Packet{
Sum: &tmp2p.Packet_PacketPing{
PacketPing: pb,
},
}
case *tmp2p.PacketPong:
msg = tmp2p.Packet{
Sum: &tmp2p.Packet_PacketPong{
PacketPong: pb,
},
}
case *tmp2p.PacketMsg:
msg = tmp2p.Packet{
Sum: &tmp2p.Packet_PacketMsg{
PacketMsg: pb,
},
}
default:
panic(fmt.Errorf("unknown packet type %T", pb))
}
return &msg
}
package p2p
import (
"fmt"
"net"
)
// ErrFilterTimeout indicates that a filter operation timed out.
type ErrFilterTimeout struct{}
func (e ErrFilterTimeout) Error() string {
return "filter timed out"
}
// ErrRejected indicates that a Peer was rejected carrying additional
// information as to the reason.
type ErrRejected struct {
addr NetAddress
conn net.Conn
err error
id ID
isAuthFailure bool
isDuplicate bool
isFiltered bool
isIncompatible bool
isNodeInfoInvalid bool
isSelf bool
}
// Addr returns the NetAddress for the rejected Peer.
func (e ErrRejected) Addr() NetAddress {
return e.addr
}
func (e ErrRejected) Error() string {
if e.isAuthFailure {
return fmt.Sprintf("auth failure: %s", e.err)
}
if e.isDuplicate {
if e.conn != nil {
return fmt.Sprintf(
"duplicate CONN<%s>",
e.conn.RemoteAddr().String(),
)
}
if e.id != "" {
return fmt.Sprintf("duplicate ID<%v>", e.id)
}
}
if e.isFiltered {
if e.conn != nil {
return fmt.Sprintf(
"filtered CONN<%s>: %s",
e.conn.RemoteAddr().String(),
e.err,
)
}
if e.id != "" {
return fmt.Sprintf("filtered ID<%v>: %s", e.id, e.err)
}
}
if e.isIncompatible {
return fmt.Sprintf("incompatible: %s", e.err)
}
if e.isNodeInfoInvalid {
return fmt.Sprintf("invalid NodeInfo: %s", e.err)
}
if e.isSelf {
return fmt.Sprintf("self ID<%v>", e.id)
}
return fmt.Sprintf("%s", e.err)
}
// IsAuthFailure when Peer authentication was unsuccessful.
func (e ErrRejected) IsAuthFailure() bool { return e.isAuthFailure }
// IsDuplicate when Peer ID or IP are present already.
func (e ErrRejected) IsDuplicate() bool { return e.isDuplicate }
// IsFiltered when Peer ID or IP was filtered.
func (e ErrRejected) IsFiltered() bool { return e.isFiltered }
// IsIncompatible when Peer NodeInfo is not compatible with our own.
func (e ErrRejected) IsIncompatible() bool { return e.isIncompatible }
// IsNodeInfoInvalid when the sent NodeInfo is not valid.
func (e ErrRejected) IsNodeInfoInvalid() bool { return e.isNodeInfoInvalid }
// IsSelf when Peer is our own node.
func (e ErrRejected) IsSelf() bool { return e.isSelf }
// ErrSwitchDuplicatePeerID to be raised when a peer is connecting with a known
// ID.
type ErrSwitchDuplicatePeerID struct {
ID ID
}
func (e ErrSwitchDuplicatePeerID) Error() string {
return fmt.Sprintf("duplicate peer ID %v", e.ID)
}
// ErrSwitchDuplicatePeerIP to be raised whena a peer is connecting with a known
// IP.
type ErrSwitchDuplicatePeerIP struct {
IP net.IP
}
func (e ErrSwitchDuplicatePeerIP) Error() string {
return fmt.Sprintf("duplicate peer IP %v", e.IP.String())
}
// ErrSwitchConnectToSelf to be raised when trying to connect to itself.
type ErrSwitchConnectToSelf struct {
Addr *NetAddress
}
func (e ErrSwitchConnectToSelf) Error() string {
return fmt.Sprintf("connect to self: %v", e.Addr)
}
type ErrSwitchAuthenticationFailure struct {
Dialed *NetAddress
Got ID
}
func (e ErrSwitchAuthenticationFailure) Error() string {
return fmt.Sprintf(
"failed to authenticate peer. Dialed %v, but got peer with ID %s",
e.Dialed,
e.Got,
)
}
// ErrTransportClosed is raised when the Transport has been closed.
type ErrTransportClosed struct{}
func (e ErrTransportClosed) Error() string {
return "transport has been closed"
}
// ErrPeerRemoval is raised when attempting to remove a peer results in an error.
type ErrPeerRemoval struct{}
func (e ErrPeerRemoval) Error() string {
return "peer removal failed"
}
//-------------------------------------------------------------------
type ErrNetAddressNoID struct {
Addr string
}
func (e ErrNetAddressNoID) Error() string {
return fmt.Sprintf("address (%s) does not contain ID", e.Addr)
}
type ErrNetAddressInvalid struct {
Addr string
Err error
}
func (e ErrNetAddressInvalid) Error() string {
return fmt.Sprintf("invalid address (%s): %v", e.Addr, e.Err)
}
type ErrNetAddressLookup struct {
Addr string
Err error
}
func (e ErrNetAddressLookup) Error() string {
return fmt.Sprintf("error looking up host (%s): %v", e.Addr, e.Err)
}
// ErrCurrentlyDialingOrExistingAddress indicates that we're currently
// dialing this address or it belongs to an existing peer.
type ErrCurrentlyDialingOrExistingAddress struct {
Addr string
}
func (e ErrCurrentlyDialingOrExistingAddress) Error() string {
return fmt.Sprintf("connection with %s has been established or dialed", e.Addr)
}
// Modified for CometBFT
// Originally Copyright (c) 2013-2014 Conformal Systems LLC.
// https://github.com/conformal/btcd/blob/master/LICENSE
package p2p
import (
"encoding/hex"
"errors"
"flag"
"fmt"
"net"
"strconv"
"strings"
"time"
tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p"
)
// EmptyNetAddress defines the string representation of an empty NetAddress
const EmptyNetAddress = "<nil-NetAddress>"
// NetAddress defines information about a peer on the network
// including its ID, IP address, and port.
type NetAddress struct {
ID ID `json:"id"`
IP net.IP `json:"ip"`
Port uint16 `json:"port"`
}
// IDAddressString returns id@hostPort. It strips the leading
// protocol from protocolHostPort if it exists.
func IDAddressString(id ID, protocolHostPort string) string {
hostPort := removeProtocolIfDefined(protocolHostPort)
return fmt.Sprintf("%s@%s", id, hostPort)
}
// NewNetAddress returns a new NetAddress using the provided TCP
// address. When testing, other net.Addr (except TCP) will result in
// using 0.0.0.0:0. When normal run, other net.Addr (except TCP) will
// panic. Panics if ID is invalid.
// TODO: socks proxies?
func NewNetAddress(id ID, addr net.Addr) *NetAddress {
tcpAddr, ok := addr.(*net.TCPAddr)
if !ok {
if flag.Lookup("test.v") == nil { // normal run
panic(fmt.Sprintf("Only TCPAddrs are supported. Got: %v", addr))
}
// in testing
netAddr := NewNetAddressIPPort(net.IP("127.0.0.1"), 0)
netAddr.ID = id
return netAddr
}
if err := validateID(id); err != nil {
panic(fmt.Sprintf("Invalid ID %v: %v (addr: %v)", id, err, addr))
}
ip := tcpAddr.IP
port := uint16(tcpAddr.Port)
na := NewNetAddressIPPort(ip, port)
na.ID = id
return na
}
// NewNetAddressString returns a new NetAddress using the provided address in
// the form of "ID@IP:Port".
// Also resolves the host if host is not an IP.
// Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup)
func NewNetAddressString(addr string) (*NetAddress, error) {
addrWithoutProtocol := removeProtocolIfDefined(addr)
spl := strings.Split(addrWithoutProtocol, "@")
if len(spl) != 2 {
return nil, ErrNetAddressNoID{addr}
}
// get ID
if err := validateID(ID(spl[0])); err != nil {
return nil, ErrNetAddressInvalid{addrWithoutProtocol, err}
}
var id ID
id, addrWithoutProtocol = ID(spl[0]), spl[1]
// get host and port
host, portStr, err := net.SplitHostPort(addrWithoutProtocol)
if err != nil {
return nil, ErrNetAddressInvalid{addrWithoutProtocol, err}
}
if len(host) == 0 {
return nil, ErrNetAddressInvalid{
addrWithoutProtocol,
errors.New("host is empty")}
}
ip := net.ParseIP(host)
if ip == nil {
ips, err := net.LookupIP(host)
if err != nil {
return nil, ErrNetAddressLookup{host, err}
}
ip = ips[0]
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, ErrNetAddressInvalid{portStr, err}
}
na := NewNetAddressIPPort(ip, uint16(port))
na.ID = id
return na, nil
}
// NewNetAddressStrings returns an array of NetAddress'es build using
// the provided strings.
func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) {
netAddrs := make([]*NetAddress, 0)
errs := make([]error, 0)
for _, addr := range addrs {
netAddr, err := NewNetAddressString(addr)
if err != nil {
errs = append(errs, err)
} else {
netAddrs = append(netAddrs, netAddr)
}
}
return netAddrs, errs
}
// NewNetAddressIPPort returns a new NetAddress using the provided IP
// and port number.
func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress {
return &NetAddress{
IP: ip,
Port: port,
}
}
// NetAddressFromProto converts a Protobuf NetAddress into a native struct.
func NetAddressFromProto(pb tmp2p.NetAddress) (*NetAddress, error) {
ip := net.ParseIP(pb.IP)
if ip == nil {
return nil, fmt.Errorf("invalid IP address %v", pb.IP)
}
if pb.Port >= 1<<16 {
return nil, fmt.Errorf("invalid port number %v", pb.Port)
}
return &NetAddress{
ID: ID(pb.ID),
IP: ip,
Port: uint16(pb.Port),
}, nil
}
// NetAddressesFromProto converts a slice of Protobuf NetAddresses into a native slice.
func NetAddressesFromProto(pbs []tmp2p.NetAddress) ([]*NetAddress, error) {
nas := make([]*NetAddress, 0, len(pbs))
for _, pb := range pbs {
na, err := NetAddressFromProto(pb)
if err != nil {
return nil, err
}
nas = append(nas, na)
}
return nas, nil
}
// NetAddressesToProto converts a slice of NetAddresses into a Protobuf slice.
func NetAddressesToProto(nas []*NetAddress) []tmp2p.NetAddress {
pbs := make([]tmp2p.NetAddress, 0, len(nas))
for _, na := range nas {
if na != nil {
pbs = append(pbs, na.ToProto())
}
}
return pbs
}
// ToProto converts a NetAddress to Protobuf.
func (na *NetAddress) ToProto() tmp2p.NetAddress {
return tmp2p.NetAddress{
ID: string(na.ID),
IP: na.IP.String(),
Port: uint32(na.Port),
}
}
// Equals reports whether na and other are the same addresses,
// including their ID, IP, and Port.
func (na *NetAddress) Equals(other interface{}) bool {
if o, ok := other.(*NetAddress); ok {
return na.String() == o.String()
}
return false
}
// Same returns true is na has the same non-empty ID or DialString as other.
func (na *NetAddress) Same(other interface{}) bool {
if o, ok := other.(*NetAddress); ok {
if na.DialString() == o.DialString() {
return true
}
if na.ID != "" && na.ID == o.ID {
return true
}
}
return false
}
// String representation: <ID>@<IP>:<PORT>
func (na *NetAddress) String() string {
if na == nil {
return EmptyNetAddress
}
addrStr := na.DialString()
if na.ID != "" {
addrStr = IDAddressString(na.ID, addrStr)
}
return addrStr
}
func (na *NetAddress) DialString() string {
if na == nil {
return "<nil-NetAddress>"
}
return net.JoinHostPort(
na.IP.String(),
strconv.FormatUint(uint64(na.Port), 10),
)
}
// Dial calls net.Dial on the address.
func (na *NetAddress) Dial() (net.Conn, error) {
conn, err := net.Dial("tcp", na.DialString())
if err != nil {
return nil, err
}
return conn, nil
}
// DialTimeout calls net.DialTimeout on the address.
func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) {
conn, err := net.DialTimeout("tcp", na.DialString(), timeout)
if err != nil {
return nil, err
}
return conn, nil
}
// Routable returns true if the address is routable.
func (na *NetAddress) Routable() bool {
if err := na.Valid(); err != nil {
return false
}
// TODO(oga) bitcoind doesn't include RFC3849 here, but should we?
return !(na.RFC1918() || na.RFC3927() || na.RFC4862() ||
na.RFC4193() || na.RFC4843() || na.Local())
}
// For IPv4 these are either a 0 or all bits set address. For IPv6 a zero
// address or one that matches the RFC3849 documentation address format.
func (na *NetAddress) Valid() error {
if err := validateID(na.ID); err != nil {
return fmt.Errorf("invalid ID: %w", err)
}
if na.IP == nil {
return errors.New("no IP")
}
if na.IP.IsUnspecified() || na.RFC3849() || na.IP.Equal(net.IPv4bcast) {
return errors.New("invalid IP")
}
return nil
}
// HasID returns true if the address has an ID.
// NOTE: It does not check whether the ID is valid or not.
func (na *NetAddress) HasID() bool {
return string(na.ID) != ""
}
// Local returns true if it is a local address.
func (na *NetAddress) Local() bool {
return na.IP.IsLoopback() || zero4.Contains(na.IP)
}
// ReachabilityTo checks whenever o can be reached from na.
func (na *NetAddress) ReachabilityTo(o *NetAddress) int {
const (
Unreachable = 0
Default = iota
Teredo
Ipv6Weak
Ipv4
Ipv6Strong
)
switch {
case !na.Routable():
return Unreachable
case na.RFC4380():
switch {
case !o.Routable():
return Default
case o.RFC4380():
return Teredo
case o.IP.To4() != nil:
return Ipv4
default: // ipv6
return Ipv6Weak
}
case na.IP.To4() != nil:
if o.Routable() && o.IP.To4() != nil {
return Ipv4
}
return Default
default: /* ipv6 */
var tunneled bool
// Is our v6 is tunneled?
if o.RFC3964() || o.RFC6052() || o.RFC6145() {
tunneled = true
}
switch {
case !o.Routable():
return Default
case o.RFC4380():
return Teredo
case o.IP.To4() != nil:
return Ipv4
case tunneled:
// only prioritize ipv6 if we aren't tunneling it.
return Ipv6Weak
}
return Ipv6Strong
}
}
// RFC1918: IPv4 Private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)
// RFC3849: IPv6 Documentation address (2001:0DB8::/32)
// RFC3927: IPv4 Autoconfig (169.254.0.0/16)
// RFC3964: IPv6 6to4 (2002::/16)
// RFC4193: IPv6 unique local (FC00::/7)
// RFC4380: IPv6 Teredo tunneling (2001::/32)
// RFC4843: IPv6 ORCHID: (2001:10::/28)
// RFC4862: IPv6 Autoconfig (FE80::/64)
// RFC6052: IPv6 well known prefix (64:FF9B::/96)
// RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96
var rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)}
var rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)}
var rfc1918_172 = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)}
var rfc3849 = net.IPNet{IP: net.ParseIP("2001:0DB8::"), Mask: net.CIDRMask(32, 128)}
var rfc3927 = net.IPNet{IP: net.ParseIP("169.254.0.0"), Mask: net.CIDRMask(16, 32)}
var rfc3964 = net.IPNet{IP: net.ParseIP("2002::"), Mask: net.CIDRMask(16, 128)}
var rfc4193 = net.IPNet{IP: net.ParseIP("FC00::"), Mask: net.CIDRMask(7, 128)}
var rfc4380 = net.IPNet{IP: net.ParseIP("2001::"), Mask: net.CIDRMask(32, 128)}
var rfc4843 = net.IPNet{IP: net.ParseIP("2001:10::"), Mask: net.CIDRMask(28, 128)}
var rfc4862 = net.IPNet{IP: net.ParseIP("FE80::"), Mask: net.CIDRMask(64, 128)}
var rfc6052 = net.IPNet{IP: net.ParseIP("64:FF9B::"), Mask: net.CIDRMask(96, 128)}
var rfc6145 = net.IPNet{IP: net.ParseIP("::FFFF:0:0:0"), Mask: net.CIDRMask(96, 128)}
var zero4 = net.IPNet{IP: net.ParseIP("0.0.0.0"), Mask: net.CIDRMask(8, 32)}
var (
// onionCatNet defines the IPv6 address block used to support Tor.
// bitcoind encodes a .onion address as a 16 byte number by decoding the
// address prior to the .onion (i.e. the key hash) base32 into a ten
// byte number. It then stores the first 6 bytes of the address as
// 0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43.
//
// This is the same range used by OnionCat, which is part part of the
// RFC4193 unique local IPv6 range.
//
// In summary the format is:
// { magic 6 bytes, 10 bytes base32 decode of key hash }
onionCatNet = ipNet("fd87:d87e:eb43::", 48, 128)
)
// ipNet returns a net.IPNet struct given the passed IP address string, number
// of one bits to include at the start of the mask, and the total number of bits
// for the mask.
func ipNet(ip string, ones, bits int) net.IPNet {
return net.IPNet{IP: net.ParseIP(ip), Mask: net.CIDRMask(ones, bits)}
}
func (na *NetAddress) RFC1918() bool {
return rfc1918_10.Contains(na.IP) ||
rfc1918_192.Contains(na.IP) ||
rfc1918_172.Contains(na.IP)
}
func (na *NetAddress) RFC3849() bool { return rfc3849.Contains(na.IP) }
func (na *NetAddress) RFC3927() bool { return rfc3927.Contains(na.IP) }
func (na *NetAddress) RFC3964() bool { return rfc3964.Contains(na.IP) }
func (na *NetAddress) RFC4193() bool { return rfc4193.Contains(na.IP) }
func (na *NetAddress) RFC4380() bool { return rfc4380.Contains(na.IP) }
func (na *NetAddress) RFC4843() bool { return rfc4843.Contains(na.IP) }
func (na *NetAddress) RFC4862() bool { return rfc4862.Contains(na.IP) }
func (na *NetAddress) RFC6052() bool { return rfc6052.Contains(na.IP) }
func (na *NetAddress) RFC6145() bool { return rfc6145.Contains(na.IP) }
func (na *NetAddress) OnionCatTor() bool { return onionCatNet.Contains(na.IP) }
func removeProtocolIfDefined(addr string) string {
if strings.Contains(addr, "://") {
return strings.Split(addr, "://")[1]
}
return addr
}
func validateID(id ID) error {
if len(id) == 0 {
return errors.New("no ID")
}
idBytes, err := hex.DecodeString(string(id))
if err != nil {
return err
}
if len(idBytes) != IDByteLength {
return fmt.Errorf("invalid hex length - got %d, expected %d", len(idBytes), IDByteLength)
}
return nil
}
package p2p
import (
"fmt"
"net"
"reflect"
"time"
"github.com/cosmos/gogoproto/proto"
"github.com/cometbft/cometbft/libs/cmap"
"github.com/cometbft/cometbft/libs/log"
"github.com/cometbft/cometbft/libs/service"
cmtconn "github.com/cometbft/cometbft/p2p/conn"
)
//go:generate ../scripts/mockery_generate.sh Peer
const metricsTickerDuration = 10 * time.Second
// Peer is an interface representing a peer connected on a reactor.
type Peer interface {
service.Service
FlushStop()
ID() ID // peer's cryptographic ID
RemoteIP() net.IP // remote IP of the connection
RemoteAddr() net.Addr // remote address of the connection
IsOutbound() bool // did we dial the peer
IsPersistent() bool // do we redial this peer when we disconnect
CloseConn() error // close original connection
NodeInfo() NodeInfo // peer's info
Status() cmtconn.ConnectionStatus
SocketAddr() *NetAddress // actual address of the socket
Send(Envelope) bool
TrySend(Envelope) bool
Set(string, interface{})
Get(string) interface{}
SetRemovalFailed()
GetRemovalFailed() bool
}
//----------------------------------------------------------
// peerConn contains the raw connection and its config.
type peerConn struct {
outbound bool
persistent bool
conn net.Conn // source connection
socketAddr *NetAddress
// cached RemoteIP()
ip net.IP
}
func newPeerConn(
outbound, persistent bool,
conn net.Conn,
socketAddr *NetAddress,
) peerConn {
return peerConn{
outbound: outbound,
persistent: persistent,
conn: conn,
socketAddr: socketAddr,
}
}
// ID only exists for SecretConnection.
// NOTE: Will panic if conn is not *SecretConnection.
func (pc peerConn) ID() ID {
return PubKeyToID(pc.conn.(*cmtconn.SecretConnection).RemotePubKey())
}
// Return the IP from the connection RemoteAddr
func (pc peerConn) RemoteIP() net.IP {
if pc.ip != nil {
return pc.ip
}
host, _, err := net.SplitHostPort(pc.conn.RemoteAddr().String())
if err != nil {
panic(err)
}
ips, err := net.LookupIP(host)
if err != nil {
panic(err)
}
pc.ip = ips[0]
return pc.ip
}
// peer implements Peer.
//
// Before using a peer, you will need to perform a handshake on connection.
type peer struct {
service.BaseService
// raw peerConn and the multiplex connection
peerConn
mconn *cmtconn.MConnection
// peer's node info and the channel it knows about
// channels = nodeInfo.Channels
// cached to avoid copying nodeInfo in hasChannel
nodeInfo NodeInfo
channels []byte
// User data
Data *cmap.CMap
metrics *Metrics
metricsTicker *time.Ticker
mlc *metricsLabelCache
// When removal of a peer fails, we set this flag
removalAttemptFailed bool
}
type PeerOption func(*peer)
func newPeer(
pc peerConn,
mConfig cmtconn.MConnConfig,
nodeInfo NodeInfo,
reactorsByCh map[byte]Reactor,
msgTypeByChID map[byte]proto.Message,
chDescs []*cmtconn.ChannelDescriptor,
onPeerError func(Peer, interface{}),
mlc *metricsLabelCache,
options ...PeerOption,
) *peer {
p := &peer{
peerConn: pc,
nodeInfo: nodeInfo,
channels: nodeInfo.(DefaultNodeInfo).Channels,
Data: cmap.NewCMap(),
metricsTicker: time.NewTicker(metricsTickerDuration),
metrics: NopMetrics(),
mlc: mlc,
}
p.mconn = createMConnection(
pc.conn,
p,
reactorsByCh,
msgTypeByChID,
chDescs,
onPeerError,
mConfig,
)
p.BaseService = *service.NewBaseService(nil, "Peer", p)
for _, option := range options {
option(p)
}
return p
}
// String representation.
func (p *peer) String() string {
if p.outbound {
return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.ID())
}
return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.ID())
}
//---------------------------------------------------
// Implements service.Service
// SetLogger implements BaseService.
func (p *peer) SetLogger(l log.Logger) {
p.Logger = l
p.mconn.SetLogger(l)
}
// OnStart implements BaseService.
func (p *peer) OnStart() error {
if err := p.BaseService.OnStart(); err != nil {
return err
}
if err := p.mconn.Start(); err != nil {
return err
}
go p.metricsReporter()
return nil
}
// FlushStop mimics OnStop but additionally ensures that all successful
// .Send() calls will get flushed before closing the connection.
// NOTE: it is not safe to call this method more than once.
func (p *peer) FlushStop() {
p.metricsTicker.Stop()
p.BaseService.OnStop()
p.mconn.FlushStop() // stop everything and close the conn
}
// OnStop implements BaseService.
func (p *peer) OnStop() {
p.metricsTicker.Stop()
p.BaseService.OnStop()
if err := p.mconn.Stop(); err != nil { // stop everything and close the conn
p.Logger.Debug("Error while stopping peer", "err", err)
}
}
//---------------------------------------------------
// Implements Peer
// ID returns the peer's ID - the hex encoded hash of its pubkey.
func (p *peer) ID() ID {
return p.nodeInfo.ID()
}
// IsOutbound returns true if the connection is outbound, false otherwise.
func (p *peer) IsOutbound() bool {
return p.peerConn.outbound
}
// IsPersistent returns true if the peer is persitent, false otherwise.
func (p *peer) IsPersistent() bool {
return p.peerConn.persistent
}
// NodeInfo returns a copy of the peer's NodeInfo.
func (p *peer) NodeInfo() NodeInfo {
return p.nodeInfo
}
// SocketAddr returns the address of the socket.
// For outbound peers, it's the address dialed (after DNS resolution).
// For inbound peers, it's the address returned by the underlying connection
// (not what's reported in the peer's NodeInfo).
func (p *peer) SocketAddr() *NetAddress {
return p.peerConn.socketAddr
}
// Status returns the peer's ConnectionStatus.
func (p *peer) Status() cmtconn.ConnectionStatus {
return p.mconn.Status()
}
// Send msg bytes to the channel identified by chID byte. Returns false if the
// send queue is full after timeout, specified by MConnection.
func (p *peer) Send(e Envelope) bool {
return p.send(e.ChannelID, e.Message, p.mconn.Send)
}
// TrySend msg bytes to the channel identified by chID byte. Immediately returns
// false if the send queue is full.
func (p *peer) TrySend(e Envelope) bool {
return p.send(e.ChannelID, e.Message, p.mconn.TrySend)
}
func (p *peer) send(chID byte, msg proto.Message, sendFunc func(byte, []byte) bool) bool {
if !p.IsRunning() {
return false
} else if !p.hasChannel(chID) {
return false
}
metricLabelValue := p.mlc.ValueToMetricLabel(msg)
if w, ok := msg.(Wrapper); ok {
msg = w.Wrap()
}
msgBytes, err := proto.Marshal(msg)
if err != nil {
p.Logger.Error("marshaling message to send", "error", err)
return false
}
res := sendFunc(chID, msgBytes)
if res {
labels := []string{
"peer_id", string(p.ID()),
"chID", fmt.Sprintf("%#x", chID),
}
p.metrics.PeerSendBytesTotal.With(labels...).Add(float64(len(msgBytes)))
p.metrics.MessageSendBytesTotal.With("message_type", metricLabelValue).Add(float64(len(msgBytes)))
}
return res
}
// Get the data for a given key.
func (p *peer) Get(key string) interface{} {
return p.Data.Get(key)
}
// Set sets the data for the given key.
func (p *peer) Set(key string, data interface{}) {
p.Data.Set(key, data)
}
// hasChannel returns true if the peer reported
// knowing about the given chID.
func (p *peer) hasChannel(chID byte) bool {
for _, ch := range p.channels {
if ch == chID {
return true
}
}
// NOTE: probably will want to remove this
// but could be helpful while the feature is new
p.Logger.Debug(
"Unknown channel for peer",
"channel",
chID,
"channels",
p.channels,
)
return false
}
// CloseConn closes original connection. Used for cleaning up in cases where the peer had not been started at all.
func (p *peer) CloseConn() error {
return p.peerConn.conn.Close()
}
func (p *peer) SetRemovalFailed() {
p.removalAttemptFailed = true
}
func (p *peer) GetRemovalFailed() bool {
return p.removalAttemptFailed
}
//---------------------------------------------------
// methods only used for testing
// TODO: can we remove these?
// CloseConn closes the underlying connection
func (pc *peerConn) CloseConn() {
pc.conn.Close()
}
// RemoteAddr returns peer's remote network address.
func (p *peer) RemoteAddr() net.Addr {
return p.peerConn.conn.RemoteAddr()
}
// CanSend returns true if the send queue is not full, false otherwise.
func (p *peer) CanSend(chID byte) bool {
if !p.IsRunning() {
return false
}
return p.mconn.CanSend(chID)
}
//---------------------------------------------------
func PeerMetrics(metrics *Metrics) PeerOption {
return func(p *peer) {
p.metrics = metrics
}
}
func (p *peer) metricsReporter() {
for {
select {
case <-p.metricsTicker.C:
status := p.mconn.Status()
var sendQueueSize float64
for _, chStatus := range status.Channels {
sendQueueSize += float64(chStatus.SendQueueSize)
}
p.metrics.PeerPendingSendBytes.With("peer_id", string(p.ID())).Set(sendQueueSize)
case <-p.Quit():
return
}
}
}
//------------------------------------------------------------------
// helper funcs
func createMConnection(
conn net.Conn,
p *peer,
reactorsByCh map[byte]Reactor,
msgTypeByChID map[byte]proto.Message,
chDescs []*cmtconn.ChannelDescriptor,
onPeerError func(Peer, interface{}),
config cmtconn.MConnConfig,
) *cmtconn.MConnection {
onReceive := func(chID byte, msgBytes []byte) {
reactor := reactorsByCh[chID]
if reactor == nil {
// Note that its ok to panic here as it's caught in the conn._recover,
// which does onPeerError.
panic(fmt.Sprintf("Unknown channel %X", chID))
}
mt := msgTypeByChID[chID]
msg := proto.Clone(mt)
err := proto.Unmarshal(msgBytes, msg)
if err != nil {
panic(fmt.Errorf("unmarshaling message: %s into type: %s", err, reflect.TypeOf(mt)))
}
labels := []string{
"peer_id", string(p.ID()),
"chID", fmt.Sprintf("%#x", chID),
}
if w, ok := msg.(Unwrapper); ok {
msg, err = w.Unwrap()
if err != nil {
panic(fmt.Errorf("unwrapping message: %s", err))
}
}
p.metrics.PeerReceiveBytesTotal.With(labels...).Add(float64(len(msgBytes)))
p.metrics.MessageReceiveBytesTotal.With("message_type", p.mlc.ValueToMetricLabel(msg)).Add(float64(len(msgBytes)))
reactor.Receive(Envelope{
ChannelID: chID,
Src: p,
Message: msg,
})
}
onError := func(r interface{}) {
onPeerError(p, r)
}
return cmtconn.NewMConnectionWithConfig(
conn,
chDescs,
onReceive,
onError,
config,
)
}
package p2p
import (
"net"
cmtsync "github.com/cometbft/cometbft/libs/sync"
)
// IPeerSet has a (immutable) subset of the methods of PeerSet.
type IPeerSet interface {
Has(key ID) bool
HasIP(ip net.IP) bool
Get(key ID) Peer
List() []Peer
Size() int
}
//-----------------------------------------------------------------------------
// PeerSet is a special structure for keeping a table of peers.
// Iteration over the peers is super fast and thread-safe.
type PeerSet struct {
mtx cmtsync.Mutex
lookup map[ID]*peerSetItem
list []Peer
}
type peerSetItem struct {
peer Peer
index int
}
// NewPeerSet creates a new peerSet with a list of initial capacity of 256 items.
func NewPeerSet() *PeerSet {
return &PeerSet{
lookup: make(map[ID]*peerSetItem),
list: make([]Peer, 0, 256),
}
}
// Add adds the peer to the PeerSet.
// It returns an error carrying the reason, if the peer is already present.
func (ps *PeerSet) Add(peer Peer) error {
ps.mtx.Lock()
defer ps.mtx.Unlock()
if ps.lookup[peer.ID()] != nil {
return ErrSwitchDuplicatePeerID{peer.ID()}
}
if peer.GetRemovalFailed() {
return ErrPeerRemoval{}
}
index := len(ps.list)
// Appending is safe even with other goroutines
// iterating over the ps.list slice.
ps.list = append(ps.list, peer)
ps.lookup[peer.ID()] = &peerSetItem{peer, index}
return nil
}
// Has returns true if the set contains the peer referred to by this
// peerKey, otherwise false.
func (ps *PeerSet) Has(peerKey ID) bool {
ps.mtx.Lock()
_, ok := ps.lookup[peerKey]
ps.mtx.Unlock()
return ok
}
// HasIP returns true if the set contains the peer referred to by this IP
// address, otherwise false.
func (ps *PeerSet) HasIP(peerIP net.IP) bool {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return ps.hasIP(peerIP)
}
// hasIP does not acquire a lock so it can be used in public methods which
// already lock.
func (ps *PeerSet) hasIP(peerIP net.IP) bool {
for _, item := range ps.lookup {
if item.peer.RemoteIP().Equal(peerIP) {
return true
}
}
return false
}
// Get looks up a peer by the provided peerKey. Returns nil if peer is not
// found.
func (ps *PeerSet) Get(peerKey ID) Peer {
ps.mtx.Lock()
defer ps.mtx.Unlock()
item, ok := ps.lookup[peerKey]
if ok {
return item.peer
}
return nil
}
// Remove discards peer by its Key, if the peer was previously memoized.
// Returns true if the peer was removed, and false if it was not found.
// in the set.
func (ps *PeerSet) Remove(peer Peer) bool {
ps.mtx.Lock()
defer ps.mtx.Unlock()
item := ps.lookup[peer.ID()]
if item == nil {
// Removing the peer has failed so we set a flag to mark that a removal was attempted.
// This can happen when the peer add routine from the switch is running in
// parallel to the receive routine of MConn.
// There is an error within MConn but the switch has not actually added the peer to the peer set yet.
// Setting this flag will prevent a peer from being added to a node's peer set afterwards.
peer.SetRemovalFailed()
return false
}
index := item.index
// Create a new copy of the list but with one less item.
// (we must copy because we'll be mutating the list).
newList := make([]Peer, len(ps.list)-1)
copy(newList, ps.list)
// If it's the last peer, that's an easy special case.
if index == len(ps.list)-1 {
ps.list = newList
delete(ps.lookup, peer.ID())
return true
}
// Replace the popped item with the last item in the old list.
lastPeer := ps.list[len(ps.list)-1]
lastPeerKey := lastPeer.ID()
lastPeerItem := ps.lookup[lastPeerKey]
newList[index] = lastPeer
lastPeerItem.index = index
ps.list = newList
delete(ps.lookup, peer.ID())
return true
}
// Size returns the number of unique items in the peerSet.
func (ps *PeerSet) Size() int {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return len(ps.list)
}
// List returns the threadsafe list of peers.
func (ps *PeerSet) List() []Peer {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return ps.list
}
// Modified for CometBFT
// Originally Copyright (c) 2013-2014 Conformal Systems LLC.
// https://github.com/conformal/btcd/blob/master/LICENSE
package pex
import (
"encoding/binary"
"fmt"
"hash"
"math"
"math/rand"
"net"
"sync"
"time"
"github.com/minio/highwayhash"
"github.com/cometbft/cometbft/crypto"
"github.com/cometbft/cometbft/libs/log"
cmtmath "github.com/cometbft/cometbft/libs/math"
cmtrand "github.com/cometbft/cometbft/libs/rand"
"github.com/cometbft/cometbft/libs/service"
cmtsync "github.com/cometbft/cometbft/libs/sync"
"github.com/cometbft/cometbft/p2p"
)
const (
bucketTypeNew = 0x01
bucketTypeOld = 0x02
)
// AddrBook is an address book used for tracking peers
// so we can gossip about them to others and select
// peers to dial.
// TODO: break this up?
type AddrBook interface {
service.Service
// Add our own addresses so we don't later add ourselves
AddOurAddress(*p2p.NetAddress)
// Check if it is our address
OurAddress(*p2p.NetAddress) bool
AddPrivateIDs([]string)
// Add and remove an address
AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error
RemoveAddress(*p2p.NetAddress)
// Check if the address is in the book
HasAddress(*p2p.NetAddress) bool
// Do we need more peers?
NeedMoreAddrs() bool
// Is Address Book Empty? Answer should not depend on being in your own
// address book, or private peers
Empty() bool
// Pick an address to dial
PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress
// Mark address
MarkGood(p2p.ID)
MarkAttempt(*p2p.NetAddress)
MarkBad(*p2p.NetAddress, time.Duration) // Move peer to bad peers list
// Add bad peers back to addrBook
ReinstateBadPeers()
IsGood(*p2p.NetAddress) bool
IsBanned(*p2p.NetAddress) bool
// Send a selection of addresses to peers
GetSelection() []*p2p.NetAddress
// Send a selection of addresses with bias
GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress
Size() int
// Persist to disk
Save()
}
var _ AddrBook = (*addrBook)(nil)
// addrBook - concurrency safe peer address manager.
// Implements AddrBook.
type addrBook struct {
service.BaseService
// accessed concurrently
mtx cmtsync.Mutex
rand *cmtrand.Rand
ourAddrs map[string]struct{}
privateIDs map[p2p.ID]struct{}
addrLookup map[p2p.ID]*knownAddress // new & old
badPeers map[p2p.ID]*knownAddress // blacklisted peers
bucketsOld []map[string]*knownAddress
bucketsNew []map[string]*knownAddress
nOld int
nNew int
// immutable after creation
filePath string
key string // random prefix for bucket placement
routabilityStrict bool
hasher hash.Hash64
wg sync.WaitGroup
}
func mustNewHasher() hash.Hash64 {
key := crypto.CRandBytes(highwayhash.Size)
hasher, err := highwayhash.New64(key)
if err != nil {
panic(err)
}
return hasher
}
// NewAddrBook creates a new address book.
// Use Start to begin processing asynchronous address updates.
func NewAddrBook(filePath string, routabilityStrict bool) AddrBook {
am := &addrBook{
rand: cmtrand.NewRand(),
ourAddrs: make(map[string]struct{}),
privateIDs: make(map[p2p.ID]struct{}),
addrLookup: make(map[p2p.ID]*knownAddress),
badPeers: make(map[p2p.ID]*knownAddress),
filePath: filePath,
routabilityStrict: routabilityStrict,
}
am.init()
am.BaseService = *service.NewBaseService(nil, "AddrBook", am)
return am
}
// Initialize the buckets.
// When modifying this, don't forget to update loadFromFile()
func (a *addrBook) init() {
a.key = crypto.CRandHex(24) // 24/2 * 8 = 96 bits
// New addr buckets
a.bucketsNew = make([]map[string]*knownAddress, newBucketCount)
for i := range a.bucketsNew {
a.bucketsNew[i] = make(map[string]*knownAddress)
}
// Old addr buckets
a.bucketsOld = make([]map[string]*knownAddress, oldBucketCount)
for i := range a.bucketsOld {
a.bucketsOld[i] = make(map[string]*knownAddress)
}
a.hasher = mustNewHasher()
}
// OnStart implements Service.
func (a *addrBook) OnStart() error {
if err := a.BaseService.OnStart(); err != nil {
return err
}
a.loadFromFile(a.filePath)
// wg.Add to ensure that any invocation of .Wait()
// later on will wait for saveRoutine to terminate.
a.wg.Add(1)
go a.saveRoutine()
return nil
}
// OnStop implements Service.
func (a *addrBook) OnStop() {
a.BaseService.OnStop()
}
func (a *addrBook) Wait() {
a.wg.Wait()
}
func (a *addrBook) FilePath() string {
return a.filePath
}
//-------------------------------------------------------
// AddOurAddress one of our addresses.
func (a *addrBook) AddOurAddress(addr *p2p.NetAddress) {
a.mtx.Lock()
defer a.mtx.Unlock()
a.Logger.Info("Add our address to book", "addr", addr)
a.ourAddrs[addr.String()] = struct{}{}
}
// OurAddress returns true if it is our address.
func (a *addrBook) OurAddress(addr *p2p.NetAddress) bool {
a.mtx.Lock()
defer a.mtx.Unlock()
_, ok := a.ourAddrs[addr.String()]
return ok
}
func (a *addrBook) AddPrivateIDs(ids []string) {
a.mtx.Lock()
defer a.mtx.Unlock()
for _, id := range ids {
a.privateIDs[p2p.ID(id)] = struct{}{}
}
}
// AddAddress implements AddrBook
// Add address to a "new" bucket. If it's already in one, only add it probabilistically.
// Returns error if the addr is non-routable. Does not add self.
// NOTE: addr must not be nil
func (a *addrBook) AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error {
a.mtx.Lock()
defer a.mtx.Unlock()
return a.addAddress(addr, src)
}
// RemoveAddress implements AddrBook - removes the address from the book.
func (a *addrBook) RemoveAddress(addr *p2p.NetAddress) {
a.mtx.Lock()
defer a.mtx.Unlock()
a.removeAddress(addr)
}
// IsGood returns true if peer was ever marked as good and haven't
// done anything wrong since then.
func (a *addrBook) IsGood(addr *p2p.NetAddress) bool {
a.mtx.Lock()
defer a.mtx.Unlock()
return a.addrLookup[addr.ID].isOld()
}
// IsBanned returns true if the peer is currently banned
func (a *addrBook) IsBanned(addr *p2p.NetAddress) bool {
a.mtx.Lock()
_, ok := a.badPeers[addr.ID]
a.mtx.Unlock()
return ok
}
// HasAddress returns true if the address is in the book.
func (a *addrBook) HasAddress(addr *p2p.NetAddress) bool {
a.mtx.Lock()
defer a.mtx.Unlock()
ka := a.addrLookup[addr.ID]
return ka != nil
}
// NeedMoreAddrs implements AddrBook - returns true if there are not have enough addresses in the book.
func (a *addrBook) NeedMoreAddrs() bool {
return a.Size() < needAddressThreshold
}
// Empty implements AddrBook - returns true if there are no addresses in the address book.
// Does not count the peer appearing in its own address book, or private peers.
func (a *addrBook) Empty() bool {
return a.Size() == 0
}
// PickAddress implements AddrBook. It picks an address to connect to.
// The address is picked randomly from an old or new bucket according
// to the biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to that range)
// and determines how biased we are to pick an address from a new bucket.
// PickAddress returns nil if the AddrBook is empty or if we try to pick
// from an empty bucket.
func (a *addrBook) PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress {
a.mtx.Lock()
defer a.mtx.Unlock()
bookSize := a.size()
if bookSize <= 0 {
if bookSize < 0 {
panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld))
}
return nil
}
if biasTowardsNewAddrs > 100 {
biasTowardsNewAddrs = 100
}
if biasTowardsNewAddrs < 0 {
biasTowardsNewAddrs = 0
}
// Bias between new and old addresses.
oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(biasTowardsNewAddrs))
newCorrelation := math.Sqrt(float64(a.nNew)) * float64(biasTowardsNewAddrs)
// pick a random peer from a random bucket
var bucket map[string]*knownAddress
pickFromOldBucket := (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation
if (pickFromOldBucket && a.nOld == 0) ||
(!pickFromOldBucket && a.nNew == 0) {
return nil
}
// loop until we pick a random non-empty bucket
for len(bucket) == 0 {
if pickFromOldBucket {
bucket = a.bucketsOld[a.rand.Intn(len(a.bucketsOld))]
} else {
bucket = a.bucketsNew[a.rand.Intn(len(a.bucketsNew))]
}
}
// pick a random index and loop over the map to return that index
randIndex := a.rand.Intn(len(bucket))
for _, ka := range bucket {
if randIndex == 0 {
return ka.Addr
}
randIndex--
}
return nil
}
// MarkGood implements AddrBook - it marks the peer as good and
// moves it into an "old" bucket.
func (a *addrBook) MarkGood(id p2p.ID) {
a.mtx.Lock()
defer a.mtx.Unlock()
ka := a.addrLookup[id]
if ka == nil {
return
}
ka.markGood()
if ka.isNew() {
if err := a.moveToOld(ka); err != nil {
a.Logger.Error("Error moving address to old", "err", err)
}
}
}
// MarkAttempt implements AddrBook - it marks that an attempt was made to connect to the address.
func (a *addrBook) MarkAttempt(addr *p2p.NetAddress) {
a.mtx.Lock()
defer a.mtx.Unlock()
ka := a.addrLookup[addr.ID]
if ka == nil {
return
}
ka.markAttempt()
}
// MarkBad implements AddrBook. Kicks address out from book, places
// the address in the badPeers pool.
func (a *addrBook) MarkBad(addr *p2p.NetAddress, banTime time.Duration) {
a.mtx.Lock()
defer a.mtx.Unlock()
if a.addBadPeer(addr, banTime) {
a.removeAddress(addr)
}
}
// ReinstateBadPeers removes bad peers from ban list and places them into a new
// bucket.
func (a *addrBook) ReinstateBadPeers() {
a.mtx.Lock()
defer a.mtx.Unlock()
for _, ka := range a.badPeers {
if ka.isBanned() {
continue
}
bucket, err := a.calcNewBucket(ka.Addr, ka.Src)
if err != nil {
a.Logger.Error("Failed to calculate new bucket (bad peer won't be reinstantiated)",
"addr", ka.Addr, "err", err)
continue
}
if err := a.addToNewBucket(ka, bucket); err != nil {
a.Logger.Error("Error adding peer to new bucket", "err", err)
}
delete(a.badPeers, ka.ID())
a.Logger.Info("Reinstated address", "addr", ka.Addr)
}
}
// GetSelection implements AddrBook.
// It randomly selects some addresses (old & new). Suitable for peer-exchange protocols.
// Must never return a nil address.
func (a *addrBook) GetSelection() []*p2p.NetAddress {
a.mtx.Lock()
defer a.mtx.Unlock()
bookSize := a.size()
if bookSize <= 0 {
if bookSize < 0 {
panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld))
}
return nil
}
numAddresses := cmtmath.MaxInt(
cmtmath.MinInt(minGetSelection, bookSize),
bookSize*getSelectionPercent/100)
numAddresses = cmtmath.MinInt(maxGetSelection, numAddresses)
// XXX: instead of making a list of all addresses, shuffling, and slicing a random chunk,
// could we just select a random numAddresses of indexes?
allAddr := make([]*p2p.NetAddress, bookSize)
i := 0
for _, ka := range a.addrLookup {
allAddr[i] = ka.Addr
i++
}
// Fisher-Yates shuffle the array. We only need to do the first
// `numAddresses' since we are throwing the rest.
for i := 0; i < numAddresses; i++ {
// pick a number between current index and the end
j := cmtrand.Intn(len(allAddr)-i) + i
allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
}
// slice off the limit we are willing to share.
return allAddr[:numAddresses]
}
func percentageOfNum(p, n int) int {
return int(math.Round((float64(p) / float64(100)) * float64(n)))
}
// GetSelectionWithBias implements AddrBook.
// It randomly selects some addresses (old & new). Suitable for peer-exchange protocols.
// Must never return a nil address.
//
// Each address is picked randomly from an old or new bucket according to the
// biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to
// that range) and determines how biased we are to pick an address from a new
// bucket.
func (a *addrBook) GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress {
a.mtx.Lock()
defer a.mtx.Unlock()
bookSize := a.size()
if bookSize <= 0 {
if bookSize < 0 {
panic(fmt.Sprintf("Addrbook size %d (new: %d + old: %d) is less than 0", a.nNew+a.nOld, a.nNew, a.nOld))
}
return nil
}
if biasTowardsNewAddrs > 100 {
biasTowardsNewAddrs = 100
}
if biasTowardsNewAddrs < 0 {
biasTowardsNewAddrs = 0
}
numAddresses := cmtmath.MaxInt(
cmtmath.MinInt(minGetSelection, bookSize),
bookSize*getSelectionPercent/100)
numAddresses = cmtmath.MinInt(maxGetSelection, numAddresses)
// number of new addresses that, if possible, should be in the beginning of the selection
// if there are no enough old addrs, will choose new addr instead.
numRequiredNewAdd := cmtmath.MaxInt(percentageOfNum(biasTowardsNewAddrs, numAddresses), numAddresses-a.nOld)
selection := a.randomPickAddresses(bucketTypeNew, numRequiredNewAdd)
selection = append(selection, a.randomPickAddresses(bucketTypeOld, numAddresses-len(selection))...)
return selection
}
//------------------------------------------------
// Size returns the number of addresses in the book.
func (a *addrBook) Size() int {
a.mtx.Lock()
defer a.mtx.Unlock()
return a.size()
}
func (a *addrBook) size() int {
return a.nNew + a.nOld
}
//----------------------------------------------------------
// Save persists the address book to disk.
func (a *addrBook) Save() {
a.saveToFile(a.filePath) // thread safe
}
func (a *addrBook) saveRoutine() {
defer a.wg.Done()
saveFileTicker := time.NewTicker(dumpAddressInterval)
out:
for {
select {
case <-saveFileTicker.C:
a.saveToFile(a.filePath)
case <-a.Quit():
break out
}
}
saveFileTicker.Stop()
a.saveToFile(a.filePath)
}
//----------------------------------------------------------
func (a *addrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress {
switch bucketType {
case bucketTypeNew:
return a.bucketsNew[bucketIdx]
case bucketTypeOld:
return a.bucketsOld[bucketIdx]
default:
panic("Invalid bucket type")
}
}
// Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full.
// NOTE: currently it always returns true.
func (a *addrBook) addToNewBucket(ka *knownAddress, bucketIdx int) error {
// Consistency check to ensure we don't add an already known address
if ka.isOld() {
return errAddrBookOldAddressNewBucket{ka.Addr, bucketIdx}
}
addrStr := ka.Addr.String()
bucket := a.getBucket(bucketTypeNew, bucketIdx)
// Already exists?
if _, ok := bucket[addrStr]; ok {
return nil
}
// Enforce max addresses.
if len(bucket) > newBucketSize {
a.Logger.Info("new bucket is full, expiring new")
a.expireNew(bucketIdx)
}
// Add to bucket.
bucket[addrStr] = ka
// increment nNew if the peer doesnt already exist in a bucket
if ka.addBucketRef(bucketIdx) == 1 {
a.nNew++
}
// Add it to addrLookup
a.addrLookup[ka.ID()] = ka
return nil
}
// Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full.
func (a *addrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool {
// Sanity check
if ka.isNew() {
a.Logger.Error(fmt.Sprintf("Cannot add new address to old bucket: %v", ka))
return false
}
if len(ka.Buckets) != 0 {
a.Logger.Error(fmt.Sprintf("Cannot add already old address to another old bucket: %v", ka))
return false
}
addrStr := ka.Addr.String()
bucket := a.getBucket(bucketTypeOld, bucketIdx)
// Already exists?
if _, ok := bucket[addrStr]; ok {
return true
}
// Enforce max addresses.
if len(bucket) > oldBucketSize {
return false
}
// Add to bucket.
bucket[addrStr] = ka
if ka.addBucketRef(bucketIdx) == 1 {
a.nOld++
}
// Ensure in addrLookup
a.addrLookup[ka.ID()] = ka
return true
}
func (a *addrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) {
if ka.BucketType != bucketType {
a.Logger.Error(fmt.Sprintf("Bucket type mismatch: %v", ka))
return
}
bucket := a.getBucket(bucketType, bucketIdx)
delete(bucket, ka.Addr.String())
if ka.removeBucketRef(bucketIdx) == 0 {
if bucketType == bucketTypeNew {
a.nNew--
} else {
a.nOld--
}
delete(a.addrLookup, ka.ID())
}
}
func (a *addrBook) removeFromAllBuckets(ka *knownAddress) {
for _, bucketIdx := range ka.Buckets {
bucket := a.getBucket(ka.BucketType, bucketIdx)
delete(bucket, ka.Addr.String())
}
ka.Buckets = nil
if ka.BucketType == bucketTypeNew {
a.nNew--
} else {
a.nOld--
}
delete(a.addrLookup, ka.ID())
}
//----------------------------------------------------------
func (a *addrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress {
bucket := a.getBucket(bucketType, bucketIdx)
var oldest *knownAddress
for _, ka := range bucket {
if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) {
oldest = ka
}
}
return oldest
}
// adds the address to a "new" bucket. if its already in one,
// it only adds it probabilistically
func (a *addrBook) addAddress(addr, src *p2p.NetAddress) error {
if addr == nil || src == nil {
return ErrAddrBookNilAddr{addr, src}
}
if err := addr.Valid(); err != nil {
return ErrAddrBookInvalidAddr{Addr: addr, AddrErr: err}
}
if _, ok := a.badPeers[addr.ID]; ok {
return ErrAddressBanned{addr}
}
if _, ok := a.privateIDs[addr.ID]; ok {
return ErrAddrBookPrivate{addr}
}
if _, ok := a.privateIDs[src.ID]; ok {
return ErrAddrBookPrivateSrc{src}
}
// TODO: we should track ourAddrs by ID and by IP:PORT and refuse both.
if _, ok := a.ourAddrs[addr.String()]; ok {
return ErrAddrBookSelf{addr}
}
if a.routabilityStrict && !addr.Routable() {
return ErrAddrBookNonRoutable{addr}
}
ka := a.addrLookup[addr.ID]
if ka != nil {
// If its already old and the address ID's are the same, ignore it.
// Thereby avoiding issues with a node on the network attempting to change
// the IP of a known node ID. (Which could yield an eclipse attack on the node)
if ka.isOld() && ka.Addr.ID == addr.ID {
return nil
}
// Already in max new buckets.
if len(ka.Buckets) == maxNewBucketsPerAddress {
return nil
}
// The more entries we have, the less likely we are to add more.
factor := int32(2 * len(ka.Buckets))
if a.rand.Int31n(factor) != 0 {
return nil
}
} else {
ka = newKnownAddress(addr, src)
}
bucket, err := a.calcNewBucket(addr, src)
if err != nil {
return err
}
return a.addToNewBucket(ka, bucket)
}
func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*p2p.NetAddress {
var buckets []map[string]*knownAddress
switch bucketType {
case bucketTypeNew:
buckets = a.bucketsNew
case bucketTypeOld:
buckets = a.bucketsOld
default:
panic("unexpected bucketType")
}
total := 0
for _, bucket := range buckets {
total += len(bucket)
}
addresses := make([]*knownAddress, 0, total)
for _, bucket := range buckets {
for _, ka := range bucket {
addresses = append(addresses, ka)
}
}
selection := make([]*p2p.NetAddress, 0, num)
chosenSet := make(map[string]bool, num)
rand.Shuffle(total, func(i, j int) {
addresses[i], addresses[j] = addresses[j], addresses[i]
})
for _, addr := range addresses {
if chosenSet[addr.Addr.String()] {
continue
}
chosenSet[addr.Addr.String()] = true
selection = append(selection, addr.Addr)
if len(selection) >= num {
return selection
}
}
return selection
}
// Make space in the new buckets by expiring the really bad entries.
// If no bad entries are available we remove the oldest.
func (a *addrBook) expireNew(bucketIdx int) {
for addrStr, ka := range a.bucketsNew[bucketIdx] {
// If an entry is bad, throw it away
if ka.isBad() {
a.Logger.Info("expire new", "msg", log.NewLazySprintf("expiring bad address %v", addrStr))
a.removeFromBucket(ka, bucketTypeNew, bucketIdx)
return
}
}
// If we haven't thrown out a bad entry, throw out the oldest entry
oldest := a.pickOldest(bucketTypeNew, bucketIdx)
a.removeFromBucket(oldest, bucketTypeNew, bucketIdx)
}
// Promotes an address from new to old. If the destination bucket is full,
// demote the oldest one to a "new" bucket.
// TODO: Demote more probabilistically?
func (a *addrBook) moveToOld(ka *knownAddress) error {
// Sanity check
if ka.isOld() {
a.Logger.Error(fmt.Sprintf("Cannot promote address that is already old %v", ka))
return nil
}
if len(ka.Buckets) == 0 {
a.Logger.Error(fmt.Sprintf("Cannot promote address that isn't in any new buckets %v", ka))
return nil
}
// Remove from all (new) buckets.
a.removeFromAllBuckets(ka)
// It's officially old now.
ka.BucketType = bucketTypeOld
// Try to add it to its oldBucket destination.
oldBucketIdx, err := a.calcOldBucket(ka.Addr)
if err != nil {
return err
}
added := a.addToOldBucket(ka, oldBucketIdx)
if !added {
// No room; move the oldest to a new bucket
oldest := a.pickOldest(bucketTypeOld, oldBucketIdx)
a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx)
newBucketIdx, err := a.calcNewBucket(oldest.Addr, oldest.Src)
if err != nil {
return err
}
if err := a.addToNewBucket(oldest, newBucketIdx); err != nil {
a.Logger.Error("Error adding peer to old bucket", "err", err)
}
// Finally, add our ka to old bucket again.
added = a.addToOldBucket(ka, oldBucketIdx)
if !added {
a.Logger.Error(fmt.Sprintf("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx))
}
}
return nil
}
func (a *addrBook) removeAddress(addr *p2p.NetAddress) {
ka := a.addrLookup[addr.ID]
if ka == nil {
return
}
a.Logger.Info("Remove address from book", "addr", addr)
a.removeFromAllBuckets(ka)
}
func (a *addrBook) addBadPeer(addr *p2p.NetAddress, banTime time.Duration) bool {
// check it exists in addrbook
ka := a.addrLookup[addr.ID]
// check address is not already there
if ka == nil {
return false
}
if _, alreadyBadPeer := a.badPeers[addr.ID]; !alreadyBadPeer {
// add to bad peer list
ka.ban(banTime)
a.badPeers[addr.ID] = ka
a.Logger.Info("Add address to blacklist", "addr", addr)
}
return true
}
//---------------------------------------------------------------------
// calculate bucket placements
// hash(key + sourcegroup + int64(hash(key + group + sourcegroup)) % bucket_per_group) % num_new_buckets
func (a *addrBook) calcNewBucket(addr, src *p2p.NetAddress) (int, error) {
data1 := []byte{}
data1 = append(data1, []byte(a.key)...)
data1 = append(data1, []byte(a.groupKey(addr))...)
data1 = append(data1, []byte(a.groupKey(src))...)
hash1, err := a.hash(data1)
if err != nil {
return 0, err
}
hash64 := binary.BigEndian.Uint64(hash1)
hash64 %= newBucketsPerGroup
var hashbuf [8]byte
binary.BigEndian.PutUint64(hashbuf[:], hash64)
data2 := []byte{}
data2 = append(data2, []byte(a.key)...)
data2 = append(data2, a.groupKey(src)...)
data2 = append(data2, hashbuf[:]...)
hash2, err := a.hash(data2)
if err != nil {
return 0, err
}
result := int(binary.BigEndian.Uint64(hash2) % newBucketCount)
return result, nil
}
// hash(key + group + int64(hash(key + addr)) % buckets_per_group) % num_old_buckets
func (a *addrBook) calcOldBucket(addr *p2p.NetAddress) (int, error) {
data1 := []byte{}
data1 = append(data1, []byte(a.key)...)
data1 = append(data1, []byte(addr.String())...)
hash1, err := a.hash(data1)
if err != nil {
return 0, err
}
hash64 := binary.BigEndian.Uint64(hash1)
hash64 %= oldBucketsPerGroup
var hashbuf [8]byte
binary.BigEndian.PutUint64(hashbuf[:], hash64)
data2 := []byte{}
data2 = append(data2, []byte(a.key)...)
data2 = append(data2, a.groupKey(addr)...)
data2 = append(data2, hashbuf[:]...)
hash2, err := a.hash(data2)
if err != nil {
return 0, err
}
result := int(binary.BigEndian.Uint64(hash2) % oldBucketCount)
return result, nil
}
// Return a string representing the network group of this address.
// This is the /16 for IPv4 (e.g. 1.2.0.0), the /32 (/36 for he.net) for IPv6, the string
// "local" for a local address and the string "unroutable" for an unroutable
// address.
func (a *addrBook) groupKey(na *p2p.NetAddress) string {
return groupKeyFor(na, a.routabilityStrict)
}
func groupKeyFor(na *p2p.NetAddress, routabilityStrict bool) string {
if routabilityStrict && na.Local() {
return "local"
}
if routabilityStrict && !na.Routable() {
return "unroutable"
}
if ipv4 := na.IP.To4(); ipv4 != nil {
return na.IP.Mask(net.CIDRMask(16, 32)).String()
}
if na.RFC6145() || na.RFC6052() {
// last four bytes are the ip address
ip := na.IP[12:16]
return ip.Mask(net.CIDRMask(16, 32)).String()
}
if na.RFC3964() {
ip := na.IP[2:6]
return ip.Mask(net.CIDRMask(16, 32)).String()
}
if na.RFC4380() {
// teredo tunnels have the last 4 bytes as the v4 address XOR
// 0xff.
ip := net.IP(make([]byte, 4))
for i, byte := range na.IP[12:16] {
ip[i] = byte ^ 0xff
}
return ip.Mask(net.CIDRMask(16, 32)).String()
}
if na.OnionCatTor() {
// group is keyed off the first 4 bits of the actual onion key.
return fmt.Sprintf("tor:%d", na.IP[6]&((1<<4)-1))
}
// OK, so now we know ourselves to be a IPv6 address.
// bitcoind uses /32 for everything, except for Hurricane Electric's
// (he.net) IP range, which it uses /36 for.
bits := 32
heNet := &net.IPNet{IP: net.ParseIP("2001:470::"), Mask: net.CIDRMask(32, 128)}
if heNet.Contains(na.IP) {
bits = 36
}
ipv6Mask := net.CIDRMask(bits, 128)
return na.IP.Mask(ipv6Mask).String()
}
func (a *addrBook) hash(b []byte) ([]byte, error) {
a.hasher.Reset()
a.hasher.Write(b)
return a.hasher.Sum(nil), nil
}
package pex
import (
"errors"
"fmt"
"github.com/cometbft/cometbft/p2p"
)
type ErrAddrBookNonRoutable struct {
Addr *p2p.NetAddress
}
func (err ErrAddrBookNonRoutable) Error() string {
return fmt.Sprintf("Cannot add non-routable address %v", err.Addr)
}
type errAddrBookOldAddressNewBucket struct {
Addr *p2p.NetAddress
BucketID int
}
func (err errAddrBookOldAddressNewBucket) Error() string {
return fmt.Sprintf("failed consistency check!"+
" Cannot add pre-existing address %v into new bucket %v",
err.Addr, err.BucketID)
}
type ErrAddrBookSelf struct {
Addr *p2p.NetAddress
}
func (err ErrAddrBookSelf) Error() string {
return fmt.Sprintf("Cannot add ourselves with address %v", err.Addr)
}
type ErrAddrBookPrivate struct {
Addr *p2p.NetAddress
}
func (err ErrAddrBookPrivate) Error() string {
return fmt.Sprintf("Cannot add private peer with address %v", err.Addr)
}
func (err ErrAddrBookPrivate) PrivateAddr() bool {
return true
}
type ErrAddrBookPrivateSrc struct {
Src *p2p.NetAddress
}
func (err ErrAddrBookPrivateSrc) Error() string {
return fmt.Sprintf("Cannot add peer coming from private peer with address %v", err.Src)
}
func (err ErrAddrBookPrivateSrc) PrivateAddr() bool {
return true
}
type ErrAddrBookNilAddr struct {
Addr *p2p.NetAddress
Src *p2p.NetAddress
}
func (err ErrAddrBookNilAddr) Error() string {
return fmt.Sprintf("Cannot add a nil address. Got (addr, src) = (%v, %v)", err.Addr, err.Src)
}
type ErrAddrBookInvalidAddr struct {
Addr *p2p.NetAddress
AddrErr error
}
func (err ErrAddrBookInvalidAddr) Error() string {
return fmt.Sprintf("Cannot add invalid address %v: %v", err.Addr, err.AddrErr)
}
// ErrAddressBanned is thrown when the address has been banned and therefore cannot be used
type ErrAddressBanned struct {
Addr *p2p.NetAddress
}
func (err ErrAddressBanned) Error() string {
return fmt.Sprintf("Address: %v is currently banned", err.Addr)
}
// ErrUnsolicitedList is thrown when a peer provides a list of addresses that have not been asked for.
var ErrUnsolicitedList = errors.New("unsolicited pexAddrsMessage")
package pex
import (
"time"
"github.com/cometbft/cometbft/p2p"
)
// knownAddress tracks information about a known network address
// that is used to determine how viable an address is.
type knownAddress struct {
Addr *p2p.NetAddress `json:"addr"`
Src *p2p.NetAddress `json:"src"`
Buckets []int `json:"buckets"`
Attempts int32 `json:"attempts"`
BucketType byte `json:"bucket_type"`
LastAttempt time.Time `json:"last_attempt"`
LastSuccess time.Time `json:"last_success"`
LastBanTime time.Time `json:"last_ban_time"`
}
func newKnownAddress(addr *p2p.NetAddress, src *p2p.NetAddress) *knownAddress {
return &knownAddress{
Addr: addr,
Src: src,
Attempts: 0,
LastAttempt: time.Now(),
BucketType: bucketTypeNew,
Buckets: nil,
}
}
func (ka *knownAddress) ID() p2p.ID {
return ka.Addr.ID
}
func (ka *knownAddress) isOld() bool {
return ka.BucketType == bucketTypeOld
}
func (ka *knownAddress) isNew() bool {
return ka.BucketType == bucketTypeNew
}
func (ka *knownAddress) markAttempt() {
now := time.Now()
ka.LastAttempt = now
ka.Attempts++
}
func (ka *knownAddress) markGood() {
now := time.Now()
ka.LastAttempt = now
ka.Attempts = 0
ka.LastSuccess = now
}
func (ka *knownAddress) ban(banTime time.Duration) {
if ka.LastBanTime.Before(time.Now().Add(banTime)) {
ka.LastBanTime = time.Now().Add(banTime)
}
}
func (ka *knownAddress) isBanned() bool {
return ka.LastBanTime.After(time.Now())
}
func (ka *knownAddress) addBucketRef(bucketIdx int) int {
for _, bucket := range ka.Buckets {
if bucket == bucketIdx {
// TODO refactor to return error?
// log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka))
return -1
}
}
ka.Buckets = append(ka.Buckets, bucketIdx)
return len(ka.Buckets)
}
func (ka *knownAddress) removeBucketRef(bucketIdx int) int {
buckets := []int{}
for _, bucket := range ka.Buckets {
if bucket != bucketIdx {
buckets = append(buckets, bucket)
}
}
if len(buckets) != len(ka.Buckets)-1 {
// TODO refactor to return error?
// log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka))
return -1
}
ka.Buckets = buckets
return len(ka.Buckets)
}
/*
An address is bad if the address in question is a New address, has not been tried in the last
minute, and meets one of the following criteria:
1) It claims to be from the future
2) It hasn't been seen in over a week
3) It has failed at least three times and never succeeded
4) It has failed ten times in the last week
All addresses that meet these criteria are assumed to be worthless and not
worth keeping hold of.
*/
func (ka *knownAddress) isBad() bool {
// Is Old --> good
if ka.BucketType == bucketTypeOld {
return false
}
// Has been attempted in the last minute --> good
if ka.LastAttempt.After(time.Now().Add(-1 * time.Minute)) {
return false
}
// TODO: From the future?
// Too old?
// TODO: should be a timestamp of last seen, not just last attempt
if ka.LastAttempt.Before(time.Now().Add(-1 * numMissingDays * time.Hour * 24)) {
return true
}
// Never succeeded?
if ka.LastSuccess.IsZero() && ka.Attempts >= numRetries {
return true
}
// Hasn't succeeded in too long?
if ka.LastSuccess.Before(time.Now().Add(-1*minBadDays*time.Hour*24)) &&
ka.Attempts >= maxFailures {
return true
}
return false
}
package pex
import (
"errors"
"fmt"
"sync"
"time"
"github.com/cometbft/cometbft/libs/cmap"
cmtmath "github.com/cometbft/cometbft/libs/math"
cmtrand "github.com/cometbft/cometbft/libs/rand"
"github.com/cometbft/cometbft/libs/service"
"github.com/cometbft/cometbft/p2p"
"github.com/cometbft/cometbft/p2p/conn"
tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p"
)
type Peer = p2p.Peer
const (
// PexChannel is a channel for PEX messages
PexChannel = byte(0x00)
// over-estimate of max NetAddress size
// hexID (40) + IP (16) + Port (2) + Name (100) ...
// NOTE: dont use massive DNS name ..
maxAddressSize = 256
// NOTE: amplificaiton factor!
// small request results in up to maxMsgSize response
maxMsgSize = maxAddressSize * maxGetSelection
// ensure we have enough peers
defaultEnsurePeersPeriod = 30 * time.Second
// Seed/Crawler constants
// minTimeBetweenCrawls is a minimum time between attempts to crawl a peer.
minTimeBetweenCrawls = 2 * time.Minute
// check some peers every this
crawlPeerPeriod = 30 * time.Second
maxAttemptsToDial = 16 // ~ 35h in total (last attempt - 18h)
// if node connects to seed, it does not have any trusted peers.
// Especially in the beginning, node should have more trusted peers than
// untrusted.
biasToSelectNewPeers = 30 // 70 to select good peers
// if a peer is marked bad, it will be banned for at least this time period
defaultBanTime = 24 * time.Hour
)
type errMaxAttemptsToDial struct{}
func (e errMaxAttemptsToDial) Error() string {
return fmt.Sprintf("reached max attempts %d to dial", maxAttemptsToDial)
}
type errTooEarlyToDial struct {
backoffDuration time.Duration
lastDialed time.Time
}
func (e errTooEarlyToDial) Error() string {
return fmt.Sprintf(
"too early to dial (backoff duration: %d, last dialed: %v, time since: %v)",
e.backoffDuration, e.lastDialed, time.Since(e.lastDialed))
}
// Reactor handles PEX (peer exchange) and ensures that an
// adequate number of peers are connected to the switch.
//
// It uses `AddrBook` (address book) to store `NetAddress`es of the peers.
//
// ## Preventing abuse
//
// Only accept pexAddrsMsg from peers we sent a corresponding pexRequestMsg too.
// Only accept one pexRequestMsg every ~defaultEnsurePeersPeriod.
type Reactor struct {
p2p.BaseReactor
book AddrBook
config *ReactorConfig
ensurePeersCh chan struct{} // Wakes up ensurePeersRoutine()
ensurePeersPeriod time.Duration // TODO: should go in the config
// maps to prevent abuse
requestsSent *cmap.CMap // ID->struct{}: unanswered send requests
lastReceivedRequests *cmap.CMap // ID->time.Time: last time peer requested from us
seedAddrs []*p2p.NetAddress
attemptsToDial sync.Map // address (string) -> {number of attempts (int), last time dialed (time.Time)}
// seed/crawled mode fields
crawlPeerInfos map[p2p.ID]crawlPeerInfo
}
func (r *Reactor) minReceiveRequestInterval() time.Duration {
// NOTE: must be less than ensurePeersPeriod, otherwise we'll request
// peers too quickly from others and they'll think we're bad!
return r.ensurePeersPeriod / 3
}
// ReactorConfig holds reactor specific configuration data.
type ReactorConfig struct {
// Seed/Crawler mode
SeedMode bool
// We want seeds to only advertise good peers. Therefore they should wait at
// least as long as we expect it to take for a peer to become good before
// disconnecting.
SeedDisconnectWaitPeriod time.Duration
// Maximum pause when redialing a persistent peer (if zero, exponential backoff is used)
PersistentPeersMaxDialPeriod time.Duration
// Seeds is a list of addresses reactor may use
// if it can't connect to peers in the addrbook.
Seeds []string
}
type _attemptsToDial struct {
number int
lastDialed time.Time
}
// NewReactor creates new PEX reactor.
func NewReactor(b AddrBook, config *ReactorConfig) *Reactor {
r := &Reactor{
book: b,
config: config,
ensurePeersCh: make(chan struct{}),
ensurePeersPeriod: defaultEnsurePeersPeriod,
requestsSent: cmap.NewCMap(),
lastReceivedRequests: cmap.NewCMap(),
crawlPeerInfos: make(map[p2p.ID]crawlPeerInfo),
}
r.BaseReactor = *p2p.NewBaseReactor("PEX", r)
return r
}
// OnStart implements BaseService
func (r *Reactor) OnStart() error {
err := r.book.Start()
if err != nil && err != service.ErrAlreadyStarted {
return err
}
numOnline, seedAddrs, err := r.checkSeeds()
if err != nil {
return err
} else if numOnline == 0 && r.book.Empty() {
return errors.New("address book is empty and couldn't resolve any seed nodes")
}
r.seedAddrs = seedAddrs
// Check if this node should run
// in seed/crawler mode
if r.config.SeedMode {
go r.crawlPeersRoutine()
} else {
go r.ensurePeersRoutine()
}
return nil
}
// OnStop implements BaseService
func (r *Reactor) OnStop() {
if err := r.book.Stop(); err != nil {
r.Logger.Error("Error stopping address book", "err", err)
}
}
// GetChannels implements Reactor
func (r *Reactor) GetChannels() []*conn.ChannelDescriptor {
return []*conn.ChannelDescriptor{
{
ID: PexChannel,
Priority: 1,
SendQueueCapacity: 10,
RecvMessageCapacity: maxMsgSize,
MessageType: &tmp2p.Message{},
},
}
}
// AddPeer implements Reactor by adding peer to the address book (if inbound)
// or by requesting more addresses (if outbound).
func (r *Reactor) AddPeer(p Peer) {
if p.IsOutbound() {
// For outbound peers, the address is already in the books -
// either via DialPeersAsync or r.Receive.
// Ask it for more peers if we need.
if r.book.NeedMoreAddrs() {
r.RequestAddrs(p)
}
} else {
// inbound peer is its own source
addr, err := p.NodeInfo().NetAddress()
if err != nil {
r.Logger.Error("Failed to get peer NetAddress", "err", err, "peer", p)
return
}
// Make it explicit that addr and src are the same for an inbound peer.
src := addr
// add to book. dont RequestAddrs right away because
// we don't trust inbound as much - let ensurePeersRoutine handle it.
err = r.book.AddAddress(addr, src)
r.logErrAddrBook(err)
}
}
// RemovePeer implements Reactor by resetting peer's requests info.
func (r *Reactor) RemovePeer(p Peer, _ interface{}) {
id := string(p.ID())
r.requestsSent.Delete(id)
r.lastReceivedRequests.Delete(id)
}
func (r *Reactor) logErrAddrBook(err error) {
if err != nil {
switch err.(type) {
case ErrAddrBookNilAddr:
r.Logger.Error("Failed to add new address", "err", err)
default:
// non-routable, self, full book, private, etc.
r.Logger.Debug("Failed to add new address", "err", err)
}
}
}
// Receive implements Reactor by handling incoming PEX messages.
func (r *Reactor) Receive(e p2p.Envelope) {
r.Logger.Debug("Received message", "src", e.Src, "chId", e.ChannelID, "msg", e.Message)
switch msg := e.Message.(type) {
case *tmp2p.PexRequest:
// NOTE: this is a prime candidate for amplification attacks,
// so it's important we
// 1) restrict how frequently peers can request
// 2) limit the output size
// If we're a seed and this is an inbound peer,
// respond once and disconnect.
if r.config.SeedMode && !e.Src.IsOutbound() {
id := string(e.Src.ID())
v := r.lastReceivedRequests.Get(id)
if v != nil {
// FlushStop/StopPeer are already
// running in a go-routine.
return
}
r.lastReceivedRequests.Set(id, time.Now())
// Send addrs and disconnect
r.SendAddrs(e.Src, r.book.GetSelectionWithBias(biasToSelectNewPeers))
go func() {
// In a go-routine so it doesn't block .Receive.
e.Src.FlushStop()
r.Switch.StopPeerGracefully(e.Src)
}()
} else {
// Check we're not receiving requests too frequently.
if err := r.receiveRequest(e.Src); err != nil {
r.Switch.StopPeerForError(e.Src, err)
r.book.MarkBad(e.Src.SocketAddr(), defaultBanTime)
return
}
r.SendAddrs(e.Src, r.book.GetSelection())
}
case *tmp2p.PexAddrs:
// If we asked for addresses, add them to the book
addrs, err := p2p.NetAddressesFromProto(msg.Addrs)
if err != nil {
r.Switch.StopPeerForError(e.Src, err)
r.book.MarkBad(e.Src.SocketAddr(), defaultBanTime)
return
}
err = r.ReceiveAddrs(addrs, e.Src)
if err != nil {
r.Switch.StopPeerForError(e.Src, err)
if err == ErrUnsolicitedList {
r.book.MarkBad(e.Src.SocketAddr(), defaultBanTime)
}
return
}
default:
r.Logger.Error(fmt.Sprintf("Unknown message type %T", msg))
}
}
// enforces a minimum amount of time between requests
func (r *Reactor) receiveRequest(src Peer) error {
id := string(src.ID())
v := r.lastReceivedRequests.Get(id)
if v == nil {
// initialize with empty time
lastReceived := time.Time{}
r.lastReceivedRequests.Set(id, lastReceived)
return nil
}
lastReceived := v.(time.Time)
if lastReceived.Equal(time.Time{}) {
// first time gets a free pass. then we start tracking the time
lastReceived = time.Now()
r.lastReceivedRequests.Set(id, lastReceived)
return nil
}
now := time.Now()
minInterval := r.minReceiveRequestInterval()
if now.Sub(lastReceived) < minInterval {
return fmt.Errorf(
"peer (%v) sent next PEX request too soon. lastReceived: %v, now: %v, minInterval: %v. Disconnecting",
src.ID(),
lastReceived,
now,
minInterval,
)
}
r.lastReceivedRequests.Set(id, now)
return nil
}
// RequestAddrs asks peer for more addresses if we do not already have a
// request out for this peer.
func (r *Reactor) RequestAddrs(p Peer) {
id := string(p.ID())
if r.requestsSent.Has(id) {
return
}
r.Logger.Debug("Request addrs", "from", p)
r.requestsSent.Set(id, struct{}{})
p.Send(p2p.Envelope{
ChannelID: PexChannel,
Message: &tmp2p.PexRequest{},
})
}
// ReceiveAddrs adds the given addrs to the addrbook if theres an open
// request for this peer and deletes the open request.
// If there's no open request for the src peer, it returns an error.
func (r *Reactor) ReceiveAddrs(addrs []*p2p.NetAddress, src Peer) error {
id := string(src.ID())
if !r.requestsSent.Has(id) {
return ErrUnsolicitedList
}
r.requestsSent.Delete(id)
srcAddr, err := src.NodeInfo().NetAddress()
if err != nil {
return err
}
for _, netAddr := range addrs {
// NOTE: we check netAddr validity and routability in book#AddAddress.
err = r.book.AddAddress(netAddr, srcAddr)
if err != nil {
r.logErrAddrBook(err)
// XXX: should we be strict about incoming data and disconnect from a
// peer here too?
continue
}
}
// Try to connect to addresses coming from a seed node without waiting (#2093)
for _, seedAddr := range r.seedAddrs {
if seedAddr.Equals(srcAddr) {
select {
case r.ensurePeersCh <- struct{}{}:
default:
}
break
}
}
return nil
}
// SendAddrs sends addrs to the peer.
func (r *Reactor) SendAddrs(p Peer, netAddrs []*p2p.NetAddress) {
e := p2p.Envelope{
ChannelID: PexChannel,
Message: &tmp2p.PexAddrs{Addrs: p2p.NetAddressesToProto(netAddrs)},
}
p.Send(e)
}
// SetEnsurePeersPeriod sets period to ensure peers connected.
func (r *Reactor) SetEnsurePeersPeriod(d time.Duration) {
r.ensurePeersPeriod = d
}
// Ensures that sufficient peers are connected. (continuous)
func (r *Reactor) ensurePeersRoutine() {
var (
seed = cmtrand.NewRand()
jitter = seed.Int63n(r.ensurePeersPeriod.Nanoseconds())
)
// Randomize first round of communication to avoid thundering herd.
// If no peers are present directly start connecting so we guarantee swift
// setup with the help of configured seeds.
if r.nodeHasSomePeersOrDialingAny() {
time.Sleep(time.Duration(jitter))
}
// fire once immediately.
// ensures we dial the seeds right away if the book is empty
r.ensurePeers(true)
// fire periodically
ticker := time.NewTicker(r.ensurePeersPeriod)
for {
select {
case <-ticker.C:
r.ensurePeers(true)
case <-r.ensurePeersCh:
r.ensurePeers(false)
case <-r.Quit():
ticker.Stop()
return
}
}
}
// ensurePeers ensures that sufficient peers are connected. (once)
//
// heuristic that we haven't perfected yet, or, perhaps is manually edited by
// the node operator. It should not be used to compute what addresses are
// already connected or not.
func (r *Reactor) ensurePeers(ensurePeersPeriodElapsed bool) {
var (
out, in, dial = r.Switch.NumPeers()
numToDial = r.Switch.MaxNumOutboundPeers() - (out + dial)
)
r.Logger.Info(
"Ensure peers",
"numOutPeers", out,
"numInPeers", in,
"numDialing", dial,
"numToDial", numToDial,
)
if numToDial <= 0 {
return
}
// bias to prefer more vetted peers when we have fewer connections.
// not perfect, but somewhate ensures that we prioritize connecting to more-vetted
// NOTE: range here is [10, 90]. Too high ?
newBias := cmtmath.MinInt(out, 8)*10 + 10
toDial := make(map[p2p.ID]*p2p.NetAddress)
// Try maxAttempts times to pick numToDial addresses to dial
maxAttempts := numToDial * 3
for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ {
try := r.book.PickAddress(newBias)
if try == nil {
continue
}
if _, selected := toDial[try.ID]; selected {
continue
}
if r.Switch.IsDialingOrExistingAddress(try) {
continue
}
// TODO: consider moving some checks from toDial into here
// so we don't even consider dialing peers that we want to wait
// before dialing again, or have dialed too many times already
toDial[try.ID] = try
}
// Dial picked addresses
for _, addr := range toDial {
go func(addr *p2p.NetAddress) {
err := r.dialPeer(addr)
if err != nil {
switch err.(type) {
case errMaxAttemptsToDial, errTooEarlyToDial:
r.Logger.Debug(err.Error(), "addr", addr)
default:
r.Logger.Debug(err.Error(), "addr", addr)
}
}
}(addr)
}
if r.book.NeedMoreAddrs() {
// Check if banned nodes can be reinstated
r.book.ReinstateBadPeers()
}
if r.book.NeedMoreAddrs() {
// 1) Pick a random peer and ask for more.
peers := r.Switch.Peers().List()
peersCount := len(peers)
if peersCount > 0 && ensurePeersPeriodElapsed {
peer := peers[cmtrand.Int()%peersCount]
r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
r.RequestAddrs(peer)
}
// 2) Dial seeds if we are not dialing anyone.
// This is done in addition to asking a peer for addresses to work-around
// peers not participating in PEX.
if len(toDial) == 0 {
r.Logger.Info("No addresses to dial. Falling back to seeds")
r.dialSeeds()
}
}
}
func (r *Reactor) dialAttemptsInfo(addr *p2p.NetAddress) (attempts int, lastDialed time.Time) {
_attempts, ok := r.attemptsToDial.Load(addr.DialString())
if !ok {
return
}
atd := _attempts.(_attemptsToDial)
return atd.number, atd.lastDialed
}
func (r *Reactor) dialPeer(addr *p2p.NetAddress) error {
attempts, lastDialed := r.dialAttemptsInfo(addr)
if !r.Switch.IsPeerPersistent(addr) && attempts > maxAttemptsToDial {
r.book.MarkBad(addr, defaultBanTime)
return errMaxAttemptsToDial{}
}
// exponential backoff if it's not our first attempt to dial given address
if attempts > 0 {
jitter := time.Duration(cmtrand.Float64() * float64(time.Second)) // 1s == (1e9 ns)
backoffDuration := jitter + ((1 << uint(attempts)) * time.Second)
backoffDuration = r.maxBackoffDurationForPeer(addr, backoffDuration)
sinceLastDialed := time.Since(lastDialed)
if sinceLastDialed < backoffDuration {
return errTooEarlyToDial{backoffDuration, lastDialed}
}
}
err := r.Switch.DialPeerWithAddress(addr)
if err != nil {
if _, ok := err.(p2p.ErrCurrentlyDialingOrExistingAddress); ok {
return err
}
markAddrInBookBasedOnErr(addr, r.book, err)
switch err.(type) {
case p2p.ErrSwitchAuthenticationFailure:
// NOTE: addr is removed from addrbook in markAddrInBookBasedOnErr
r.attemptsToDial.Delete(addr.DialString())
default:
r.attemptsToDial.Store(addr.DialString(), _attemptsToDial{attempts + 1, time.Now()})
}
return fmt.Errorf("dialing failed (attempts: %d): %w", attempts+1, err)
}
// cleanup any history
r.attemptsToDial.Delete(addr.DialString())
return nil
}
// maxBackoffDurationForPeer caps the backoff duration for persistent peers.
func (r *Reactor) maxBackoffDurationForPeer(addr *p2p.NetAddress, planned time.Duration) time.Duration {
if r.config.PersistentPeersMaxDialPeriod > 0 &&
planned > r.config.PersistentPeersMaxDialPeriod &&
r.Switch.IsPeerPersistent(addr) {
return r.config.PersistentPeersMaxDialPeriod
}
return planned
}
// checkSeeds checks that addresses are well formed.
// Returns number of seeds we can connect to, along with all seeds addrs.
// return err if user provided any badly formatted seed addresses.
// Doesn't error if the seed node can't be reached.
// numOnline returns -1 if no seed nodes were in the initial configuration.
func (r *Reactor) checkSeeds() (numOnline int, netAddrs []*p2p.NetAddress, err error) {
lSeeds := len(r.config.Seeds)
if lSeeds == 0 {
return -1, nil, nil
}
netAddrs, errs := p2p.NewNetAddressStrings(r.config.Seeds)
numOnline = lSeeds - len(errs)
for _, err := range errs {
switch e := err.(type) {
case p2p.ErrNetAddressLookup:
r.Logger.Error("Connecting to seed failed", "err", e)
default:
return 0, nil, fmt.Errorf("seed node configuration has error: %w", e)
}
}
return numOnline, netAddrs, nil
}
// randomly dial seeds until we connect to one or exhaust them
func (r *Reactor) dialSeeds() {
perm := cmtrand.Perm(len(r.seedAddrs))
// perm := r.Switch.rng.Perm(lSeeds)
for _, i := range perm {
// dial a random seed
seedAddr := r.seedAddrs[i]
err := r.Switch.DialPeerWithAddress(seedAddr)
switch err.(type) {
case nil, p2p.ErrCurrentlyDialingOrExistingAddress:
return
}
r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
}
// do not write error message if there were no seeds specified in config
if len(r.seedAddrs) > 0 {
r.Switch.Logger.Error("Couldn't connect to any seeds")
}
}
// AttemptsToDial returns the number of attempts to dial specific address. It
// returns 0 if never attempted or successfully connected.
func (r *Reactor) AttemptsToDial(addr *p2p.NetAddress) int {
lAttempts, attempted := r.attemptsToDial.Load(addr.DialString())
if attempted {
return lAttempts.(_attemptsToDial).number
}
return 0
}
//----------------------------------------------------------
// Explores the network searching for more peers. (continuous)
// Seed/Crawler Mode causes this node to quickly disconnect
// from peers, except other seed nodes.
func (r *Reactor) crawlPeersRoutine() {
// If we have any seed nodes, consult them first
if len(r.seedAddrs) > 0 {
r.dialSeeds()
} else {
// Do an initial crawl
r.crawlPeers(r.book.GetSelection())
}
// Fire periodically
ticker := time.NewTicker(crawlPeerPeriod)
for {
select {
case <-ticker.C:
r.attemptDisconnects()
r.crawlPeers(r.book.GetSelection())
r.cleanupCrawlPeerInfos()
case <-r.Quit():
return
}
}
}
// nodeHasSomePeersOrDialingAny returns true if the node is connected to some
// peers or dialing them currently.
func (r *Reactor) nodeHasSomePeersOrDialingAny() bool {
out, in, dial := r.Switch.NumPeers()
return out+in+dial > 0
}
// crawlPeerInfo handles temporary data needed for the network crawling
// performed during seed/crawler mode.
type crawlPeerInfo struct {
Addr *p2p.NetAddress `json:"addr"`
// The last time we crawled the peer or attempted to do so.
LastCrawled time.Time `json:"last_crawled"`
}
// crawlPeers will crawl the network looking for new peer addresses.
func (r *Reactor) crawlPeers(addrs []*p2p.NetAddress) {
now := time.Now()
for _, addr := range addrs {
peerInfo, ok := r.crawlPeerInfos[addr.ID]
// Do not attempt to connect with peers we recently crawled.
if ok && now.Sub(peerInfo.LastCrawled) < minTimeBetweenCrawls {
continue
}
// Record crawling attempt.
r.crawlPeerInfos[addr.ID] = crawlPeerInfo{
Addr: addr,
LastCrawled: now,
}
err := r.dialPeer(addr)
if err != nil {
switch err.(type) {
case errMaxAttemptsToDial, errTooEarlyToDial, p2p.ErrCurrentlyDialingOrExistingAddress:
r.Logger.Debug(err.Error(), "addr", addr)
default:
r.Logger.Debug(err.Error(), "addr", addr)
}
continue
}
peer := r.Switch.Peers().Get(addr.ID)
if peer != nil {
r.RequestAddrs(peer)
}
}
}
func (r *Reactor) cleanupCrawlPeerInfos() {
for id, info := range r.crawlPeerInfos {
// If we did not crawl a peer for 24 hours, it means the peer was removed
// from the addrbook => remove
//
// 10000 addresses / maxGetSelection = 40 cycles to get all addresses in
// the ideal case,
// 40 * crawlPeerPeriod ~ 20 minutes
if time.Since(info.LastCrawled) > 24*time.Hour {
delete(r.crawlPeerInfos, id)
}
}
}
// attemptDisconnects checks if we've been with each peer long enough to disconnect
func (r *Reactor) attemptDisconnects() {
for _, peer := range r.Switch.Peers().List() {
if peer.Status().Duration < r.config.SeedDisconnectWaitPeriod {
continue
}
if peer.IsPersistent() {
continue
}
r.Switch.StopPeerGracefully(peer)
}
}
func markAddrInBookBasedOnErr(addr *p2p.NetAddress, book AddrBook, err error) {
// TODO: detect more "bad peer" scenarios
switch err.(type) {
case p2p.ErrSwitchAuthenticationFailure:
book.MarkBad(addr, defaultBanTime)
default:
book.MarkAttempt(addr)
}
}
package p2p
import (
"fmt"
"math"
"sync"
"time"
"github.com/cosmos/gogoproto/proto"
"github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/libs/cmap"
"github.com/cometbft/cometbft/libs/rand"
"github.com/cometbft/cometbft/libs/service"
"github.com/cometbft/cometbft/p2p/conn"
)
const (
// wait a random amount of time from this interval
// before dialing peers or reconnecting to help prevent DoS
dialRandomizerIntervalMilliseconds = 3000
// repeatedly try to reconnect for a few minutes
// ie. 5 * 20 = 100s
reconnectAttempts = 20
reconnectInterval = 5 * time.Second
// then move into exponential backoff mode for ~1day
// ie. 3**10 = 16hrs
reconnectBackOffAttempts = 10
reconnectBackOffBaseSeconds = 3
)
// MConnConfig returns an MConnConfig with fields updated
// from the P2PConfig.
func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig {
mConfig := conn.DefaultMConnConfig()
mConfig.FlushThrottle = cfg.FlushThrottleTimeout
mConfig.SendRate = cfg.SendRate
mConfig.RecvRate = cfg.RecvRate
mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize
mConfig.TestFuzz = cfg.TestFuzz
mConfig.TestFuzzConfig = cfg.TestFuzzConfig
return mConfig
}
//-----------------------------------------------------------------------------
// An AddrBook represents an address book from the pex package, which is used
// to store peer addresses.
type AddrBook interface {
AddAddress(addr *NetAddress, src *NetAddress) error
AddPrivateIDs([]string)
AddOurAddress(*NetAddress)
OurAddress(*NetAddress) bool
MarkGood(ID)
RemoveAddress(*NetAddress)
HasAddress(*NetAddress) bool
Save()
}
// PeerFilterFunc to be implemented by filter hooks after a new Peer has been
// fully setup.
type PeerFilterFunc func(IPeerSet, Peer) error
//-----------------------------------------------------------------------------
// Switch handles peer connections and exposes an API to receive incoming messages
// on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
// or more `Channels`. So while sending outgoing messages is typically performed on the peer,
// incoming messages are received on the reactor.
type Switch struct {
service.BaseService
config *config.P2PConfig
reactors map[string]Reactor
chDescs []*conn.ChannelDescriptor
reactorsByCh map[byte]Reactor
msgTypeByChID map[byte]proto.Message
peers *PeerSet
dialing *cmap.CMap
reconnecting *cmap.CMap
nodeInfo NodeInfo // our node info
nodeKey *NodeKey // our node privkey
addrBook AddrBook
// peers addresses with whom we'll maintain constant connection
persistentPeersAddrs []*NetAddress
unconditionalPeerIDs map[ID]struct{}
transport Transport
filterTimeout time.Duration
peerFilters []PeerFilterFunc
rng *rand.Rand // seed for randomizing dial times and orders
metrics *Metrics
mlc *metricsLabelCache
}
// NetAddress returns the address the switch is listening on.
func (sw *Switch) NetAddress() *NetAddress {
addr := sw.transport.NetAddress()
return &addr
}
// SwitchOption sets an optional parameter on the Switch.
type SwitchOption func(*Switch)
// NewSwitch creates a new Switch with the given config.
func NewSwitch(
cfg *config.P2PConfig,
transport Transport,
options ...SwitchOption,
) *Switch {
sw := &Switch{
config: cfg,
reactors: make(map[string]Reactor),
chDescs: make([]*conn.ChannelDescriptor, 0),
reactorsByCh: make(map[byte]Reactor),
msgTypeByChID: make(map[byte]proto.Message),
peers: NewPeerSet(),
dialing: cmap.NewCMap(),
reconnecting: cmap.NewCMap(),
metrics: NopMetrics(),
transport: transport,
filterTimeout: defaultFilterTimeout,
persistentPeersAddrs: make([]*NetAddress, 0),
unconditionalPeerIDs: make(map[ID]struct{}),
mlc: newMetricsLabelCache(),
}
// Ensure we have a completely undeterministic PRNG.
sw.rng = rand.NewRand()
sw.BaseService = *service.NewBaseService(nil, "P2P Switch", sw)
for _, option := range options {
option(sw)
}
return sw
}
// SwitchFilterTimeout sets the timeout used for peer filters.
func SwitchFilterTimeout(timeout time.Duration) SwitchOption {
return func(sw *Switch) { sw.filterTimeout = timeout }
}
// SwitchPeerFilters sets the filters for rejection of new peers.
func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption {
return func(sw *Switch) { sw.peerFilters = filters }
}
// WithMetrics sets the metrics.
func WithMetrics(metrics *Metrics) SwitchOption {
return func(sw *Switch) { sw.metrics = metrics }
}
//---------------------------------------------------------------------
// Switch setup
// AddReactor adds the given reactor to the switch.
// NOTE: Not goroutine safe.
func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
for _, chDesc := range reactor.GetChannels() {
chID := chDesc.ID
// No two reactors can share the same channel.
if sw.reactorsByCh[chID] != nil {
panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
}
sw.chDescs = append(sw.chDescs, chDesc)
sw.reactorsByCh[chID] = reactor
sw.msgTypeByChID[chID] = chDesc.MessageType
}
sw.reactors[name] = reactor
reactor.SetSwitch(sw)
return reactor
}
// RemoveReactor removes the given Reactor from the Switch.
// NOTE: Not goroutine safe.
func (sw *Switch) RemoveReactor(name string, reactor Reactor) {
for _, chDesc := range reactor.GetChannels() {
// remove channel description
for i := 0; i < len(sw.chDescs); i++ {
if chDesc.ID == sw.chDescs[i].ID {
sw.chDescs = append(sw.chDescs[:i], sw.chDescs[i+1:]...)
break
}
}
delete(sw.reactorsByCh, chDesc.ID)
delete(sw.msgTypeByChID, chDesc.ID)
}
delete(sw.reactors, name)
reactor.SetSwitch(nil)
}
// Reactors returns a map of reactors registered on the switch.
// NOTE: Not goroutine safe.
func (sw *Switch) Reactors() map[string]Reactor {
return sw.reactors
}
// Reactor returns the reactor with the given name.
// NOTE: Not goroutine safe.
func (sw *Switch) Reactor(name string) Reactor {
return sw.reactors[name]
}
// SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
// NOTE: Not goroutine safe.
func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) {
sw.nodeInfo = nodeInfo
}
// NodeInfo returns the switch's NodeInfo.
// NOTE: Not goroutine safe.
func (sw *Switch) NodeInfo() NodeInfo {
return sw.nodeInfo
}
// SetNodeKey sets the switch's private key for authenticated encryption.
// NOTE: Not goroutine safe.
func (sw *Switch) SetNodeKey(nodeKey *NodeKey) {
sw.nodeKey = nodeKey
}
//---------------------------------------------------------------------
// Service start/stop
// OnStart implements BaseService. It starts all the reactors and peers.
func (sw *Switch) OnStart() error {
// Start reactors
for _, reactor := range sw.reactors {
err := reactor.Start()
if err != nil {
return fmt.Errorf("failed to start %v: %w", reactor, err)
}
}
// Start accepting Peers.
go sw.acceptRoutine()
return nil
}
// OnStop implements BaseService. It stops all peers and reactors.
func (sw *Switch) OnStop() {
// Stop peers
for _, p := range sw.peers.List() {
sw.stopAndRemovePeer(p, nil)
}
// Stop reactors
sw.Logger.Debug("Switch: Stopping reactors")
for _, reactor := range sw.reactors {
if err := reactor.Stop(); err != nil {
sw.Logger.Error("error while stopped reactor", "reactor", reactor, "error", err)
}
}
}
//---------------------------------------------------------------------
// Peers
// Broadcast runs a go routine for each attempted send, which will block trying
// to send for defaultSendTimeoutSeconds. Returns a channel which receives
// success values for each attempted send (false if times out). Channel will be
// closed once msg bytes are sent to all peers (or time out).
//
// NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
func (sw *Switch) Broadcast(e Envelope) chan bool {
sw.Logger.Debug("Broadcast", "channel", e.ChannelID)
peers := sw.peers.List()
var wg sync.WaitGroup
wg.Add(len(peers))
successChan := make(chan bool, len(peers))
for _, peer := range peers {
go func(p Peer) {
defer wg.Done()
success := p.Send(e)
successChan <- success
}(peer)
}
go func() {
wg.Wait()
close(successChan)
}()
return successChan
}
// NumPeers returns the count of outbound/inbound and outbound-dialing peers.
// unconditional peers are not counted here.
func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
peers := sw.peers.List()
for _, peer := range peers {
if peer.IsOutbound() {
if !sw.IsPeerUnconditional(peer.ID()) {
outbound++
}
} else {
if !sw.IsPeerUnconditional(peer.ID()) {
inbound++
}
}
}
dialing = sw.dialing.Size()
return
}
func (sw *Switch) IsPeerUnconditional(id ID) bool {
_, ok := sw.unconditionalPeerIDs[id]
return ok
}
// MaxNumOutboundPeers returns a maximum number of outbound peers.
func (sw *Switch) MaxNumOutboundPeers() int {
return sw.config.MaxNumOutboundPeers
}
// Peers returns the set of peers that are connected to the switch.
func (sw *Switch) Peers() IPeerSet {
return sw.peers
}
// StopPeerForError disconnects from a peer due to external error.
// If the peer is persistent, it will attempt to reconnect.
// TODO: make record depending on reason.
func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
if !peer.IsRunning() {
return
}
sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
sw.stopAndRemovePeer(peer, reason)
if peer.IsPersistent() {
var addr *NetAddress
if peer.IsOutbound() { // socket address for outbound peers
addr = peer.SocketAddr()
} else { // self-reported address for inbound peers
var err error
addr, err = peer.NodeInfo().NetAddress()
if err != nil {
sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong",
"peer", peer, "err", err)
return
}
}
go sw.reconnectToPeer(addr)
}
}
// StopPeerGracefully disconnects from a peer gracefully.
// TODO: handle graceful disconnects.
func (sw *Switch) StopPeerGracefully(peer Peer) {
sw.Logger.Info("Stopping peer gracefully")
sw.stopAndRemovePeer(peer, nil)
}
func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
sw.transport.Cleanup(peer)
if err := peer.Stop(); err != nil {
sw.Logger.Error("error while stopping peer", "error", err) // TODO: should return error to be handled accordingly
}
for _, reactor := range sw.reactors {
reactor.RemovePeer(peer, reason)
}
// Removing a peer should go last to avoid a situation where a peer
// reconnect to our node and the switch calls InitPeer before
// RemovePeer is finished.
// https://github.com/tendermint/tendermint/issues/3338
if sw.peers.Remove(peer) {
sw.metrics.Peers.Add(float64(-1))
} else {
// Removal of the peer has failed. The function above sets a flag within the peer to mark this.
// We keep this message here as information to the developer.
sw.Logger.Debug("error on peer removal", ",", "peer", peer.ID())
}
}
// reconnectToPeer tries to reconnect to the addr, first repeatedly
// with a fixed interval (approximately 2 minutes), then with
// exponential backoff (approximately close to 24 hours).
// If no success after all that, it stops trying, and leaves it
// to the PEX/Addrbook to find the peer with the addr again
// NOTE: this will keep trying even if the handshake or auth fails.
// TODO: be more explicit with error types so we only retry on certain failures
// - ie. if we're getting ErrDuplicatePeer we can stop
// because the addrbook got us the peer back already
func (sw *Switch) reconnectToPeer(addr *NetAddress) {
if sw.reconnecting.Has(string(addr.ID)) {
return
}
sw.reconnecting.Set(string(addr.ID), addr)
defer sw.reconnecting.Delete(string(addr.ID))
start := time.Now()
sw.Logger.Info("Reconnecting to peer", "addr", addr)
for i := 0; i < reconnectAttempts; i++ {
if !sw.IsRunning() {
return
}
err := sw.DialPeerWithAddress(addr)
if err == nil {
return // success
} else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
return
}
sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
// sleep a set amount
sw.randomSleep(reconnectInterval)
continue
}
sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
"addr", addr, "elapsed", time.Since(start))
for i := 1; i <= reconnectBackOffAttempts; i++ {
if !sw.IsRunning() {
return
}
// sleep an exponentially increasing amount
sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
err := sw.DialPeerWithAddress(addr)
if err == nil {
return // success
} else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
return
}
sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
}
sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
}
// SetAddrBook allows to set address book on Switch.
func (sw *Switch) SetAddrBook(addrBook AddrBook) {
sw.addrBook = addrBook
}
// MarkPeerAsGood marks the given peer as good when it did something useful
// like contributed to consensus.
func (sw *Switch) MarkPeerAsGood(peer Peer) {
if sw.addrBook != nil {
sw.addrBook.MarkGood(peer.ID())
}
}
//---------------------------------------------------------------------
// Dialing
type privateAddr interface {
PrivateAddr() bool
}
func isPrivateAddr(err error) bool {
te, ok := err.(privateAddr)
return ok && te.PrivateAddr()
}
// DialPeersAsync dials a list of peers asynchronously in random order.
// Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
// It ignores ErrNetAddressLookup. However, if there are other errors, first
// encounter is returned.
// Nop if there are no peers.
func (sw *Switch) DialPeersAsync(peers []string) error {
netAddrs, errs := NewNetAddressStrings(peers)
// report all the errors
for _, err := range errs {
sw.Logger.Error("Error in peer's address", "err", err)
}
// return first non-ErrNetAddressLookup error
for _, err := range errs {
if _, ok := err.(ErrNetAddressLookup); ok {
continue
}
return err
}
sw.dialPeersAsync(netAddrs)
return nil
}
func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
ourAddr := sw.NetAddress()
// TODO: this code feels like it's in the wrong place.
// The integration tests depend on the addrBook being saved
// right away but maybe we can change that. Recall that
// the addrBook is only written to disk every 2min
if sw.addrBook != nil {
// add peers to `addrBook`
for _, netAddr := range netAddrs {
// do not add our address or ID
if !netAddr.Same(ourAddr) {
if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
if isPrivateAddr(err) {
sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
} else {
sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
}
}
}
}
// Persist some peers to disk right away.
// NOTE: integration tests depend on this
sw.addrBook.Save()
}
// permute the list, dial them in random order.
perm := sw.rng.Perm(len(netAddrs))
for i := 0; i < len(perm); i++ {
go func(i int) {
j := perm[i]
addr := netAddrs[j]
if addr.Same(ourAddr) {
sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
return
}
sw.randomSleep(0)
err := sw.DialPeerWithAddress(addr)
if err != nil {
switch err.(type) {
case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
sw.Logger.Debug("Error dialing peer", "err", err)
default:
sw.Logger.Error("Error dialing peer", "err", err)
}
}
}(i)
}
}
// DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
// and authenticates successfully.
// If we're currently dialing this address or it belongs to an existing peer,
// ErrCurrentlyDialingOrExistingAddress is returned.
func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
if sw.IsDialingOrExistingAddress(addr) {
return ErrCurrentlyDialingOrExistingAddress{addr.String()}
}
sw.dialing.Set(string(addr.ID), addr)
defer sw.dialing.Delete(string(addr.ID))
return sw.addOutboundPeerWithConfig(addr, sw.config)
}
// sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
func (sw *Switch) randomSleep(interval time.Duration) {
r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
time.Sleep(r + interval)
}
// IsDialingOrExistingAddress returns true if switch has a peer with the given
// address or dialing it at the moment.
func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
return sw.dialing.Has(string(addr.ID)) ||
sw.peers.Has(addr.ID) ||
(!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
}
// AddPersistentPeers allows you to set persistent peers. It ignores
// ErrNetAddressLookup. However, if there are other errors, first encounter is
// returned.
func (sw *Switch) AddPersistentPeers(addrs []string) error {
sw.Logger.Info("Adding persistent peers", "addrs", addrs)
netAddrs, errs := NewNetAddressStrings(addrs)
// report all the errors
for _, err := range errs {
sw.Logger.Error("Error in peer's address", "err", err)
}
// return first non-ErrNetAddressLookup error
for _, err := range errs {
if _, ok := err.(ErrNetAddressLookup); ok {
continue
}
return err
}
sw.persistentPeersAddrs = netAddrs
return nil
}
func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
sw.Logger.Info("Adding unconditional peer ids", "ids", ids)
for i, id := range ids {
err := validateID(ID(id))
if err != nil {
return fmt.Errorf("wrong ID #%d: %w", i, err)
}
sw.unconditionalPeerIDs[ID(id)] = struct{}{}
}
return nil
}
func (sw *Switch) AddPrivatePeerIDs(ids []string) error {
validIDs := make([]string, 0, len(ids))
for i, id := range ids {
err := validateID(ID(id))
if err != nil {
return fmt.Errorf("wrong ID #%d: %w", i, err)
}
validIDs = append(validIDs, id)
}
sw.addrBook.AddPrivateIDs(validIDs)
return nil
}
func (sw *Switch) IsPeerPersistent(na *NetAddress) bool {
for _, pa := range sw.persistentPeersAddrs {
if pa.Equals(na) {
return true
}
}
return false
}
func (sw *Switch) acceptRoutine() {
for {
p, err := sw.transport.Accept(peerConfig{
chDescs: sw.chDescs,
onPeerError: sw.StopPeerForError,
reactorsByCh: sw.reactorsByCh,
msgTypeByChID: sw.msgTypeByChID,
metrics: sw.metrics,
mlc: sw.mlc,
isPersistent: sw.IsPeerPersistent,
})
if err != nil {
switch err := err.(type) {
case ErrRejected:
if err.IsSelf() {
// Remove the given address from the address book and add to our addresses
// to avoid dialing in the future.
addr := err.Addr()
sw.addrBook.RemoveAddress(&addr)
sw.addrBook.AddOurAddress(&addr)
}
sw.Logger.Info(
"Inbound Peer rejected",
"err", err,
"numPeers", sw.peers.Size(),
)
continue
case ErrFilterTimeout:
sw.Logger.Error(
"Peer filter timed out",
"err", err,
)
continue
case ErrTransportClosed:
sw.Logger.Error(
"Stopped accept routine, as transport is closed",
"numPeers", sw.peers.Size(),
)
default:
sw.Logger.Error(
"Accept on transport errored",
"err", err,
"numPeers", sw.peers.Size(),
)
// We could instead have a retry loop around the acceptRoutine,
// but that would need to stop and let the node shutdown eventually.
// So might as well panic and let process managers restart the node.
// There's no point in letting the node run without the acceptRoutine,
// since it won't be able to accept new connections.
panic(fmt.Errorf("accept routine exited: %v", err))
}
break
}
if !sw.IsPeerUnconditional(p.NodeInfo().ID()) {
// Ignore connection if we already have enough peers.
_, in, _ := sw.NumPeers()
if in >= sw.config.MaxNumInboundPeers {
sw.Logger.Info(
"Ignoring inbound connection: already have enough inbound peers",
"address", p.SocketAddr(),
"have", in,
"max", sw.config.MaxNumInboundPeers,
)
sw.transport.Cleanup(p)
continue
}
}
if err := sw.addPeer(p); err != nil {
sw.transport.Cleanup(p)
if p.IsRunning() {
_ = p.Stop()
}
sw.Logger.Info(
"Ignoring inbound connection: error while adding peer",
"err", err,
"id", p.ID(),
)
}
}
}
// dial the peer; make secret connection; authenticate against the dialed ID;
// add the peer.
// if dialing fails, start the reconnect loop. If handshake fails, it's over.
// If peer is started successfully, reconnectLoop will start when
// StopPeerForError is called.
func (sw *Switch) addOutboundPeerWithConfig(
addr *NetAddress,
cfg *config.P2PConfig,
) error {
sw.Logger.Debug("Dialing peer", "address", addr)
// XXX(xla): Remove the leakage of test concerns in implementation.
if cfg.TestDialFail {
go sw.reconnectToPeer(addr)
return fmt.Errorf("dial err (peerConfig.DialFail == true)")
}
p, err := sw.transport.Dial(*addr, peerConfig{
chDescs: sw.chDescs,
onPeerError: sw.StopPeerForError,
isPersistent: sw.IsPeerPersistent,
reactorsByCh: sw.reactorsByCh,
msgTypeByChID: sw.msgTypeByChID,
metrics: sw.metrics,
mlc: sw.mlc,
})
if err != nil {
if e, ok := err.(ErrRejected); ok {
if e.IsSelf() {
// Remove the given address from the address book and add to our addresses
// to avoid dialing in the future.
sw.addrBook.RemoveAddress(addr)
sw.addrBook.AddOurAddress(addr)
return err
}
}
// retry persistent peers after
// any dial error besides IsSelf()
if sw.IsPeerPersistent(addr) {
go sw.reconnectToPeer(addr)
}
return err
}
if err := sw.addPeer(p); err != nil {
sw.transport.Cleanup(p)
if p.IsRunning() {
_ = p.Stop()
}
return err
}
return nil
}
func (sw *Switch) filterPeer(p Peer) error {
// Avoid duplicate
if sw.peers.Has(p.ID()) {
return ErrRejected{id: p.ID(), isDuplicate: true}
}
errc := make(chan error, len(sw.peerFilters))
for _, f := range sw.peerFilters {
go func(f PeerFilterFunc, p Peer, errc chan<- error) {
errc <- f(sw.peers, p)
}(f, p, errc)
}
for i := 0; i < cap(errc); i++ {
select {
case err := <-errc:
if err != nil {
return ErrRejected{id: p.ID(), err: err, isFiltered: true}
}
case <-time.After(sw.filterTimeout):
return ErrFilterTimeout{}
}
}
return nil
}
// addPeer starts up the Peer and adds it to the Switch. Error is returned if
// the peer is filtered out or failed to start or can't be added.
func (sw *Switch) addPeer(p Peer) error {
if err := sw.filterPeer(p); err != nil {
return err
}
p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
// Handle the shut down case where the switch has stopped but we're
// concurrently trying to add a peer.
if !sw.IsRunning() {
// XXX should this return an error or just log and terminate?
sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
return nil
}
// Add some data to the peer, which is required by reactors.
for _, reactor := range sw.reactors {
p = reactor.InitPeer(p)
}
// Start the peer's send/recv routines.
// Must start it before adding it to the peer set
// to prevent Start and Stop from being called concurrently.
err := p.Start()
if err != nil {
// Should never happen
sw.Logger.Error("Error starting peer", "err", err, "peer", p)
return err
}
// Add the peer to PeerSet. Do this before starting the reactors
// so that if Receive errors, we will find the peer and remove it.
// Add should not err since we already checked peers.Has().
if err := sw.peers.Add(p); err != nil {
switch err.(type) {
case ErrPeerRemoval:
sw.Logger.Error("Error starting peer ",
" err ", "Peer has already errored and removal was attempted.",
"peer", p.ID())
}
return err
}
sw.metrics.Peers.Add(float64(1))
// Start all the reactor protocols on the peer.
for _, reactor := range sw.reactors {
reactor.AddPeer(p)
}
sw.Logger.Debug("Added peer", "peer", p)
return nil
}
package p2p
import (
"context"
"fmt"
"net"
"time"
"golang.org/x/net/netutil"
"github.com/cosmos/gogoproto/proto"
"github.com/cometbft/cometbft/crypto"
"github.com/cometbft/cometbft/libs/protoio"
"github.com/cometbft/cometbft/p2p/conn"
tmp2p "github.com/cometbft/cometbft/proto/tendermint/p2p"
)
const (
defaultDialTimeout = time.Second
defaultFilterTimeout = 5 * time.Second
defaultHandshakeTimeout = 3 * time.Second
)
// IPResolver is a behavior subset of net.Resolver.
type IPResolver interface {
LookupIPAddr(context.Context, string) ([]net.IPAddr, error)
}
// accept is the container to carry the upgraded connection and NodeInfo from an
// asynchronously running routine to the Accept method.
type accept struct {
netAddr *NetAddress
conn net.Conn
nodeInfo NodeInfo
err error
}
// peerConfig is used to bundle data we need to fully setup a Peer with an
// MConn, provided by the caller of Accept and Dial (currently the Switch). This
// a temporary measure until reactor setup is less dynamic and we introduce the
// concept of PeerBehaviour to communicate about significant Peer lifecycle
// events.
// TODO(xla): Refactor out with more static Reactor setup and PeerBehaviour.
type peerConfig struct {
chDescs []*conn.ChannelDescriptor
onPeerError func(Peer, interface{})
outbound bool
// isPersistent allows you to set a function, which, given socket address
// (for outbound peers) OR self-reported address (for inbound peers), tells
// if the peer is persistent or not.
isPersistent func(*NetAddress) bool
reactorsByCh map[byte]Reactor
msgTypeByChID map[byte]proto.Message
metrics *Metrics
mlc *metricsLabelCache
}
// Transport emits and connects to Peers. The implementation of Peer is left to
// the transport. Each transport is also responsible to filter establishing
// peers specific to its domain.
type Transport interface {
// Listening address.
NetAddress() NetAddress
// Accept returns a newly connected Peer.
Accept(peerConfig) (Peer, error)
// Dial connects to the Peer for the address.
Dial(NetAddress, peerConfig) (Peer, error)
// Cleanup any resources associated with Peer.
Cleanup(Peer)
}
// transportLifecycle bundles the methods for callers to control start and stop
// behavior.
type transportLifecycle interface {
Close() error
Listen(NetAddress) error
}
// ConnFilterFunc to be implemented by filter hooks after a new connection has
// been established. The set of exisiting connections is passed along together
// with all resolved IPs for the new connection.
type ConnFilterFunc func(ConnSet, net.Conn, []net.IP) error
// ConnDuplicateIPFilter resolves and keeps all ips for an incoming connection
// and refuses new ones if they come from a known ip.
func ConnDuplicateIPFilter() ConnFilterFunc {
return func(cs ConnSet, c net.Conn, ips []net.IP) error {
for _, ip := range ips {
if cs.HasIP(ip) {
return ErrRejected{
conn: c,
err: fmt.Errorf("ip<%v> already connected", ip),
isDuplicate: true,
}
}
}
return nil
}
}
// MultiplexTransportOption sets an optional parameter on the
// MultiplexTransport.
type MultiplexTransportOption func(*MultiplexTransport)
// MultiplexTransportConnFilters sets the filters for rejection new connections.
func MultiplexTransportConnFilters(
filters ...ConnFilterFunc,
) MultiplexTransportOption {
return func(mt *MultiplexTransport) { mt.connFilters = filters }
}
// MultiplexTransportFilterTimeout sets the timeout waited for filter calls to
// return.
func MultiplexTransportFilterTimeout(
timeout time.Duration,
) MultiplexTransportOption {
return func(mt *MultiplexTransport) { mt.filterTimeout = timeout }
}
// MultiplexTransportResolver sets the Resolver used for ip lokkups, defaults to
// net.DefaultResolver.
func MultiplexTransportResolver(resolver IPResolver) MultiplexTransportOption {
return func(mt *MultiplexTransport) { mt.resolver = resolver }
}
// MultiplexTransportMaxIncomingConnections sets the maximum number of
// simultaneous connections (incoming). Default: 0 (unlimited)
func MultiplexTransportMaxIncomingConnections(n int) MultiplexTransportOption {
return func(mt *MultiplexTransport) { mt.maxIncomingConnections = n }
}
// MultiplexTransport accepts and dials tcp connections and upgrades them to
// multiplexed peers.
type MultiplexTransport struct {
netAddr NetAddress
listener net.Listener
maxIncomingConnections int // see MaxIncomingConnections
acceptc chan accept
closec chan struct{}
// Lookup table for duplicate ip and id checks.
conns ConnSet
connFilters []ConnFilterFunc
dialTimeout time.Duration
filterTimeout time.Duration
handshakeTimeout time.Duration
nodeInfo NodeInfo
nodeKey NodeKey
resolver IPResolver
// TODO(xla): This config is still needed as we parameterise peerConn and
// peer currently. All relevant configuration should be refactored into options
// with sane defaults.
mConfig conn.MConnConfig
}
// Test multiplexTransport for interface completeness.
var _ Transport = (*MultiplexTransport)(nil)
var _ transportLifecycle = (*MultiplexTransport)(nil)
// NewMultiplexTransport returns a tcp connected multiplexed peer.
func NewMultiplexTransport(
nodeInfo NodeInfo,
nodeKey NodeKey,
mConfig conn.MConnConfig,
) *MultiplexTransport {
return &MultiplexTransport{
acceptc: make(chan accept),
closec: make(chan struct{}),
dialTimeout: defaultDialTimeout,
filterTimeout: defaultFilterTimeout,
handshakeTimeout: defaultHandshakeTimeout,
mConfig: mConfig,
nodeInfo: nodeInfo,
nodeKey: nodeKey,
conns: NewConnSet(),
resolver: net.DefaultResolver,
}
}
// NetAddress implements Transport.
func (mt *MultiplexTransport) NetAddress() NetAddress {
return mt.netAddr
}
// Accept implements Transport.
func (mt *MultiplexTransport) Accept(cfg peerConfig) (Peer, error) {
select {
// This case should never have any side-effectful/blocking operations to
// ensure that quality peers are ready to be used.
case a := <-mt.acceptc:
if a.err != nil {
return nil, a.err
}
cfg.outbound = false
return mt.wrapPeer(a.conn, a.nodeInfo, cfg, a.netAddr), nil
case <-mt.closec:
return nil, ErrTransportClosed{}
}
}
// Dial implements Transport.
func (mt *MultiplexTransport) Dial(
addr NetAddress,
cfg peerConfig,
) (Peer, error) {
c, err := addr.DialTimeout(mt.dialTimeout)
if err != nil {
return nil, err
}
if mt.mConfig.TestFuzz {
// so we have time to do peer handshakes and get set up.
c = FuzzConnAfterFromConfig(c, 10*time.Second, mt.mConfig.TestFuzzConfig)
}
// TODO(xla): Evaluate if we should apply filters if we explicitly dial.
if err := mt.filterConn(c); err != nil {
return nil, err
}
secretConn, nodeInfo, err := mt.upgrade(c, &addr)
if err != nil {
return nil, err
}
cfg.outbound = true
p := mt.wrapPeer(secretConn, nodeInfo, cfg, &addr)
return p, nil
}
// Close implements transportLifecycle.
func (mt *MultiplexTransport) Close() error {
close(mt.closec)
if mt.listener != nil {
return mt.listener.Close()
}
return nil
}
// Listen implements transportLifecycle.
func (mt *MultiplexTransport) Listen(addr NetAddress) error {
ln, err := net.Listen("tcp", addr.DialString())
if err != nil {
return err
}
if mt.maxIncomingConnections > 0 {
ln = netutil.LimitListener(ln, mt.maxIncomingConnections)
}
mt.netAddr = addr
mt.listener = ln
go mt.acceptPeers()
return nil
}
// AddChannel registers a channel to nodeInfo.
// NOTE: NodeInfo must be of type DefaultNodeInfo else channels won't be updated
// This is a bit messy at the moment but is cleaned up in the following version
// when NodeInfo changes from an interface to a concrete type
func (mt *MultiplexTransport) AddChannel(chID byte) {
if ni, ok := mt.nodeInfo.(DefaultNodeInfo); ok {
if !ni.HasChannel(chID) {
ni.Channels = append(ni.Channels, chID)
}
mt.nodeInfo = ni
}
}
func (mt *MultiplexTransport) acceptPeers() {
for {
c, err := mt.listener.Accept()
if err != nil {
// If Close() has been called, silently exit.
select {
case _, ok := <-mt.closec:
if !ok {
return
}
default:
// Transport is not closed
}
mt.acceptc <- accept{err: err}
return
}
// Connection upgrade and filtering should be asynchronous to avoid
// Head-of-line blocking[0].
// Reference: https://github.com/tendermint/tendermint/issues/2047
//
// [0] https://en.wikipedia.org/wiki/Head-of-line_blocking
go func(c net.Conn) {
defer func() {
if r := recover(); r != nil {
err := ErrRejected{
conn: c,
err: fmt.Errorf("recovered from panic: %v", r),
isAuthFailure: true,
}
select {
case mt.acceptc <- accept{err: err}:
case <-mt.closec:
// Give up if the transport was closed.
_ = c.Close()
return
}
}
}()
var (
nodeInfo NodeInfo
secretConn *conn.SecretConnection
netAddr *NetAddress
)
err := mt.filterConn(c)
if err == nil {
secretConn, nodeInfo, err = mt.upgrade(c, nil)
if err == nil {
addr := c.RemoteAddr()
id := PubKeyToID(secretConn.RemotePubKey())
netAddr = NewNetAddress(id, addr)
}
}
select {
case mt.acceptc <- accept{netAddr, secretConn, nodeInfo, err}:
// Make the upgraded peer available.
case <-mt.closec:
// Give up if the transport was closed.
_ = c.Close()
return
}
}(c)
}
}
// Cleanup removes the given address from the connections set and
// closes the connection.
func (mt *MultiplexTransport) Cleanup(p Peer) {
mt.conns.RemoveAddr(p.RemoteAddr())
_ = p.CloseConn()
}
func (mt *MultiplexTransport) cleanup(c net.Conn) error {
mt.conns.Remove(c)
return c.Close()
}
func (mt *MultiplexTransport) filterConn(c net.Conn) (err error) {
defer func() {
if err != nil {
_ = c.Close()
}
}()
// Reject if connection is already present.
if mt.conns.Has(c) {
return ErrRejected{conn: c, isDuplicate: true}
}
// Resolve ips for incoming conn.
ips, err := resolveIPs(mt.resolver, c)
if err != nil {
return err
}
errc := make(chan error, len(mt.connFilters))
for _, f := range mt.connFilters {
go func(f ConnFilterFunc, c net.Conn, ips []net.IP, errc chan<- error) {
errc <- f(mt.conns, c, ips)
}(f, c, ips, errc)
}
for i := 0; i < cap(errc); i++ {
select {
case err := <-errc:
if err != nil {
return ErrRejected{conn: c, err: err, isFiltered: true}
}
case <-time.After(mt.filterTimeout):
return ErrFilterTimeout{}
}
}
mt.conns.Set(c, ips)
return nil
}
func (mt *MultiplexTransport) upgrade(
c net.Conn,
dialedAddr *NetAddress,
) (secretConn *conn.SecretConnection, nodeInfo NodeInfo, err error) {
defer func() {
if err != nil {
_ = mt.cleanup(c)
}
}()
secretConn, err = upgradeSecretConn(c, mt.handshakeTimeout, mt.nodeKey.PrivKey)
if err != nil {
return nil, nil, ErrRejected{
conn: c,
err: fmt.Errorf("secret conn failed: %v", err),
isAuthFailure: true,
}
}
// For outgoing conns, ensure connection key matches dialed key.
connID := PubKeyToID(secretConn.RemotePubKey())
if dialedAddr != nil {
if dialedID := dialedAddr.ID; connID != dialedID {
return nil, nil, ErrRejected{
conn: c,
id: connID,
err: fmt.Errorf(
"conn.ID (%v) dialed ID (%v) mismatch",
connID,
dialedID,
),
isAuthFailure: true,
}
}
}
nodeInfo, err = handshake(secretConn, mt.handshakeTimeout, mt.nodeInfo)
if err != nil {
return nil, nil, ErrRejected{
conn: c,
err: fmt.Errorf("handshake failed: %v", err),
isAuthFailure: true,
}
}
if err := nodeInfo.Validate(); err != nil {
return nil, nil, ErrRejected{
conn: c,
err: err,
isNodeInfoInvalid: true,
}
}
// Ensure connection key matches self reported key.
if connID != nodeInfo.ID() {
return nil, nil, ErrRejected{
conn: c,
id: connID,
err: fmt.Errorf(
"conn.ID (%v) NodeInfo.ID (%v) mismatch",
connID,
nodeInfo.ID(),
),
isAuthFailure: true,
}
}
// Reject self.
if mt.nodeInfo.ID() == nodeInfo.ID() {
return nil, nil, ErrRejected{
addr: *NewNetAddress(nodeInfo.ID(), c.RemoteAddr()),
conn: c,
id: nodeInfo.ID(),
isSelf: true,
}
}
if err := mt.nodeInfo.CompatibleWith(nodeInfo); err != nil {
return nil, nil, ErrRejected{
conn: c,
err: err,
id: nodeInfo.ID(),
isIncompatible: true,
}
}
return secretConn, nodeInfo, nil
}
func (mt *MultiplexTransport) wrapPeer(
c net.Conn,
ni NodeInfo,
cfg peerConfig,
socketAddr *NetAddress,
) Peer {
persistent := false
if cfg.isPersistent != nil {
if cfg.outbound {
persistent = cfg.isPersistent(socketAddr)
} else {
selfReportedAddr, err := ni.NetAddress()
if err == nil {
persistent = cfg.isPersistent(selfReportedAddr)
}
}
}
peerConn := newPeerConn(
cfg.outbound,
persistent,
c,
socketAddr,
)
p := newPeer(
peerConn,
mt.mConfig,
ni,
cfg.reactorsByCh,
cfg.msgTypeByChID,
cfg.chDescs,
cfg.onPeerError,
cfg.mlc,
PeerMetrics(cfg.metrics),
)
return p
}
func handshake(
c net.Conn,
timeout time.Duration,
nodeInfo NodeInfo,
) (NodeInfo, error) {
if err := c.SetDeadline(time.Now().Add(timeout)); err != nil {
return nil, err
}
var (
errc = make(chan error, 2)
pbpeerNodeInfo tmp2p.DefaultNodeInfo
peerNodeInfo DefaultNodeInfo
ourNodeInfo = nodeInfo.(DefaultNodeInfo)
)
go func(errc chan<- error, c net.Conn) {
_, err := protoio.NewDelimitedWriter(c).WriteMsg(ourNodeInfo.ToProto())
errc <- err
}(errc, c)
go func(errc chan<- error, c net.Conn) {
protoReader := protoio.NewDelimitedReader(c, MaxNodeInfoSize())
_, err := protoReader.ReadMsg(&pbpeerNodeInfo)
errc <- err
}(errc, c)
for i := 0; i < cap(errc); i++ {
err := <-errc
if err != nil {
return nil, err
}
}
peerNodeInfo, err := DefaultNodeInfoFromToProto(&pbpeerNodeInfo)
if err != nil {
return nil, err
}
return peerNodeInfo, c.SetDeadline(time.Time{})
}
func upgradeSecretConn(
c net.Conn,
timeout time.Duration,
privKey crypto.PrivKey,
) (*conn.SecretConnection, error) {
if err := c.SetDeadline(time.Now().Add(timeout)); err != nil {
return nil, err
}
sc, err := conn.MakeSecretConnection(c, privKey)
if err != nil {
return nil, err
}
return sc, sc.SetDeadline(time.Time{})
}
func resolveIPs(resolver IPResolver, c net.Conn) ([]net.IP, error) {
host, _, err := net.SplitHostPort(c.RemoteAddr().String())
if err != nil {
return nil, err
}
addrs, err := resolver.LookupIPAddr(context.Background(), host)
if err != nil {
return nil, err
}
ips := []net.IP{}
for _, addr := range addrs {
ips = append(ips, addr.IP)
}
return ips, nil
}
package mempool
import (
"fmt"
"github.com/cosmos/gogoproto/proto"
"github.com/cometbft/cometbft/p2p"
)
var _ p2p.Wrapper = &Txs{}
var _ p2p.Unwrapper = &Message{}
// Wrap implements the p2p Wrapper interface and wraps a mempool message.
func (m *Txs) Wrap() proto.Message {
mm := &Message{}
mm.Sum = &Message_Txs{Txs: m}
return mm
}
// Unwrap implements the p2p Wrapper interface and unwraps a wrapped mempool
// message.
func (m *Message) Unwrap() (proto.Message, error) {
switch msg := m.Sum.(type) {
case *Message_Txs:
return m.GetTxs(), nil
default:
return nil, fmt.Errorf("unknown message: %T", msg)
}
}
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: tendermint/mempool/types.proto
package mempool
import (
fmt "fmt"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
type Txs struct {
Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"`
}
func (m *Txs) Reset() { *m = Txs{} }
func (m *Txs) String() string { return proto.CompactTextString(m) }
func (*Txs) ProtoMessage() {}
func (*Txs) Descriptor() ([]byte, []int) {
return fileDescriptor_2af51926fdbcbc05, []int{0}
}
func (m *Txs) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Txs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Txs.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Txs) XXX_Merge(src proto.Message) {
xxx_messageInfo_Txs.Merge(m, src)
}
func (m *Txs) XXX_Size() int {
return m.Size()
}
func (m *Txs) XXX_DiscardUnknown() {
xxx_messageInfo_Txs.DiscardUnknown(m)
}
var xxx_messageInfo_Txs proto.InternalMessageInfo
func (m *Txs) GetTxs() [][]byte {
if m != nil {
return m.Txs
}
return nil
}
type Message struct {
// Types that are valid to be assigned to Sum:
//
// *Message_Txs
Sum isMessage_Sum `protobuf_oneof:"sum"`
}
func (m *Message) Reset() { *m = Message{} }
func (m *Message) String() string { return proto.CompactTextString(m) }
func (*Message) ProtoMessage() {}
func (*Message) Descriptor() ([]byte, []int) {
return fileDescriptor_2af51926fdbcbc05, []int{1}
}
func (m *Message) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Message.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Message) XXX_Merge(src proto.Message) {
xxx_messageInfo_Message.Merge(m, src)
}
func (m *Message) XXX_Size() int {
return m.Size()
}
func (m *Message) XXX_DiscardUnknown() {
xxx_messageInfo_Message.DiscardUnknown(m)
}
var xxx_messageInfo_Message proto.InternalMessageInfo
type isMessage_Sum interface {
isMessage_Sum()
MarshalTo([]byte) (int, error)
Size() int
}
type Message_Txs struct {
Txs *Txs `protobuf:"bytes,1,opt,name=txs,proto3,oneof" json:"txs,omitempty"`
}
func (*Message_Txs) isMessage_Sum() {}
func (m *Message) GetSum() isMessage_Sum {
if m != nil {
return m.Sum
}
return nil
}
func (m *Message) GetTxs() *Txs {
if x, ok := m.GetSum().(*Message_Txs); ok {
return x.Txs
}
return nil
}
// XXX_OneofWrappers is for the internal use of the proto package.
func (*Message) XXX_OneofWrappers() []interface{} {
return []interface{}{
(*Message_Txs)(nil),
}
}
func init() {
proto.RegisterType((*Txs)(nil), "tendermint.mempool.Txs")
proto.RegisterType((*Message)(nil), "tendermint.mempool.Message")
}
func init() { proto.RegisterFile("tendermint/mempool/types.proto", fileDescriptor_2af51926fdbcbc05) }
var fileDescriptor_2af51926fdbcbc05 = []byte{
// 184 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0x49, 0xcd, 0x4b,
0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0xcf, 0x4d, 0xcd, 0x2d, 0xc8, 0xcf, 0xcf, 0xd1, 0x2f,
0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x42, 0xc8, 0xeb, 0x41,
0xe5, 0x95, 0xc4, 0xb9, 0x98, 0x43, 0x2a, 0x8a, 0x85, 0x04, 0xb8, 0x98, 0x4b, 0x2a, 0x8a, 0x25,
0x18, 0x15, 0x98, 0x35, 0x78, 0x82, 0x40, 0x4c, 0x25, 0x5b, 0x2e, 0x76, 0xdf, 0xd4, 0xe2, 0xe2,
0xc4, 0xf4, 0x54, 0x21, 0x6d, 0x98, 0x24, 0xa3, 0x06, 0xb7, 0x91, 0xb8, 0x1e, 0xa6, 0x29, 0x7a,
0x21, 0x15, 0xc5, 0x1e, 0x0c, 0x60, 0x7d, 0x4e, 0xac, 0x5c, 0xcc, 0xc5, 0xa5, 0xb9, 0x4e, 0xfe,
0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72,
0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0x65, 0x9a, 0x9e, 0x59, 0x92, 0x51,
0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f, 0x9c, 0x9f, 0x9b, 0x5a, 0x92, 0x94, 0x56, 0x82, 0x60,
0x80, 0x5d, 0xaa, 0x8f, 0xe9, 0x91, 0x24, 0x36, 0xb0, 0x8c, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff,
0x53, 0xc3, 0xc4, 0x0a, 0xe5, 0x00, 0x00, 0x00,
}
func (m *Txs) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Txs) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Txs) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Txs[iNdEx])
copy(dAtA[i:], m.Txs[iNdEx])
i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *Message) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Message) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Sum != nil {
{
size := m.Sum.Size()
i -= size
if _, err := m.Sum.MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
}
}
return len(dAtA) - i, nil
}
func (m *Message_Txs) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Message_Txs) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.Txs != nil {
{
size, err := m.Txs.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintTypes(dAtA []byte, offset int, v uint64) int {
offset -= sovTypes(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *Txs) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Txs) > 0 {
for _, b := range m.Txs {
l = len(b)
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *Message) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Sum != nil {
n += m.Sum.Size()
}
return n
}
func (m *Message_Txs) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Txs != nil {
l = m.Txs.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func sovTypes(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozTypes(x uint64) (n int) {
return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *Txs) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Txs: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Txs: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx))
copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Message) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Message: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &Txs{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Sum = &Message_Txs{v}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipTypes(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthTypes
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupTypes
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthTypes
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group")
)
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: tendermint/types/params.proto
package types
import (
fmt "fmt"
_ "github.com/cosmos/gogoproto/gogoproto"
proto "github.com/cosmos/gogoproto/proto"
github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types"
_ "github.com/golang/protobuf/ptypes/duration"
io "io"
math "math"
math_bits "math/bits"
time "time"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
var _ = time.Kitchen
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// ConsensusParams contains consensus critical parameters that determine the
// validity of blocks.
type ConsensusParams struct {
Block *BlockParams `protobuf:"bytes,1,opt,name=block,proto3" json:"block,omitempty"`
Evidence *EvidenceParams `protobuf:"bytes,2,opt,name=evidence,proto3" json:"evidence,omitempty"`
Validator *ValidatorParams `protobuf:"bytes,3,opt,name=validator,proto3" json:"validator,omitempty"`
Version *VersionParams `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"`
Abci *ABCIParams `protobuf:"bytes,5,opt,name=abci,proto3" json:"abci,omitempty"`
}
func (m *ConsensusParams) Reset() { *m = ConsensusParams{} }
func (m *ConsensusParams) String() string { return proto.CompactTextString(m) }
func (*ConsensusParams) ProtoMessage() {}
func (*ConsensusParams) Descriptor() ([]byte, []int) {
return fileDescriptor_e12598271a686f57, []int{0}
}
func (m *ConsensusParams) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ConsensusParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ConsensusParams.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ConsensusParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_ConsensusParams.Merge(m, src)
}
func (m *ConsensusParams) XXX_Size() int {
return m.Size()
}
func (m *ConsensusParams) XXX_DiscardUnknown() {
xxx_messageInfo_ConsensusParams.DiscardUnknown(m)
}
var xxx_messageInfo_ConsensusParams proto.InternalMessageInfo
func (m *ConsensusParams) GetBlock() *BlockParams {
if m != nil {
return m.Block
}
return nil
}
func (m *ConsensusParams) GetEvidence() *EvidenceParams {
if m != nil {
return m.Evidence
}
return nil
}
func (m *ConsensusParams) GetValidator() *ValidatorParams {
if m != nil {
return m.Validator
}
return nil
}
func (m *ConsensusParams) GetVersion() *VersionParams {
if m != nil {
return m.Version
}
return nil
}
func (m *ConsensusParams) GetAbci() *ABCIParams {
if m != nil {
return m.Abci
}
return nil
}
// BlockParams contains limits on the block size.
type BlockParams struct {
// Max block size, in bytes.
// Note: must be greater than 0
MaxBytes int64 `protobuf:"varint,1,opt,name=max_bytes,json=maxBytes,proto3" json:"max_bytes,omitempty"`
// Max gas per block.
// Note: must be greater or equal to -1
MaxGas int64 `protobuf:"varint,2,opt,name=max_gas,json=maxGas,proto3" json:"max_gas,omitempty"`
}
func (m *BlockParams) Reset() { *m = BlockParams{} }
func (m *BlockParams) String() string { return proto.CompactTextString(m) }
func (*BlockParams) ProtoMessage() {}
func (*BlockParams) Descriptor() ([]byte, []int) {
return fileDescriptor_e12598271a686f57, []int{1}
}
func (m *BlockParams) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *BlockParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_BlockParams.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *BlockParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_BlockParams.Merge(m, src)
}
func (m *BlockParams) XXX_Size() int {
return m.Size()
}
func (m *BlockParams) XXX_DiscardUnknown() {
xxx_messageInfo_BlockParams.DiscardUnknown(m)
}
var xxx_messageInfo_BlockParams proto.InternalMessageInfo
func (m *BlockParams) GetMaxBytes() int64 {
if m != nil {
return m.MaxBytes
}
return 0
}
func (m *BlockParams) GetMaxGas() int64 {
if m != nil {
return m.MaxGas
}
return 0
}
// EvidenceParams determine how we handle evidence of malfeasance.
type EvidenceParams struct {
// Max age of evidence, in blocks.
//
// The basic formula for calculating this is: MaxAgeDuration / {average block
// time}.
MaxAgeNumBlocks int64 `protobuf:"varint,1,opt,name=max_age_num_blocks,json=maxAgeNumBlocks,proto3" json:"max_age_num_blocks,omitempty"`
// Max age of evidence, in time.
//
// It should correspond with an app's "unbonding period" or other similar
// mechanism for handling [Nothing-At-Stake
// attacks](https://github.com/ethereum/wiki/wiki/Proof-of-Stake-FAQ#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed).
MaxAgeDuration time.Duration `protobuf:"bytes,2,opt,name=max_age_duration,json=maxAgeDuration,proto3,stdduration" json:"max_age_duration"`
// This sets the maximum size of total evidence in bytes that can be committed in a single block.
// and should fall comfortably under the max block bytes.
// Default is 1048576 or 1MB
MaxBytes int64 `protobuf:"varint,3,opt,name=max_bytes,json=maxBytes,proto3" json:"max_bytes,omitempty"`
}
func (m *EvidenceParams) Reset() { *m = EvidenceParams{} }
func (m *EvidenceParams) String() string { return proto.CompactTextString(m) }
func (*EvidenceParams) ProtoMessage() {}
func (*EvidenceParams) Descriptor() ([]byte, []int) {
return fileDescriptor_e12598271a686f57, []int{2}
}
func (m *EvidenceParams) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *EvidenceParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_EvidenceParams.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *EvidenceParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_EvidenceParams.Merge(m, src)
}
func (m *EvidenceParams) XXX_Size() int {
return m.Size()
}
func (m *EvidenceParams) XXX_DiscardUnknown() {
xxx_messageInfo_EvidenceParams.DiscardUnknown(m)
}
var xxx_messageInfo_EvidenceParams proto.InternalMessageInfo
func (m *EvidenceParams) GetMaxAgeNumBlocks() int64 {
if m != nil {
return m.MaxAgeNumBlocks
}
return 0
}
func (m *EvidenceParams) GetMaxAgeDuration() time.Duration {
if m != nil {
return m.MaxAgeDuration
}
return 0
}
func (m *EvidenceParams) GetMaxBytes() int64 {
if m != nil {
return m.MaxBytes
}
return 0
}
// ValidatorParams restrict the public key types validators can use.
// NOTE: uses ABCI pubkey naming, not Amino names.
type ValidatorParams struct {
PubKeyTypes []string `protobuf:"bytes,1,rep,name=pub_key_types,json=pubKeyTypes,proto3" json:"pub_key_types,omitempty"`
}
func (m *ValidatorParams) Reset() { *m = ValidatorParams{} }
func (m *ValidatorParams) String() string { return proto.CompactTextString(m) }
func (*ValidatorParams) ProtoMessage() {}
func (*ValidatorParams) Descriptor() ([]byte, []int) {
return fileDescriptor_e12598271a686f57, []int{3}
}
func (m *ValidatorParams) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ValidatorParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ValidatorParams.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ValidatorParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_ValidatorParams.Merge(m, src)
}
func (m *ValidatorParams) XXX_Size() int {
return m.Size()
}
func (m *ValidatorParams) XXX_DiscardUnknown() {
xxx_messageInfo_ValidatorParams.DiscardUnknown(m)
}
var xxx_messageInfo_ValidatorParams proto.InternalMessageInfo
func (m *ValidatorParams) GetPubKeyTypes() []string {
if m != nil {
return m.PubKeyTypes
}
return nil
}
// VersionParams contains the ABCI application version.
type VersionParams struct {
App uint64 `protobuf:"varint,1,opt,name=app,proto3" json:"app,omitempty"`
}
func (m *VersionParams) Reset() { *m = VersionParams{} }
func (m *VersionParams) String() string { return proto.CompactTextString(m) }
func (*VersionParams) ProtoMessage() {}
func (*VersionParams) Descriptor() ([]byte, []int) {
return fileDescriptor_e12598271a686f57, []int{4}
}
func (m *VersionParams) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *VersionParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_VersionParams.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *VersionParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_VersionParams.Merge(m, src)
}
func (m *VersionParams) XXX_Size() int {
return m.Size()
}
func (m *VersionParams) XXX_DiscardUnknown() {
xxx_messageInfo_VersionParams.DiscardUnknown(m)
}
var xxx_messageInfo_VersionParams proto.InternalMessageInfo
func (m *VersionParams) GetApp() uint64 {
if m != nil {
return m.App
}
return 0
}
// HashedParams is a subset of ConsensusParams.
//
// It is hashed into the Header.ConsensusHash.
type HashedParams struct {
BlockMaxBytes int64 `protobuf:"varint,1,opt,name=block_max_bytes,json=blockMaxBytes,proto3" json:"block_max_bytes,omitempty"`
BlockMaxGas int64 `protobuf:"varint,2,opt,name=block_max_gas,json=blockMaxGas,proto3" json:"block_max_gas,omitempty"`
}
func (m *HashedParams) Reset() { *m = HashedParams{} }
func (m *HashedParams) String() string { return proto.CompactTextString(m) }
func (*HashedParams) ProtoMessage() {}
func (*HashedParams) Descriptor() ([]byte, []int) {
return fileDescriptor_e12598271a686f57, []int{5}
}
func (m *HashedParams) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *HashedParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_HashedParams.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *HashedParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_HashedParams.Merge(m, src)
}
func (m *HashedParams) XXX_Size() int {
return m.Size()
}
func (m *HashedParams) XXX_DiscardUnknown() {
xxx_messageInfo_HashedParams.DiscardUnknown(m)
}
var xxx_messageInfo_HashedParams proto.InternalMessageInfo
func (m *HashedParams) GetBlockMaxBytes() int64 {
if m != nil {
return m.BlockMaxBytes
}
return 0
}
func (m *HashedParams) GetBlockMaxGas() int64 {
if m != nil {
return m.BlockMaxGas
}
return 0
}
// ABCIParams configure functionality specific to the Application Blockchain Interface.
type ABCIParams struct {
// vote_extensions_enable_height configures the first height during which
// vote extensions will be enabled. During this specified height, and for all
// subsequent heights, precommit messages that do not contain valid extension data
// will be considered invalid. Prior to this height, vote extensions will not
// be used or accepted by validators on the network.
//
// Once enabled, vote extensions will be created by the application in ExtendVote,
// passed to the application for validation in VerifyVoteExtension and given
// to the application to use when proposing a block during PrepareProposal.
VoteExtensionsEnableHeight int64 `protobuf:"varint,1,opt,name=vote_extensions_enable_height,json=voteExtensionsEnableHeight,proto3" json:"vote_extensions_enable_height,omitempty"`
}
func (m *ABCIParams) Reset() { *m = ABCIParams{} }
func (m *ABCIParams) String() string { return proto.CompactTextString(m) }
func (*ABCIParams) ProtoMessage() {}
func (*ABCIParams) Descriptor() ([]byte, []int) {
return fileDescriptor_e12598271a686f57, []int{6}
}
func (m *ABCIParams) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ABCIParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ABCIParams.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ABCIParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_ABCIParams.Merge(m, src)
}
func (m *ABCIParams) XXX_Size() int {
return m.Size()
}
func (m *ABCIParams) XXX_DiscardUnknown() {
xxx_messageInfo_ABCIParams.DiscardUnknown(m)
}
var xxx_messageInfo_ABCIParams proto.InternalMessageInfo
func (m *ABCIParams) GetVoteExtensionsEnableHeight() int64 {
if m != nil {
return m.VoteExtensionsEnableHeight
}
return 0
}
func init() {
proto.RegisterType((*ConsensusParams)(nil), "tendermint.types.ConsensusParams")
proto.RegisterType((*BlockParams)(nil), "tendermint.types.BlockParams")
proto.RegisterType((*EvidenceParams)(nil), "tendermint.types.EvidenceParams")
proto.RegisterType((*ValidatorParams)(nil), "tendermint.types.ValidatorParams")
proto.RegisterType((*VersionParams)(nil), "tendermint.types.VersionParams")
proto.RegisterType((*HashedParams)(nil), "tendermint.types.HashedParams")
proto.RegisterType((*ABCIParams)(nil), "tendermint.types.ABCIParams")
}
func init() { proto.RegisterFile("tendermint/types/params.proto", fileDescriptor_e12598271a686f57) }
var fileDescriptor_e12598271a686f57 = []byte{
// 576 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x93, 0x3f, 0x6f, 0xd3, 0x4e,
0x18, 0xc7, 0x73, 0x75, 0xda, 0xa6, 0x4f, 0x7e, 0x69, 0xa2, 0xd3, 0x4f, 0xc2, 0x14, 0xe2, 0x04,
0x0f, 0xa8, 0x52, 0x25, 0x1b, 0x91, 0x09, 0x84, 0x54, 0x25, 0x25, 0x6a, 0x0b, 0x2a, 0x7f, 0x2c,
0xc4, 0xd0, 0xc5, 0x3a, 0x27, 0x57, 0xc7, 0x6a, 0xec, 0xb3, 0x7c, 0xe7, 0x28, 0x79, 0x17, 0x8c,
0x8c, 0x1d, 0x61, 0x65, 0xe2, 0x25, 0x74, 0xec, 0xc8, 0x04, 0x28, 0x59, 0x78, 0x19, 0xc8, 0x67,
0xbb, 0x6e, 0x12, 0xb6, 0xbb, 0x7b, 0x3e, 0x9f, 0xfb, 0xf3, 0x7d, 0x74, 0xd0, 0x14, 0x34, 0x18,
0xd2, 0xc8, 0xf7, 0x02, 0x61, 0x8a, 0x59, 0x48, 0xb9, 0x19, 0x92, 0x88, 0xf8, 0xdc, 0x08, 0x23,
0x26, 0x18, 0x6e, 0x14, 0x65, 0x43, 0x96, 0xf7, 0xfe, 0x77, 0x99, 0xcb, 0x64, 0xd1, 0x4c, 0x46,
0x29, 0xb7, 0xa7, 0xb9, 0x8c, 0xb9, 0x63, 0x6a, 0xca, 0x99, 0x13, 0x5f, 0x98, 0xc3, 0x38, 0x22,
0xc2, 0x63, 0x41, 0x5a, 0xd7, 0xbf, 0x6d, 0x40, 0xfd, 0x88, 0x05, 0x9c, 0x06, 0x3c, 0xe6, 0xef,
0xe4, 0x09, 0xb8, 0x03, 0x9b, 0xce, 0x98, 0x0d, 0x2e, 0x55, 0xd4, 0x46, 0xfb, 0xd5, 0xa7, 0x4d,
0x63, 0xf5, 0x2c, 0xa3, 0x97, 0x94, 0x53, 0xda, 0x4a, 0x59, 0xfc, 0x02, 0x2a, 0x74, 0xe2, 0x0d,
0x69, 0x30, 0xa0, 0xea, 0x86, 0xf4, 0xda, 0xeb, 0x5e, 0x3f, 0x23, 0x32, 0xf5, 0xd6, 0xc0, 0x87,
0xb0, 0x33, 0x21, 0x63, 0x6f, 0x48, 0x04, 0x8b, 0x54, 0x45, 0xea, 0x8f, 0xd6, 0xf5, 0x8f, 0x39,
0x92, 0xf9, 0x85, 0x83, 0x9f, 0xc1, 0xf6, 0x84, 0x46, 0xdc, 0x63, 0x81, 0x5a, 0x96, 0x7a, 0xeb,
0x1f, 0x7a, 0x0a, 0x64, 0x72, 0xce, 0xe3, 0x27, 0x50, 0x26, 0xce, 0xc0, 0x53, 0x37, 0xa5, 0xf7,
0x70, 0xdd, 0xeb, 0xf6, 0x8e, 0x4e, 0x33, 0x49, 0x92, 0xfa, 0x29, 0x54, 0xef, 0x24, 0x80, 0x1f,
0xc0, 0x8e, 0x4f, 0xa6, 0xb6, 0x33, 0x13, 0x94, 0xcb, 0xcc, 0x14, 0xab, 0xe2, 0x93, 0x69, 0x2f,
0x99, 0xe3, 0x7b, 0xb0, 0x9d, 0x14, 0x5d, 0xc2, 0x65, 0x2c, 0x8a, 0xb5, 0xe5, 0x93, 0xe9, 0x31,
0xe1, 0xaf, 0xca, 0x15, 0xa5, 0x51, 0xd6, 0xbf, 0x22, 0xd8, 0x5d, 0x4e, 0x05, 0x1f, 0x00, 0x4e,
0x0c, 0xe2, 0x52, 0x3b, 0x88, 0x7d, 0x5b, 0xc6, 0x9b, 0xef, 0x5b, 0xf7, 0xc9, 0xb4, 0xeb, 0xd2,
0x37, 0xb1, 0x2f, 0x2f, 0xc0, 0xf1, 0x19, 0x34, 0x72, 0x38, 0xef, 0x6c, 0x16, 0xff, 0x7d, 0x23,
0x6d, 0xbd, 0x91, 0xb7, 0xde, 0x78, 0x99, 0x01, 0xbd, 0xca, 0xf5, 0xcf, 0x56, 0xe9, 0xf3, 0xaf,
0x16, 0xb2, 0x76, 0xd3, 0xfd, 0xf2, 0xca, 0xf2, 0x53, 0x94, 0xe5, 0xa7, 0xe8, 0x87, 0x50, 0x5f,
0xe9, 0x00, 0xd6, 0xa1, 0x16, 0xc6, 0x8e, 0x7d, 0x49, 0x67, 0xb6, 0xcc, 0x4a, 0x45, 0x6d, 0x65,
0x7f, 0xc7, 0xaa, 0x86, 0xb1, 0xf3, 0x9a, 0xce, 0x3e, 0x24, 0x4b, 0xcf, 0x2b, 0xdf, 0xaf, 0x5a,
0xe8, 0xcf, 0x55, 0x0b, 0xe9, 0x07, 0x50, 0x5b, 0xea, 0x01, 0x6e, 0x80, 0x42, 0xc2, 0x50, 0xbe,
0xad, 0x6c, 0x25, 0xc3, 0x3b, 0xf0, 0x39, 0xfc, 0x77, 0x42, 0xf8, 0x88, 0x0e, 0x33, 0xf6, 0x31,
0xd4, 0x65, 0x14, 0xf6, 0x6a, 0xd6, 0x35, 0xb9, 0x7c, 0x96, 0x07, 0xae, 0x43, 0xad, 0xe0, 0x8a,
0xd8, 0xab, 0x39, 0x75, 0x4c, 0xb8, 0xfe, 0x16, 0xa0, 0x68, 0x2a, 0xee, 0x42, 0x73, 0xc2, 0x04,
0xb5, 0xe9, 0x54, 0xd0, 0x20, 0xb9, 0x1d, 0xb7, 0x69, 0x40, 0x9c, 0x31, 0xb5, 0x47, 0xd4, 0x73,
0x47, 0x22, 0x3b, 0x67, 0x2f, 0x81, 0xfa, 0xb7, 0x4c, 0x5f, 0x22, 0x27, 0x92, 0xe8, 0xbd, 0xff,
0x32, 0xd7, 0xd0, 0xf5, 0x5c, 0x43, 0x37, 0x73, 0x0d, 0xfd, 0x9e, 0x6b, 0xe8, 0xd3, 0x42, 0x2b,
0xdd, 0x2c, 0xb4, 0xd2, 0x8f, 0x85, 0x56, 0x3a, 0xef, 0xb8, 0x9e, 0x18, 0xc5, 0x8e, 0x31, 0x60,
0xbe, 0x39, 0x60, 0x3e, 0x15, 0xce, 0x85, 0x28, 0x06, 0xe9, 0x9f, 0x5d, 0xfd, 0xee, 0xce, 0x96,
0x5c, 0xef, 0xfc, 0x0d, 0x00, 0x00, 0xff, 0xff, 0xb9, 0xe8, 0xce, 0x9a, 0x09, 0x04, 0x00, 0x00,
}
func (this *ConsensusParams) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*ConsensusParams)
if !ok {
that2, ok := that.(ConsensusParams)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !this.Block.Equal(that1.Block) {
return false
}
if !this.Evidence.Equal(that1.Evidence) {
return false
}
if !this.Validator.Equal(that1.Validator) {
return false
}
if !this.Version.Equal(that1.Version) {
return false
}
if !this.Abci.Equal(that1.Abci) {
return false
}
return true
}
func (this *BlockParams) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*BlockParams)
if !ok {
that2, ok := that.(BlockParams)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.MaxBytes != that1.MaxBytes {
return false
}
if this.MaxGas != that1.MaxGas {
return false
}
return true
}
func (this *EvidenceParams) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*EvidenceParams)
if !ok {
that2, ok := that.(EvidenceParams)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.MaxAgeNumBlocks != that1.MaxAgeNumBlocks {
return false
}
if this.MaxAgeDuration != that1.MaxAgeDuration {
return false
}
if this.MaxBytes != that1.MaxBytes {
return false
}
return true
}
func (this *ValidatorParams) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*ValidatorParams)
if !ok {
that2, ok := that.(ValidatorParams)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if len(this.PubKeyTypes) != len(that1.PubKeyTypes) {
return false
}
for i := range this.PubKeyTypes {
if this.PubKeyTypes[i] != that1.PubKeyTypes[i] {
return false
}
}
return true
}
func (this *VersionParams) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*VersionParams)
if !ok {
that2, ok := that.(VersionParams)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.App != that1.App {
return false
}
return true
}
func (this *HashedParams) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*HashedParams)
if !ok {
that2, ok := that.(HashedParams)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.BlockMaxBytes != that1.BlockMaxBytes {
return false
}
if this.BlockMaxGas != that1.BlockMaxGas {
return false
}
return true
}
func (this *ABCIParams) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*ABCIParams)
if !ok {
that2, ok := that.(ABCIParams)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.VoteExtensionsEnableHeight != that1.VoteExtensionsEnableHeight {
return false
}
return true
}
func (m *ConsensusParams) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ConsensusParams) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ConsensusParams) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Abci != nil {
{
size, err := m.Abci.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintParams(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x2a
}
if m.Version != nil {
{
size, err := m.Version.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintParams(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
if m.Validator != nil {
{
size, err := m.Validator.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintParams(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
if m.Evidence != nil {
{
size, err := m.Evidence.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintParams(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if m.Block != nil {
{
size, err := m.Block.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintParams(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *BlockParams) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *BlockParams) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *BlockParams) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.MaxGas != 0 {
i = encodeVarintParams(dAtA, i, uint64(m.MaxGas))
i--
dAtA[i] = 0x10
}
if m.MaxBytes != 0 {
i = encodeVarintParams(dAtA, i, uint64(m.MaxBytes))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *EvidenceParams) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *EvidenceParams) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *EvidenceParams) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.MaxBytes != 0 {
i = encodeVarintParams(dAtA, i, uint64(m.MaxBytes))
i--
dAtA[i] = 0x18
}
n6, err6 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.MaxAgeDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.MaxAgeDuration):])
if err6 != nil {
return 0, err6
}
i -= n6
i = encodeVarintParams(dAtA, i, uint64(n6))
i--
dAtA[i] = 0x12
if m.MaxAgeNumBlocks != 0 {
i = encodeVarintParams(dAtA, i, uint64(m.MaxAgeNumBlocks))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ValidatorParams) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ValidatorParams) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ValidatorParams) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.PubKeyTypes) > 0 {
for iNdEx := len(m.PubKeyTypes) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.PubKeyTypes[iNdEx])
copy(dAtA[i:], m.PubKeyTypes[iNdEx])
i = encodeVarintParams(dAtA, i, uint64(len(m.PubKeyTypes[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *VersionParams) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *VersionParams) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *VersionParams) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.App != 0 {
i = encodeVarintParams(dAtA, i, uint64(m.App))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *HashedParams) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *HashedParams) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *HashedParams) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.BlockMaxGas != 0 {
i = encodeVarintParams(dAtA, i, uint64(m.BlockMaxGas))
i--
dAtA[i] = 0x10
}
if m.BlockMaxBytes != 0 {
i = encodeVarintParams(dAtA, i, uint64(m.BlockMaxBytes))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ABCIParams) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ABCIParams) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ABCIParams) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.VoteExtensionsEnableHeight != 0 {
i = encodeVarintParams(dAtA, i, uint64(m.VoteExtensionsEnableHeight))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func encodeVarintParams(dAtA []byte, offset int, v uint64) int {
offset -= sovParams(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func NewPopulatedValidatorParams(r randyParams, easy bool) *ValidatorParams {
this := &ValidatorParams{}
v1 := r.Intn(10)
this.PubKeyTypes = make([]string, v1)
for i := 0; i < v1; i++ {
this.PubKeyTypes[i] = string(randStringParams(r))
}
if !easy && r.Intn(10) != 0 {
}
return this
}
func NewPopulatedVersionParams(r randyParams, easy bool) *VersionParams {
this := &VersionParams{}
this.App = uint64(uint64(r.Uint32()))
if !easy && r.Intn(10) != 0 {
}
return this
}
type randyParams interface {
Float32() float32
Float64() float64
Int63() int64
Int31() int32
Uint32() uint32
Intn(n int) int
}
func randUTF8RuneParams(r randyParams) rune {
ru := r.Intn(62)
if ru < 10 {
return rune(ru + 48)
} else if ru < 36 {
return rune(ru + 55)
}
return rune(ru + 61)
}
func randStringParams(r randyParams) string {
v2 := r.Intn(100)
tmps := make([]rune, v2)
for i := 0; i < v2; i++ {
tmps[i] = randUTF8RuneParams(r)
}
return string(tmps)
}
func randUnrecognizedParams(r randyParams, maxFieldNumber int) (dAtA []byte) {
l := r.Intn(5)
for i := 0; i < l; i++ {
wire := r.Intn(4)
if wire == 3 {
wire = 5
}
fieldNumber := maxFieldNumber + r.Intn(100)
dAtA = randFieldParams(dAtA, r, fieldNumber, wire)
}
return dAtA
}
func randFieldParams(dAtA []byte, r randyParams, fieldNumber int, wire int) []byte {
key := uint32(fieldNumber)<<3 | uint32(wire)
switch wire {
case 0:
dAtA = encodeVarintPopulateParams(dAtA, uint64(key))
v3 := r.Int63()
if r.Intn(2) == 0 {
v3 *= -1
}
dAtA = encodeVarintPopulateParams(dAtA, uint64(v3))
case 1:
dAtA = encodeVarintPopulateParams(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
case 2:
dAtA = encodeVarintPopulateParams(dAtA, uint64(key))
ll := r.Intn(100)
dAtA = encodeVarintPopulateParams(dAtA, uint64(ll))
for j := 0; j < ll; j++ {
dAtA = append(dAtA, byte(r.Intn(256)))
}
default:
dAtA = encodeVarintPopulateParams(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
}
return dAtA
}
func encodeVarintPopulateParams(dAtA []byte, v uint64) []byte {
for v >= 1<<7 {
dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
v >>= 7
}
dAtA = append(dAtA, uint8(v))
return dAtA
}
func (m *ConsensusParams) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Block != nil {
l = m.Block.Size()
n += 1 + l + sovParams(uint64(l))
}
if m.Evidence != nil {
l = m.Evidence.Size()
n += 1 + l + sovParams(uint64(l))
}
if m.Validator != nil {
l = m.Validator.Size()
n += 1 + l + sovParams(uint64(l))
}
if m.Version != nil {
l = m.Version.Size()
n += 1 + l + sovParams(uint64(l))
}
if m.Abci != nil {
l = m.Abci.Size()
n += 1 + l + sovParams(uint64(l))
}
return n
}
func (m *BlockParams) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.MaxBytes != 0 {
n += 1 + sovParams(uint64(m.MaxBytes))
}
if m.MaxGas != 0 {
n += 1 + sovParams(uint64(m.MaxGas))
}
return n
}
func (m *EvidenceParams) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.MaxAgeNumBlocks != 0 {
n += 1 + sovParams(uint64(m.MaxAgeNumBlocks))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.MaxAgeDuration)
n += 1 + l + sovParams(uint64(l))
if m.MaxBytes != 0 {
n += 1 + sovParams(uint64(m.MaxBytes))
}
return n
}
func (m *ValidatorParams) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.PubKeyTypes) > 0 {
for _, s := range m.PubKeyTypes {
l = len(s)
n += 1 + l + sovParams(uint64(l))
}
}
return n
}
func (m *VersionParams) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.App != 0 {
n += 1 + sovParams(uint64(m.App))
}
return n
}
func (m *HashedParams) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.BlockMaxBytes != 0 {
n += 1 + sovParams(uint64(m.BlockMaxBytes))
}
if m.BlockMaxGas != 0 {
n += 1 + sovParams(uint64(m.BlockMaxGas))
}
return n
}
func (m *ABCIParams) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.VoteExtensionsEnableHeight != 0 {
n += 1 + sovParams(uint64(m.VoteExtensionsEnableHeight))
}
return n
}
func sovParams(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozParams(x uint64) (n int) {
return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *ConsensusParams) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ConsensusParams: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ConsensusParams: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Block", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthParams
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthParams
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Block == nil {
m.Block = &BlockParams{}
}
if err := m.Block.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Evidence", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthParams
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthParams
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Evidence == nil {
m.Evidence = &EvidenceParams{}
}
if err := m.Evidence.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthParams
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthParams
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Validator == nil {
m.Validator = &ValidatorParams{}
}
if err := m.Validator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthParams
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthParams
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Version == nil {
m.Version = &VersionParams{}
}
if err := m.Version.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Abci", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthParams
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthParams
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Abci == nil {
m.Abci = &ABCIParams{}
}
if err := m.Abci.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipParams(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthParams
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *BlockParams) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: BlockParams: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: BlockParams: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxBytes", wireType)
}
m.MaxBytes = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.MaxBytes |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxGas", wireType)
}
m.MaxGas = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.MaxGas |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipParams(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthParams
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *EvidenceParams) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: EvidenceParams: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: EvidenceParams: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxAgeNumBlocks", wireType)
}
m.MaxAgeNumBlocks = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.MaxAgeNumBlocks |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxAgeDuration", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthParams
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthParams
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.MaxAgeDuration, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxBytes", wireType)
}
m.MaxBytes = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.MaxBytes |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipParams(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthParams
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ValidatorParams) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ValidatorParams: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ValidatorParams: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field PubKeyTypes", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthParams
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthParams
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.PubKeyTypes = append(m.PubKeyTypes, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipParams(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthParams
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *VersionParams) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: VersionParams: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: VersionParams: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field App", wireType)
}
m.App = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.App |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipParams(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthParams
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *HashedParams) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: HashedParams: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: HashedParams: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockMaxBytes", wireType)
}
m.BlockMaxBytes = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BlockMaxBytes |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockMaxGas", wireType)
}
m.BlockMaxGas = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BlockMaxGas |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipParams(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthParams
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ABCIParams) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ABCIParams: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ABCIParams: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field VoteExtensionsEnableHeight", wireType)
}
m.VoteExtensionsEnableHeight = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowParams
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.VoteExtensionsEnableHeight |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipParams(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthParams
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipParams(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowParams
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowParams
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowParams
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthParams
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupParams
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthParams
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowParams = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group")
)
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: tendermint/types/types.proto
package types
import (
fmt "fmt"
crypto "github.com/cometbft/cometbft/proto/tendermint/crypto"
version "github.com/cometbft/cometbft/proto/tendermint/version"
_ "github.com/cosmos/gogoproto/gogoproto"
proto "github.com/cosmos/gogoproto/proto"
_ "github.com/cosmos/gogoproto/types"
github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types"
io "io"
math "math"
math_bits "math/bits"
time "time"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
var _ = time.Kitchen
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// SignedMsgType is a type of signed message in the consensus.
type SignedMsgType int32
const (
UnknownType SignedMsgType = 0
// Votes
PrevoteType SignedMsgType = 1
PrecommitType SignedMsgType = 2
// Proposals
ProposalType SignedMsgType = 32
)
var SignedMsgType_name = map[int32]string{
0: "SIGNED_MSG_TYPE_UNKNOWN",
1: "SIGNED_MSG_TYPE_PREVOTE",
2: "SIGNED_MSG_TYPE_PRECOMMIT",
32: "SIGNED_MSG_TYPE_PROPOSAL",
}
var SignedMsgType_value = map[string]int32{
"SIGNED_MSG_TYPE_UNKNOWN": 0,
"SIGNED_MSG_TYPE_PREVOTE": 1,
"SIGNED_MSG_TYPE_PRECOMMIT": 2,
"SIGNED_MSG_TYPE_PROPOSAL": 32,
}
func (x SignedMsgType) String() string {
return proto.EnumName(SignedMsgType_name, int32(x))
}
func (SignedMsgType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{0}
}
// PartsetHeader
type PartSetHeader struct {
Total uint32 `protobuf:"varint,1,opt,name=total,proto3" json:"total,omitempty"`
Hash []byte `protobuf:"bytes,2,opt,name=hash,proto3" json:"hash,omitempty"`
}
func (m *PartSetHeader) Reset() { *m = PartSetHeader{} }
func (m *PartSetHeader) String() string { return proto.CompactTextString(m) }
func (*PartSetHeader) ProtoMessage() {}
func (*PartSetHeader) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{0}
}
func (m *PartSetHeader) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PartSetHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PartSetHeader.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PartSetHeader) XXX_Merge(src proto.Message) {
xxx_messageInfo_PartSetHeader.Merge(m, src)
}
func (m *PartSetHeader) XXX_Size() int {
return m.Size()
}
func (m *PartSetHeader) XXX_DiscardUnknown() {
xxx_messageInfo_PartSetHeader.DiscardUnknown(m)
}
var xxx_messageInfo_PartSetHeader proto.InternalMessageInfo
func (m *PartSetHeader) GetTotal() uint32 {
if m != nil {
return m.Total
}
return 0
}
func (m *PartSetHeader) GetHash() []byte {
if m != nil {
return m.Hash
}
return nil
}
type Part struct {
Index uint32 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Bytes []byte `protobuf:"bytes,2,opt,name=bytes,proto3" json:"bytes,omitempty"`
Proof crypto.Proof `protobuf:"bytes,3,opt,name=proof,proto3" json:"proof"`
}
func (m *Part) Reset() { *m = Part{} }
func (m *Part) String() string { return proto.CompactTextString(m) }
func (*Part) ProtoMessage() {}
func (*Part) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{1}
}
func (m *Part) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Part) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Part.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Part) XXX_Merge(src proto.Message) {
xxx_messageInfo_Part.Merge(m, src)
}
func (m *Part) XXX_Size() int {
return m.Size()
}
func (m *Part) XXX_DiscardUnknown() {
xxx_messageInfo_Part.DiscardUnknown(m)
}
var xxx_messageInfo_Part proto.InternalMessageInfo
func (m *Part) GetIndex() uint32 {
if m != nil {
return m.Index
}
return 0
}
func (m *Part) GetBytes() []byte {
if m != nil {
return m.Bytes
}
return nil
}
func (m *Part) GetProof() crypto.Proof {
if m != nil {
return m.Proof
}
return crypto.Proof{}
}
// BlockID
type BlockID struct {
Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"`
PartSetHeader PartSetHeader `protobuf:"bytes,2,opt,name=part_set_header,json=partSetHeader,proto3" json:"part_set_header"`
}
func (m *BlockID) Reset() { *m = BlockID{} }
func (m *BlockID) String() string { return proto.CompactTextString(m) }
func (*BlockID) ProtoMessage() {}
func (*BlockID) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{2}
}
func (m *BlockID) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *BlockID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_BlockID.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *BlockID) XXX_Merge(src proto.Message) {
xxx_messageInfo_BlockID.Merge(m, src)
}
func (m *BlockID) XXX_Size() int {
return m.Size()
}
func (m *BlockID) XXX_DiscardUnknown() {
xxx_messageInfo_BlockID.DiscardUnknown(m)
}
var xxx_messageInfo_BlockID proto.InternalMessageInfo
func (m *BlockID) GetHash() []byte {
if m != nil {
return m.Hash
}
return nil
}
func (m *BlockID) GetPartSetHeader() PartSetHeader {
if m != nil {
return m.PartSetHeader
}
return PartSetHeader{}
}
// Header defines the structure of a block header.
type Header struct {
// basic block info
Version version.Consensus `protobuf:"bytes,1,opt,name=version,proto3" json:"version"`
ChainID string `protobuf:"bytes,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"`
Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"`
Time time.Time `protobuf:"bytes,4,opt,name=time,proto3,stdtime" json:"time"`
// prev block info
LastBlockId BlockID `protobuf:"bytes,5,opt,name=last_block_id,json=lastBlockId,proto3" json:"last_block_id"`
// hashes of block data
LastCommitHash []byte `protobuf:"bytes,6,opt,name=last_commit_hash,json=lastCommitHash,proto3" json:"last_commit_hash,omitempty"`
DataHash []byte `protobuf:"bytes,7,opt,name=data_hash,json=dataHash,proto3" json:"data_hash,omitempty"`
// hashes from the app output from the prev block
ValidatorsHash []byte `protobuf:"bytes,8,opt,name=validators_hash,json=validatorsHash,proto3" json:"validators_hash,omitempty"`
NextValidatorsHash []byte `protobuf:"bytes,9,opt,name=next_validators_hash,json=nextValidatorsHash,proto3" json:"next_validators_hash,omitempty"`
ConsensusHash []byte `protobuf:"bytes,10,opt,name=consensus_hash,json=consensusHash,proto3" json:"consensus_hash,omitempty"`
AppHash []byte `protobuf:"bytes,11,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"`
LastResultsHash []byte `protobuf:"bytes,12,opt,name=last_results_hash,json=lastResultsHash,proto3" json:"last_results_hash,omitempty"`
// consensus info
EvidenceHash []byte `protobuf:"bytes,13,opt,name=evidence_hash,json=evidenceHash,proto3" json:"evidence_hash,omitempty"`
ProposerAddress []byte `protobuf:"bytes,14,opt,name=proposer_address,json=proposerAddress,proto3" json:"proposer_address,omitempty"`
}
func (m *Header) Reset() { *m = Header{} }
func (m *Header) String() string { return proto.CompactTextString(m) }
func (*Header) ProtoMessage() {}
func (*Header) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{3}
}
func (m *Header) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Header) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Header.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Header) XXX_Merge(src proto.Message) {
xxx_messageInfo_Header.Merge(m, src)
}
func (m *Header) XXX_Size() int {
return m.Size()
}
func (m *Header) XXX_DiscardUnknown() {
xxx_messageInfo_Header.DiscardUnknown(m)
}
var xxx_messageInfo_Header proto.InternalMessageInfo
func (m *Header) GetVersion() version.Consensus {
if m != nil {
return m.Version
}
return version.Consensus{}
}
func (m *Header) GetChainID() string {
if m != nil {
return m.ChainID
}
return ""
}
func (m *Header) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *Header) GetTime() time.Time {
if m != nil {
return m.Time
}
return time.Time{}
}
func (m *Header) GetLastBlockId() BlockID {
if m != nil {
return m.LastBlockId
}
return BlockID{}
}
func (m *Header) GetLastCommitHash() []byte {
if m != nil {
return m.LastCommitHash
}
return nil
}
func (m *Header) GetDataHash() []byte {
if m != nil {
return m.DataHash
}
return nil
}
func (m *Header) GetValidatorsHash() []byte {
if m != nil {
return m.ValidatorsHash
}
return nil
}
func (m *Header) GetNextValidatorsHash() []byte {
if m != nil {
return m.NextValidatorsHash
}
return nil
}
func (m *Header) GetConsensusHash() []byte {
if m != nil {
return m.ConsensusHash
}
return nil
}
func (m *Header) GetAppHash() []byte {
if m != nil {
return m.AppHash
}
return nil
}
func (m *Header) GetLastResultsHash() []byte {
if m != nil {
return m.LastResultsHash
}
return nil
}
func (m *Header) GetEvidenceHash() []byte {
if m != nil {
return m.EvidenceHash
}
return nil
}
func (m *Header) GetProposerAddress() []byte {
if m != nil {
return m.ProposerAddress
}
return nil
}
// Data contains the set of transactions included in the block
type Data struct {
// Txs that will be applied by state @ block.Height+1.
// NOTE: not all txs here are valid. We're just agreeing on the order first.
// This means that block.AppHash does not include these txs.
Txs [][]byte `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"`
}
func (m *Data) Reset() { *m = Data{} }
func (m *Data) String() string { return proto.CompactTextString(m) }
func (*Data) ProtoMessage() {}
func (*Data) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{4}
}
func (m *Data) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Data) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Data.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Data) XXX_Merge(src proto.Message) {
xxx_messageInfo_Data.Merge(m, src)
}
func (m *Data) XXX_Size() int {
return m.Size()
}
func (m *Data) XXX_DiscardUnknown() {
xxx_messageInfo_Data.DiscardUnknown(m)
}
var xxx_messageInfo_Data proto.InternalMessageInfo
func (m *Data) GetTxs() [][]byte {
if m != nil {
return m.Txs
}
return nil
}
// Vote represents a prevote or precommit vote from validators for
// consensus.
type Vote struct {
Type SignedMsgType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"`
Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"`
Round int32 `protobuf:"varint,3,opt,name=round,proto3" json:"round,omitempty"`
BlockID BlockID `protobuf:"bytes,4,opt,name=block_id,json=blockId,proto3" json:"block_id"`
Timestamp time.Time `protobuf:"bytes,5,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
ValidatorAddress []byte `protobuf:"bytes,6,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"`
ValidatorIndex int32 `protobuf:"varint,7,opt,name=validator_index,json=validatorIndex,proto3" json:"validator_index,omitempty"`
// Vote signature by the validator if they participated in consensus for the
// associated block.
Signature []byte `protobuf:"bytes,8,opt,name=signature,proto3" json:"signature,omitempty"`
// Vote extension provided by the application. Only valid for precommit
// messages.
Extension []byte `protobuf:"bytes,9,opt,name=extension,proto3" json:"extension,omitempty"`
// Vote extension signature by the validator if they participated in
// consensus for the associated block.
// Only valid for precommit messages.
ExtensionSignature []byte `protobuf:"bytes,10,opt,name=extension_signature,json=extensionSignature,proto3" json:"extension_signature,omitempty"`
}
func (m *Vote) Reset() { *m = Vote{} }
func (m *Vote) String() string { return proto.CompactTextString(m) }
func (*Vote) ProtoMessage() {}
func (*Vote) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{5}
}
func (m *Vote) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Vote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Vote.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Vote) XXX_Merge(src proto.Message) {
xxx_messageInfo_Vote.Merge(m, src)
}
func (m *Vote) XXX_Size() int {
return m.Size()
}
func (m *Vote) XXX_DiscardUnknown() {
xxx_messageInfo_Vote.DiscardUnknown(m)
}
var xxx_messageInfo_Vote proto.InternalMessageInfo
func (m *Vote) GetType() SignedMsgType {
if m != nil {
return m.Type
}
return UnknownType
}
func (m *Vote) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *Vote) GetRound() int32 {
if m != nil {
return m.Round
}
return 0
}
func (m *Vote) GetBlockID() BlockID {
if m != nil {
return m.BlockID
}
return BlockID{}
}
func (m *Vote) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
func (m *Vote) GetValidatorAddress() []byte {
if m != nil {
return m.ValidatorAddress
}
return nil
}
func (m *Vote) GetValidatorIndex() int32 {
if m != nil {
return m.ValidatorIndex
}
return 0
}
func (m *Vote) GetSignature() []byte {
if m != nil {
return m.Signature
}
return nil
}
func (m *Vote) GetExtension() []byte {
if m != nil {
return m.Extension
}
return nil
}
func (m *Vote) GetExtensionSignature() []byte {
if m != nil {
return m.ExtensionSignature
}
return nil
}
// Commit contains the evidence that a block was committed by a set of validators.
type Commit struct {
Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"`
Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"`
BlockID BlockID `protobuf:"bytes,3,opt,name=block_id,json=blockId,proto3" json:"block_id"`
Signatures []CommitSig `protobuf:"bytes,4,rep,name=signatures,proto3" json:"signatures"`
}
func (m *Commit) Reset() { *m = Commit{} }
func (m *Commit) String() string { return proto.CompactTextString(m) }
func (*Commit) ProtoMessage() {}
func (*Commit) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{6}
}
func (m *Commit) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Commit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Commit.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Commit) XXX_Merge(src proto.Message) {
xxx_messageInfo_Commit.Merge(m, src)
}
func (m *Commit) XXX_Size() int {
return m.Size()
}
func (m *Commit) XXX_DiscardUnknown() {
xxx_messageInfo_Commit.DiscardUnknown(m)
}
var xxx_messageInfo_Commit proto.InternalMessageInfo
func (m *Commit) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *Commit) GetRound() int32 {
if m != nil {
return m.Round
}
return 0
}
func (m *Commit) GetBlockID() BlockID {
if m != nil {
return m.BlockID
}
return BlockID{}
}
func (m *Commit) GetSignatures() []CommitSig {
if m != nil {
return m.Signatures
}
return nil
}
// CommitSig is a part of the Vote included in a Commit.
type CommitSig struct {
BlockIdFlag BlockIDFlag `protobuf:"varint,1,opt,name=block_id_flag,json=blockIdFlag,proto3,enum=tendermint.types.BlockIDFlag" json:"block_id_flag,omitempty"`
ValidatorAddress []byte `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
Signature []byte `protobuf:"bytes,4,opt,name=signature,proto3" json:"signature,omitempty"`
}
func (m *CommitSig) Reset() { *m = CommitSig{} }
func (m *CommitSig) String() string { return proto.CompactTextString(m) }
func (*CommitSig) ProtoMessage() {}
func (*CommitSig) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{7}
}
func (m *CommitSig) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *CommitSig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_CommitSig.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *CommitSig) XXX_Merge(src proto.Message) {
xxx_messageInfo_CommitSig.Merge(m, src)
}
func (m *CommitSig) XXX_Size() int {
return m.Size()
}
func (m *CommitSig) XXX_DiscardUnknown() {
xxx_messageInfo_CommitSig.DiscardUnknown(m)
}
var xxx_messageInfo_CommitSig proto.InternalMessageInfo
func (m *CommitSig) GetBlockIdFlag() BlockIDFlag {
if m != nil {
return m.BlockIdFlag
}
return BlockIDFlagUnknown
}
func (m *CommitSig) GetValidatorAddress() []byte {
if m != nil {
return m.ValidatorAddress
}
return nil
}
func (m *CommitSig) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
func (m *CommitSig) GetSignature() []byte {
if m != nil {
return m.Signature
}
return nil
}
type ExtendedCommit struct {
Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"`
Round int32 `protobuf:"varint,2,opt,name=round,proto3" json:"round,omitempty"`
BlockID BlockID `protobuf:"bytes,3,opt,name=block_id,json=blockId,proto3" json:"block_id"`
ExtendedSignatures []ExtendedCommitSig `protobuf:"bytes,4,rep,name=extended_signatures,json=extendedSignatures,proto3" json:"extended_signatures"`
}
func (m *ExtendedCommit) Reset() { *m = ExtendedCommit{} }
func (m *ExtendedCommit) String() string { return proto.CompactTextString(m) }
func (*ExtendedCommit) ProtoMessage() {}
func (*ExtendedCommit) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{8}
}
func (m *ExtendedCommit) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ExtendedCommit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ExtendedCommit.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ExtendedCommit) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExtendedCommit.Merge(m, src)
}
func (m *ExtendedCommit) XXX_Size() int {
return m.Size()
}
func (m *ExtendedCommit) XXX_DiscardUnknown() {
xxx_messageInfo_ExtendedCommit.DiscardUnknown(m)
}
var xxx_messageInfo_ExtendedCommit proto.InternalMessageInfo
func (m *ExtendedCommit) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *ExtendedCommit) GetRound() int32 {
if m != nil {
return m.Round
}
return 0
}
func (m *ExtendedCommit) GetBlockID() BlockID {
if m != nil {
return m.BlockID
}
return BlockID{}
}
func (m *ExtendedCommit) GetExtendedSignatures() []ExtendedCommitSig {
if m != nil {
return m.ExtendedSignatures
}
return nil
}
// ExtendedCommitSig retains all the same fields as CommitSig but adds vote
// extension-related fields. We use two signatures to ensure backwards compatibility.
// That is the digest of the original signature is still the same in prior versions
type ExtendedCommitSig struct {
BlockIdFlag BlockIDFlag `protobuf:"varint,1,opt,name=block_id_flag,json=blockIdFlag,proto3,enum=tendermint.types.BlockIDFlag" json:"block_id_flag,omitempty"`
ValidatorAddress []byte `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
Signature []byte `protobuf:"bytes,4,opt,name=signature,proto3" json:"signature,omitempty"`
// Vote extension data
Extension []byte `protobuf:"bytes,5,opt,name=extension,proto3" json:"extension,omitempty"`
// Vote extension signature
ExtensionSignature []byte `protobuf:"bytes,6,opt,name=extension_signature,json=extensionSignature,proto3" json:"extension_signature,omitempty"`
}
func (m *ExtendedCommitSig) Reset() { *m = ExtendedCommitSig{} }
func (m *ExtendedCommitSig) String() string { return proto.CompactTextString(m) }
func (*ExtendedCommitSig) ProtoMessage() {}
func (*ExtendedCommitSig) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{9}
}
func (m *ExtendedCommitSig) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ExtendedCommitSig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ExtendedCommitSig.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ExtendedCommitSig) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExtendedCommitSig.Merge(m, src)
}
func (m *ExtendedCommitSig) XXX_Size() int {
return m.Size()
}
func (m *ExtendedCommitSig) XXX_DiscardUnknown() {
xxx_messageInfo_ExtendedCommitSig.DiscardUnknown(m)
}
var xxx_messageInfo_ExtendedCommitSig proto.InternalMessageInfo
func (m *ExtendedCommitSig) GetBlockIdFlag() BlockIDFlag {
if m != nil {
return m.BlockIdFlag
}
return BlockIDFlagUnknown
}
func (m *ExtendedCommitSig) GetValidatorAddress() []byte {
if m != nil {
return m.ValidatorAddress
}
return nil
}
func (m *ExtendedCommitSig) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
func (m *ExtendedCommitSig) GetSignature() []byte {
if m != nil {
return m.Signature
}
return nil
}
func (m *ExtendedCommitSig) GetExtension() []byte {
if m != nil {
return m.Extension
}
return nil
}
func (m *ExtendedCommitSig) GetExtensionSignature() []byte {
if m != nil {
return m.ExtensionSignature
}
return nil
}
type Proposal struct {
Type SignedMsgType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.types.SignedMsgType" json:"type,omitempty"`
Height int64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"`
Round int32 `protobuf:"varint,3,opt,name=round,proto3" json:"round,omitempty"`
PolRound int32 `protobuf:"varint,4,opt,name=pol_round,json=polRound,proto3" json:"pol_round,omitempty"`
BlockID BlockID `protobuf:"bytes,5,opt,name=block_id,json=blockId,proto3" json:"block_id"`
Timestamp time.Time `protobuf:"bytes,6,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
Signature []byte `protobuf:"bytes,7,opt,name=signature,proto3" json:"signature,omitempty"`
}
func (m *Proposal) Reset() { *m = Proposal{} }
func (m *Proposal) String() string { return proto.CompactTextString(m) }
func (*Proposal) ProtoMessage() {}
func (*Proposal) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{10}
}
func (m *Proposal) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Proposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Proposal.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Proposal) XXX_Merge(src proto.Message) {
xxx_messageInfo_Proposal.Merge(m, src)
}
func (m *Proposal) XXX_Size() int {
return m.Size()
}
func (m *Proposal) XXX_DiscardUnknown() {
xxx_messageInfo_Proposal.DiscardUnknown(m)
}
var xxx_messageInfo_Proposal proto.InternalMessageInfo
func (m *Proposal) GetType() SignedMsgType {
if m != nil {
return m.Type
}
return UnknownType
}
func (m *Proposal) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *Proposal) GetRound() int32 {
if m != nil {
return m.Round
}
return 0
}
func (m *Proposal) GetPolRound() int32 {
if m != nil {
return m.PolRound
}
return 0
}
func (m *Proposal) GetBlockID() BlockID {
if m != nil {
return m.BlockID
}
return BlockID{}
}
func (m *Proposal) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
func (m *Proposal) GetSignature() []byte {
if m != nil {
return m.Signature
}
return nil
}
type SignedHeader struct {
Header *Header `protobuf:"bytes,1,opt,name=header,proto3" json:"header,omitempty"`
Commit *Commit `protobuf:"bytes,2,opt,name=commit,proto3" json:"commit,omitempty"`
}
func (m *SignedHeader) Reset() { *m = SignedHeader{} }
func (m *SignedHeader) String() string { return proto.CompactTextString(m) }
func (*SignedHeader) ProtoMessage() {}
func (*SignedHeader) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{11}
}
func (m *SignedHeader) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SignedHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SignedHeader.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SignedHeader) XXX_Merge(src proto.Message) {
xxx_messageInfo_SignedHeader.Merge(m, src)
}
func (m *SignedHeader) XXX_Size() int {
return m.Size()
}
func (m *SignedHeader) XXX_DiscardUnknown() {
xxx_messageInfo_SignedHeader.DiscardUnknown(m)
}
var xxx_messageInfo_SignedHeader proto.InternalMessageInfo
func (m *SignedHeader) GetHeader() *Header {
if m != nil {
return m.Header
}
return nil
}
func (m *SignedHeader) GetCommit() *Commit {
if m != nil {
return m.Commit
}
return nil
}
type LightBlock struct {
SignedHeader *SignedHeader `protobuf:"bytes,1,opt,name=signed_header,json=signedHeader,proto3" json:"signed_header,omitempty"`
ValidatorSet *ValidatorSet `protobuf:"bytes,2,opt,name=validator_set,json=validatorSet,proto3" json:"validator_set,omitempty"`
}
func (m *LightBlock) Reset() { *m = LightBlock{} }
func (m *LightBlock) String() string { return proto.CompactTextString(m) }
func (*LightBlock) ProtoMessage() {}
func (*LightBlock) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{12}
}
func (m *LightBlock) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *LightBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_LightBlock.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *LightBlock) XXX_Merge(src proto.Message) {
xxx_messageInfo_LightBlock.Merge(m, src)
}
func (m *LightBlock) XXX_Size() int {
return m.Size()
}
func (m *LightBlock) XXX_DiscardUnknown() {
xxx_messageInfo_LightBlock.DiscardUnknown(m)
}
var xxx_messageInfo_LightBlock proto.InternalMessageInfo
func (m *LightBlock) GetSignedHeader() *SignedHeader {
if m != nil {
return m.SignedHeader
}
return nil
}
func (m *LightBlock) GetValidatorSet() *ValidatorSet {
if m != nil {
return m.ValidatorSet
}
return nil
}
type BlockMeta struct {
BlockID BlockID `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id"`
BlockSize int64 `protobuf:"varint,2,opt,name=block_size,json=blockSize,proto3" json:"block_size,omitempty"`
Header Header `protobuf:"bytes,3,opt,name=header,proto3" json:"header"`
NumTxs int64 `protobuf:"varint,4,opt,name=num_txs,json=numTxs,proto3" json:"num_txs,omitempty"`
}
func (m *BlockMeta) Reset() { *m = BlockMeta{} }
func (m *BlockMeta) String() string { return proto.CompactTextString(m) }
func (*BlockMeta) ProtoMessage() {}
func (*BlockMeta) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{13}
}
func (m *BlockMeta) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *BlockMeta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_BlockMeta.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *BlockMeta) XXX_Merge(src proto.Message) {
xxx_messageInfo_BlockMeta.Merge(m, src)
}
func (m *BlockMeta) XXX_Size() int {
return m.Size()
}
func (m *BlockMeta) XXX_DiscardUnknown() {
xxx_messageInfo_BlockMeta.DiscardUnknown(m)
}
var xxx_messageInfo_BlockMeta proto.InternalMessageInfo
func (m *BlockMeta) GetBlockID() BlockID {
if m != nil {
return m.BlockID
}
return BlockID{}
}
func (m *BlockMeta) GetBlockSize() int64 {
if m != nil {
return m.BlockSize
}
return 0
}
func (m *BlockMeta) GetHeader() Header {
if m != nil {
return m.Header
}
return Header{}
}
func (m *BlockMeta) GetNumTxs() int64 {
if m != nil {
return m.NumTxs
}
return 0
}
// TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree.
type TxProof struct {
RootHash []byte `protobuf:"bytes,1,opt,name=root_hash,json=rootHash,proto3" json:"root_hash,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
Proof *crypto.Proof `protobuf:"bytes,3,opt,name=proof,proto3" json:"proof,omitempty"`
}
func (m *TxProof) Reset() { *m = TxProof{} }
func (m *TxProof) String() string { return proto.CompactTextString(m) }
func (*TxProof) ProtoMessage() {}
func (*TxProof) Descriptor() ([]byte, []int) {
return fileDescriptor_d3a6e55e2345de56, []int{14}
}
func (m *TxProof) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxProof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxProof.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxProof) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxProof.Merge(m, src)
}
func (m *TxProof) XXX_Size() int {
return m.Size()
}
func (m *TxProof) XXX_DiscardUnknown() {
xxx_messageInfo_TxProof.DiscardUnknown(m)
}
var xxx_messageInfo_TxProof proto.InternalMessageInfo
func (m *TxProof) GetRootHash() []byte {
if m != nil {
return m.RootHash
}
return nil
}
func (m *TxProof) GetData() []byte {
if m != nil {
return m.Data
}
return nil
}
func (m *TxProof) GetProof() *crypto.Proof {
if m != nil {
return m.Proof
}
return nil
}
func init() {
proto.RegisterEnum("tendermint.types.SignedMsgType", SignedMsgType_name, SignedMsgType_value)
proto.RegisterType((*PartSetHeader)(nil), "tendermint.types.PartSetHeader")
proto.RegisterType((*Part)(nil), "tendermint.types.Part")
proto.RegisterType((*BlockID)(nil), "tendermint.types.BlockID")
proto.RegisterType((*Header)(nil), "tendermint.types.Header")
proto.RegisterType((*Data)(nil), "tendermint.types.Data")
proto.RegisterType((*Vote)(nil), "tendermint.types.Vote")
proto.RegisterType((*Commit)(nil), "tendermint.types.Commit")
proto.RegisterType((*CommitSig)(nil), "tendermint.types.CommitSig")
proto.RegisterType((*ExtendedCommit)(nil), "tendermint.types.ExtendedCommit")
proto.RegisterType((*ExtendedCommitSig)(nil), "tendermint.types.ExtendedCommitSig")
proto.RegisterType((*Proposal)(nil), "tendermint.types.Proposal")
proto.RegisterType((*SignedHeader)(nil), "tendermint.types.SignedHeader")
proto.RegisterType((*LightBlock)(nil), "tendermint.types.LightBlock")
proto.RegisterType((*BlockMeta)(nil), "tendermint.types.BlockMeta")
proto.RegisterType((*TxProof)(nil), "tendermint.types.TxProof")
}
func init() { proto.RegisterFile("tendermint/types/types.proto", fileDescriptor_d3a6e55e2345de56) }
var fileDescriptor_d3a6e55e2345de56 = []byte{
// 1310 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x57, 0xcf, 0x6f, 0x1b, 0x45,
0x14, 0xce, 0xda, 0xeb, 0x5f, 0xcf, 0x76, 0xe2, 0x2c, 0x11, 0x75, 0xdd, 0xc6, 0xb1, 0x5c, 0x01,
0xa1, 0xa0, 0x4d, 0x95, 0x22, 0x04, 0x07, 0x0e, 0xf9, 0x45, 0x1b, 0x51, 0x27, 0xd6, 0xda, 0x2d,
0xa2, 0x97, 0xd5, 0xda, 0x3b, 0xb1, 0x97, 0xda, 0x3b, 0xab, 0xdd, 0x71, 0x70, 0xfa, 0x17, 0xa0,
0x9e, 0x7a, 0xe2, 0xd6, 0x13, 0x1c, 0xb8, 0x83, 0xc4, 0x15, 0x71, 0xea, 0xb1, 0x37, 0xb8, 0x50,
0x20, 0x95, 0xf8, 0x3b, 0xd0, 0xbc, 0x99, 0xdd, 0xb5, 0xe3, 0x18, 0xaa, 0xa8, 0x02, 0x89, 0x8b,
0xb5, 0xf3, 0xde, 0xf7, 0xde, 0xbc, 0x79, 0xdf, 0x37, 0xa3, 0x67, 0xb8, 0xca, 0x88, 0x6b, 0x13,
0x7f, 0xe8, 0xb8, 0x6c, 0x83, 0x9d, 0x78, 0x24, 0x10, 0xbf, 0xba, 0xe7, 0x53, 0x46, 0xb5, 0x52,
0xec, 0xd5, 0xd1, 0x5e, 0x59, 0xe9, 0xd1, 0x1e, 0x45, 0xe7, 0x06, 0xff, 0x12, 0xb8, 0xca, 0x5a,
0x8f, 0xd2, 0xde, 0x80, 0x6c, 0xe0, 0xaa, 0x33, 0x3a, 0xda, 0x60, 0xce, 0x90, 0x04, 0xcc, 0x1a,
0x7a, 0x12, 0xb0, 0x3a, 0xb1, 0x4d, 0xd7, 0x3f, 0xf1, 0x18, 0xe5, 0x58, 0x7a, 0x24, 0xdd, 0xd5,
0x09, 0xf7, 0x31, 0xf1, 0x03, 0x87, 0xba, 0x93, 0x75, 0x54, 0x6a, 0x33, 0x55, 0x1e, 0x5b, 0x03,
0xc7, 0xb6, 0x18, 0xf5, 0x05, 0xa2, 0xfe, 0x21, 0x14, 0x9b, 0x96, 0xcf, 0x5a, 0x84, 0xdd, 0x26,
0x96, 0x4d, 0x7c, 0x6d, 0x05, 0x52, 0x8c, 0x32, 0x6b, 0x50, 0x56, 0x6a, 0xca, 0x7a, 0xd1, 0x10,
0x0b, 0x4d, 0x03, 0xb5, 0x6f, 0x05, 0xfd, 0x72, 0xa2, 0xa6, 0xac, 0x17, 0x0c, 0xfc, 0xae, 0xf7,
0x41, 0xe5, 0xa1, 0x3c, 0xc2, 0x71, 0x6d, 0x32, 0x0e, 0x23, 0x70, 0xc1, 0xad, 0x9d, 0x13, 0x46,
0x02, 0x19, 0x22, 0x16, 0xda, 0x7b, 0x90, 0xc2, 0xfa, 0xcb, 0xc9, 0x9a, 0xb2, 0x9e, 0xdf, 0x2c,
0xeb, 0x13, 0x8d, 0x12, 0xe7, 0xd3, 0x9b, 0xdc, 0xbf, 0xad, 0x3e, 0x7d, 0xbe, 0xb6, 0x60, 0x08,
0x70, 0x7d, 0x00, 0x99, 0xed, 0x01, 0xed, 0x3e, 0xd8, 0xdf, 0x8d, 0x0a, 0x51, 0xe2, 0x42, 0xb4,
0x06, 0x2c, 0x79, 0x96, 0xcf, 0xcc, 0x80, 0x30, 0xb3, 0x8f, 0xa7, 0xc0, 0x4d, 0xf3, 0x9b, 0x6b,
0xfa, 0x59, 0x1e, 0xf4, 0xa9, 0xc3, 0xca, 0x5d, 0x8a, 0xde, 0xa4, 0xb1, 0xfe, 0xa7, 0x0a, 0x69,
0xd9, 0x8c, 0x8f, 0x20, 0x23, 0xdb, 0x8a, 0x1b, 0xe6, 0x37, 0x57, 0x27, 0x33, 0x4a, 0x97, 0xbe,
0x43, 0xdd, 0x80, 0xb8, 0xc1, 0x28, 0x90, 0xf9, 0xc2, 0x18, 0xed, 0x4d, 0xc8, 0x76, 0xfb, 0x96,
0xe3, 0x9a, 0x8e, 0x8d, 0x15, 0xe5, 0xb6, 0xf3, 0xa7, 0xcf, 0xd7, 0x32, 0x3b, 0xdc, 0xb6, 0xbf,
0x6b, 0x64, 0xd0, 0xb9, 0x6f, 0x6b, 0xaf, 0x43, 0xba, 0x4f, 0x9c, 0x5e, 0x9f, 0x61, 0x5b, 0x92,
0x86, 0x5c, 0x69, 0x1f, 0x80, 0xca, 0x05, 0x51, 0x56, 0x71, 0xef, 0x8a, 0x2e, 0xd4, 0xa2, 0x87,
0x6a, 0xd1, 0xdb, 0xa1, 0x5a, 0xb6, 0xb3, 0x7c, 0xe3, 0xc7, 0xbf, 0xad, 0x29, 0x06, 0x46, 0x68,
0x3b, 0x50, 0x1c, 0x58, 0x01, 0x33, 0x3b, 0xbc, 0x6d, 0x7c, 0xfb, 0x14, 0xa6, 0xb8, 0x3c, 0xdb,
0x10, 0xd9, 0x58, 0x59, 0x7a, 0x9e, 0x47, 0x09, 0x93, 0xad, 0xad, 0x43, 0x09, 0x93, 0x74, 0xe9,
0x70, 0xe8, 0x30, 0x13, 0xfb, 0x9e, 0xc6, 0xbe, 0x2f, 0x72, 0xfb, 0x0e, 0x9a, 0x6f, 0x73, 0x06,
0xae, 0x40, 0xce, 0xb6, 0x98, 0x25, 0x20, 0x19, 0x84, 0x64, 0xb9, 0x01, 0x9d, 0x6f, 0xc1, 0x52,
0xa4, 0xba, 0x40, 0x40, 0xb2, 0x22, 0x4b, 0x6c, 0x46, 0xe0, 0x0d, 0x58, 0x71, 0xc9, 0x98, 0x99,
0x67, 0xd1, 0x39, 0x44, 0x6b, 0xdc, 0x77, 0x6f, 0x3a, 0xe2, 0x0d, 0x58, 0xec, 0x86, 0xcd, 0x17,
0x58, 0x40, 0x6c, 0x31, 0xb2, 0x22, 0xec, 0x32, 0x64, 0x2d, 0xcf, 0x13, 0x80, 0x3c, 0x02, 0x32,
0x96, 0xe7, 0xa1, 0xeb, 0x3a, 0x2c, 0xe3, 0x19, 0x7d, 0x12, 0x8c, 0x06, 0x4c, 0x26, 0x29, 0x20,
0x66, 0x89, 0x3b, 0x0c, 0x61, 0x47, 0xec, 0x35, 0x28, 0x92, 0x63, 0xc7, 0x26, 0x6e, 0x97, 0x08,
0x5c, 0x11, 0x71, 0x85, 0xd0, 0x88, 0xa0, 0xb7, 0xa1, 0xe4, 0xf9, 0xd4, 0xa3, 0x01, 0xf1, 0x4d,
0xcb, 0xb6, 0x7d, 0x12, 0x04, 0xe5, 0x45, 0x91, 0x2f, 0xb4, 0x6f, 0x09, 0x73, 0xbd, 0x0c, 0xea,
0xae, 0xc5, 0x2c, 0xad, 0x04, 0x49, 0x36, 0x0e, 0xca, 0x4a, 0x2d, 0xb9, 0x5e, 0x30, 0xf8, 0x67,
0xfd, 0x87, 0x24, 0xa8, 0xf7, 0x28, 0x23, 0xda, 0x4d, 0x50, 0x39, 0x4d, 0xa8, 0xbe, 0xc5, 0xf3,
0xf4, 0xdc, 0x72, 0x7a, 0x2e, 0xb1, 0x1b, 0x41, 0xaf, 0x7d, 0xe2, 0x11, 0x03, 0xc1, 0x13, 0x72,
0x4a, 0x4c, 0xc9, 0x69, 0x05, 0x52, 0x3e, 0x1d, 0xb9, 0x36, 0xaa, 0x2c, 0x65, 0x88, 0x85, 0xb6,
0x07, 0xd9, 0x48, 0x25, 0xea, 0x3f, 0xa9, 0x64, 0x89, 0xab, 0x84, 0x6b, 0x58, 0x1a, 0x8c, 0x4c,
0x47, 0x8a, 0x65, 0x1b, 0x72, 0xd1, 0xe3, 0x25, 0xd5, 0xf6, 0x72, 0x82, 0x8d, 0xc3, 0xb4, 0x77,
0x60, 0x39, 0xe2, 0x3e, 0x6a, 0x9e, 0x50, 0x5c, 0x29, 0x72, 0xc8, 0xee, 0x4d, 0xc9, 0xca, 0x14,
0x0f, 0x50, 0x06, 0xcf, 0x15, 0xcb, 0x6a, 0x1f, 0x5f, 0xa2, 0xab, 0x90, 0x0b, 0x9c, 0x9e, 0x6b,
0xb1, 0x91, 0x4f, 0xa4, 0xf2, 0x62, 0x03, 0xf7, 0x92, 0x31, 0x23, 0x2e, 0x5e, 0x72, 0xa1, 0xb4,
0xd8, 0xa0, 0x6d, 0xc0, 0x6b, 0xd1, 0xc2, 0x8c, 0xb3, 0x08, 0x95, 0x69, 0x91, 0xab, 0x15, 0x7a,
0xea, 0x3f, 0x2a, 0x90, 0x16, 0x17, 0x63, 0x82, 0x06, 0xe5, 0x7c, 0x1a, 0x12, 0xf3, 0x68, 0x48,
0x5e, 0x9c, 0x86, 0x2d, 0x80, 0xa8, 0xcc, 0xa0, 0xac, 0xd6, 0x92, 0xeb, 0xf9, 0xcd, 0x2b, 0xb3,
0x89, 0x44, 0x89, 0x2d, 0xa7, 0x27, 0xef, 0xfd, 0x44, 0x50, 0xfd, 0x57, 0x05, 0x72, 0x91, 0x5f,
0xdb, 0x82, 0x62, 0x58, 0x97, 0x79, 0x34, 0xb0, 0x7a, 0x52, 0x8a, 0xab, 0x73, 0x8b, 0xfb, 0x78,
0x60, 0xf5, 0x8c, 0xbc, 0xac, 0x87, 0x2f, 0xce, 0xa7, 0x35, 0x31, 0x87, 0xd6, 0x29, 0x1d, 0x25,
0x2f, 0xa6, 0xa3, 0x29, 0xc6, 0xd5, 0x33, 0x8c, 0xd7, 0xff, 0x50, 0x60, 0x71, 0x6f, 0x8c, 0xe5,
0xdb, 0xff, 0x25, 0x55, 0xf7, 0xa5, 0xb6, 0x6c, 0x62, 0x9b, 0x33, 0x9c, 0x5d, 0x9b, 0xcd, 0x38,
0x5d, 0x73, 0xcc, 0x9d, 0x16, 0x66, 0x69, 0xc5, 0x1c, 0x7e, 0x9f, 0x80, 0xe5, 0x19, 0xfc, 0xff,
0x8f, 0xcb, 0xe9, 0xdb, 0x9b, 0x7a, 0xc9, 0xdb, 0x9b, 0x9e, 0x7b, 0x7b, 0xbf, 0x4b, 0x40, 0xb6,
0x89, 0xaf, 0xb4, 0x35, 0xf8, 0x37, 0xde, 0xde, 0x2b, 0x90, 0xf3, 0xe8, 0xc0, 0x14, 0x1e, 0x15,
0x3d, 0x59, 0x8f, 0x0e, 0x8c, 0x19, 0x99, 0xa5, 0x5e, 0xd1, 0xc3, 0x9c, 0x7e, 0x05, 0x24, 0x64,
0xce, 0x5e, 0x28, 0x1f, 0x0a, 0xa2, 0x15, 0x72, 0x6a, 0xba, 0xc1, 0x7b, 0x80, 0x63, 0x98, 0x32,
0x3b, 0xe5, 0x89, 0xb2, 0x05, 0xd2, 0x90, 0x38, 0x1e, 0x21, 0x86, 0x0c, 0x39, 0xb8, 0x95, 0xe7,
0xbd, 0x58, 0x86, 0xc4, 0xd5, 0xbf, 0x52, 0x00, 0xee, 0xf0, 0xce, 0xe2, 0x79, 0xf9, 0xbc, 0x13,
0x60, 0x09, 0xe6, 0xd4, 0xce, 0xd5, 0x79, 0xa4, 0xc9, 0xfd, 0x0b, 0xc1, 0x64, 0xdd, 0x3b, 0x50,
0x8c, 0xb5, 0x1d, 0x90, 0xb0, 0x98, 0x73, 0x92, 0x44, 0x63, 0x48, 0x8b, 0x30, 0xa3, 0x70, 0x3c,
0xb1, 0xaa, 0xff, 0xa4, 0x40, 0x0e, 0x6b, 0x6a, 0x10, 0x66, 0x4d, 0x71, 0xa8, 0x5c, 0x9c, 0xc3,
0x55, 0x00, 0x91, 0x26, 0x70, 0x1e, 0x12, 0xa9, 0xac, 0x1c, 0x5a, 0x5a, 0xce, 0x43, 0xa2, 0xbd,
0x1f, 0x35, 0x3c, 0xf9, 0xf7, 0x0d, 0x97, 0x2f, 0x46, 0xd8, 0xf6, 0x4b, 0x90, 0x71, 0x47, 0x43,
0x93, 0x0f, 0x1f, 0xaa, 0x50, 0xab, 0x3b, 0x1a, 0xb6, 0xc7, 0x41, 0xfd, 0x73, 0xc8, 0xb4, 0xc7,
0x38, 0x88, 0x73, 0x89, 0xfa, 0x94, 0xca, 0xe9, 0x4f, 0x4c, 0xdd, 0x59, 0x6e, 0xc0, 0x61, 0x47,
0x03, 0x95, 0x8f, 0x79, 0xe1, 0xdf, 0x02, 0xfe, 0xad, 0xe9, 0x2f, 0x39, 0xe2, 0xcb, 0xe1, 0xfe,
0xfa, 0xcf, 0x0a, 0x14, 0xa7, 0x6e, 0x92, 0xf6, 0x2e, 0x5c, 0x6a, 0xed, 0xdf, 0x3a, 0xd8, 0xdb,
0x35, 0x1b, 0xad, 0x5b, 0x66, 0xfb, 0xb3, 0xe6, 0x9e, 0x79, 0xf7, 0xe0, 0x93, 0x83, 0xc3, 0x4f,
0x0f, 0x4a, 0x0b, 0x95, 0xa5, 0x47, 0x4f, 0x6a, 0xf9, 0xbb, 0xee, 0x03, 0x97, 0x7e, 0xe1, 0xce,
0x43, 0x37, 0x8d, 0xbd, 0x7b, 0x87, 0xed, 0xbd, 0x92, 0x22, 0xd0, 0x4d, 0x9f, 0x1c, 0x53, 0x46,
0x10, 0x7d, 0x03, 0x2e, 0x9f, 0x83, 0xde, 0x39, 0x6c, 0x34, 0xf6, 0xdb, 0xa5, 0x44, 0x65, 0xf9,
0xd1, 0x93, 0x5a, 0xb1, 0xe9, 0x13, 0xa1, 0x32, 0x8c, 0xd0, 0xa1, 0x3c, 0x1b, 0x71, 0xd8, 0x3c,
0x6c, 0x6d, 0xdd, 0x29, 0xd5, 0x2a, 0xa5, 0x47, 0x4f, 0x6a, 0x85, 0xf0, 0xc9, 0xe0, 0xf8, 0x4a,
0xf6, 0xcb, 0xaf, 0xab, 0x0b, 0xdf, 0x7e, 0x53, 0x55, 0xb6, 0x1b, 0x4f, 0x4f, 0xab, 0xca, 0xb3,
0xd3, 0xaa, 0xf2, 0xfb, 0x69, 0x55, 0x79, 0xfc, 0xa2, 0xba, 0xf0, 0xec, 0x45, 0x75, 0xe1, 0x97,
0x17, 0xd5, 0x85, 0xfb, 0x37, 0x7b, 0x0e, 0xeb, 0x8f, 0x3a, 0x7a, 0x97, 0x0e, 0x37, 0xba, 0x74,
0x48, 0x58, 0xe7, 0x88, 0xc5, 0x1f, 0xe2, 0x6f, 0xe2, 0xd9, 0xbf, 0x6e, 0x9d, 0x34, 0xda, 0x6f,
0xfe, 0x15, 0x00, 0x00, 0xff, 0xff, 0x8c, 0xb6, 0xa1, 0x4e, 0x7b, 0x0e, 0x00, 0x00,
}
func (m *PartSetHeader) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PartSetHeader) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PartSetHeader) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Hash) > 0 {
i -= len(m.Hash)
copy(dAtA[i:], m.Hash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash)))
i--
dAtA[i] = 0x12
}
if m.Total != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Total))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Part) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Part) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Part) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.Proof.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
if len(m.Bytes) > 0 {
i -= len(m.Bytes)
copy(dAtA[i:], m.Bytes)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Bytes)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *BlockID) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *BlockID) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *BlockID) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.PartSetHeader.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
if len(m.Hash) > 0 {
i -= len(m.Hash)
copy(dAtA[i:], m.Hash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Hash)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *Header) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Header) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Header) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.ProposerAddress) > 0 {
i -= len(m.ProposerAddress)
copy(dAtA[i:], m.ProposerAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ProposerAddress)))
i--
dAtA[i] = 0x72
}
if len(m.EvidenceHash) > 0 {
i -= len(m.EvidenceHash)
copy(dAtA[i:], m.EvidenceHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.EvidenceHash)))
i--
dAtA[i] = 0x6a
}
if len(m.LastResultsHash) > 0 {
i -= len(m.LastResultsHash)
copy(dAtA[i:], m.LastResultsHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.LastResultsHash)))
i--
dAtA[i] = 0x62
}
if len(m.AppHash) > 0 {
i -= len(m.AppHash)
copy(dAtA[i:], m.AppHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.AppHash)))
i--
dAtA[i] = 0x5a
}
if len(m.ConsensusHash) > 0 {
i -= len(m.ConsensusHash)
copy(dAtA[i:], m.ConsensusHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ConsensusHash)))
i--
dAtA[i] = 0x52
}
if len(m.NextValidatorsHash) > 0 {
i -= len(m.NextValidatorsHash)
copy(dAtA[i:], m.NextValidatorsHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.NextValidatorsHash)))
i--
dAtA[i] = 0x4a
}
if len(m.ValidatorsHash) > 0 {
i -= len(m.ValidatorsHash)
copy(dAtA[i:], m.ValidatorsHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorsHash)))
i--
dAtA[i] = 0x42
}
if len(m.DataHash) > 0 {
i -= len(m.DataHash)
copy(dAtA[i:], m.DataHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.DataHash)))
i--
dAtA[i] = 0x3a
}
if len(m.LastCommitHash) > 0 {
i -= len(m.LastCommitHash)
copy(dAtA[i:], m.LastCommitHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.LastCommitHash)))
i--
dAtA[i] = 0x32
}
{
size, err := m.LastBlockId.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x2a
n4, err4 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Time, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time):])
if err4 != nil {
return 0, err4
}
i -= n4
i = encodeVarintTypes(dAtA, i, uint64(n4))
i--
dAtA[i] = 0x22
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x18
}
if len(m.ChainID) > 0 {
i -= len(m.ChainID)
copy(dAtA[i:], m.ChainID)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainID)))
i--
dAtA[i] = 0x12
}
{
size, err := m.Version.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *Data) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Data) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Data) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Txs[iNdEx])
copy(dAtA[i:], m.Txs[iNdEx])
i = encodeVarintTypes(dAtA, i, uint64(len(m.Txs[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *Vote) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Vote) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Vote) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.ExtensionSignature) > 0 {
i -= len(m.ExtensionSignature)
copy(dAtA[i:], m.ExtensionSignature)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ExtensionSignature)))
i--
dAtA[i] = 0x52
}
if len(m.Extension) > 0 {
i -= len(m.Extension)
copy(dAtA[i:], m.Extension)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Extension)))
i--
dAtA[i] = 0x4a
}
if len(m.Signature) > 0 {
i -= len(m.Signature)
copy(dAtA[i:], m.Signature)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Signature)))
i--
dAtA[i] = 0x42
}
if m.ValidatorIndex != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.ValidatorIndex))
i--
dAtA[i] = 0x38
}
if len(m.ValidatorAddress) > 0 {
i -= len(m.ValidatorAddress)
copy(dAtA[i:], m.ValidatorAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorAddress)))
i--
dAtA[i] = 0x32
}
n6, err6 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):])
if err6 != nil {
return 0, err6
}
i -= n6
i = encodeVarintTypes(dAtA, i, uint64(n6))
i--
dAtA[i] = 0x2a
{
size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
if m.Round != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Round))
i--
dAtA[i] = 0x18
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x10
}
if m.Type != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Type))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Commit) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Commit) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Commit) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Signatures) > 0 {
for iNdEx := len(m.Signatures) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Signatures[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
}
{
size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
if m.Round != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Round))
i--
dAtA[i] = 0x10
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *CommitSig) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *CommitSig) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *CommitSig) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Signature) > 0 {
i -= len(m.Signature)
copy(dAtA[i:], m.Signature)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Signature)))
i--
dAtA[i] = 0x22
}
n9, err9 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):])
if err9 != nil {
return 0, err9
}
i -= n9
i = encodeVarintTypes(dAtA, i, uint64(n9))
i--
dAtA[i] = 0x1a
if len(m.ValidatorAddress) > 0 {
i -= len(m.ValidatorAddress)
copy(dAtA[i:], m.ValidatorAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorAddress)))
i--
dAtA[i] = 0x12
}
if m.BlockIdFlag != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.BlockIdFlag))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ExtendedCommit) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ExtendedCommit) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ExtendedCommit) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.ExtendedSignatures) > 0 {
for iNdEx := len(m.ExtendedSignatures) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.ExtendedSignatures[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
}
{
size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
if m.Round != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Round))
i--
dAtA[i] = 0x10
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ExtendedCommitSig) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ExtendedCommitSig) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ExtendedCommitSig) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.ExtensionSignature) > 0 {
i -= len(m.ExtensionSignature)
copy(dAtA[i:], m.ExtensionSignature)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ExtensionSignature)))
i--
dAtA[i] = 0x32
}
if len(m.Extension) > 0 {
i -= len(m.Extension)
copy(dAtA[i:], m.Extension)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Extension)))
i--
dAtA[i] = 0x2a
}
if len(m.Signature) > 0 {
i -= len(m.Signature)
copy(dAtA[i:], m.Signature)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Signature)))
i--
dAtA[i] = 0x22
}
n11, err11 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):])
if err11 != nil {
return 0, err11
}
i -= n11
i = encodeVarintTypes(dAtA, i, uint64(n11))
i--
dAtA[i] = 0x1a
if len(m.ValidatorAddress) > 0 {
i -= len(m.ValidatorAddress)
copy(dAtA[i:], m.ValidatorAddress)
i = encodeVarintTypes(dAtA, i, uint64(len(m.ValidatorAddress)))
i--
dAtA[i] = 0x12
}
if m.BlockIdFlag != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.BlockIdFlag))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Proposal) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Proposal) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Proposal) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Signature) > 0 {
i -= len(m.Signature)
copy(dAtA[i:], m.Signature)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Signature)))
i--
dAtA[i] = 0x3a
}
n12, err12 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp):])
if err12 != nil {
return 0, err12
}
i -= n12
i = encodeVarintTypes(dAtA, i, uint64(n12))
i--
dAtA[i] = 0x32
{
size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x2a
if m.PolRound != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.PolRound))
i--
dAtA[i] = 0x20
}
if m.Round != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Round))
i--
dAtA[i] = 0x18
}
if m.Height != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x10
}
if m.Type != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.Type))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *SignedHeader) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SignedHeader) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SignedHeader) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Commit != nil {
{
size, err := m.Commit.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if m.Header != nil {
{
size, err := m.Header.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *LightBlock) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *LightBlock) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *LightBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.ValidatorSet != nil {
{
size, err := m.ValidatorSet.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if m.SignedHeader != nil {
{
size, err := m.SignedHeader.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *BlockMeta) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *BlockMeta) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *BlockMeta) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.NumTxs != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.NumTxs))
i--
dAtA[i] = 0x20
}
{
size, err := m.Header.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
if m.BlockSize != 0 {
i = encodeVarintTypes(dAtA, i, uint64(m.BlockSize))
i--
dAtA[i] = 0x10
}
{
size, err := m.BlockID.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *TxProof) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxProof) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxProof) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Proof != nil {
{
size, err := m.Proof.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTypes(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintTypes(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0x12
}
if len(m.RootHash) > 0 {
i -= len(m.RootHash)
copy(dAtA[i:], m.RootHash)
i = encodeVarintTypes(dAtA, i, uint64(len(m.RootHash)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintTypes(dAtA []byte, offset int, v uint64) int {
offset -= sovTypes(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *PartSetHeader) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Total != 0 {
n += 1 + sovTypes(uint64(m.Total))
}
l = len(m.Hash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Part) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovTypes(uint64(m.Index))
}
l = len(m.Bytes)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = m.Proof.Size()
n += 1 + l + sovTypes(uint64(l))
return n
}
func (m *BlockID) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Hash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = m.PartSetHeader.Size()
n += 1 + l + sovTypes(uint64(l))
return n
}
func (m *Header) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.Version.Size()
n += 1 + l + sovTypes(uint64(l))
l = len(m.ChainID)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Time)
n += 1 + l + sovTypes(uint64(l))
l = m.LastBlockId.Size()
n += 1 + l + sovTypes(uint64(l))
l = len(m.LastCommitHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.DataHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ValidatorsHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.NextValidatorsHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ConsensusHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.AppHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.LastResultsHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.EvidenceHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ProposerAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Data) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Txs) > 0 {
for _, b := range m.Txs {
l = len(b)
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *Vote) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Type != 0 {
n += 1 + sovTypes(uint64(m.Type))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
if m.Round != 0 {
n += 1 + sovTypes(uint64(m.Round))
}
l = m.BlockID.Size()
n += 1 + l + sovTypes(uint64(l))
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovTypes(uint64(l))
l = len(m.ValidatorAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.ValidatorIndex != 0 {
n += 1 + sovTypes(uint64(m.ValidatorIndex))
}
l = len(m.Signature)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Extension)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ExtensionSignature)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Commit) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
if m.Round != 0 {
n += 1 + sovTypes(uint64(m.Round))
}
l = m.BlockID.Size()
n += 1 + l + sovTypes(uint64(l))
if len(m.Signatures) > 0 {
for _, e := range m.Signatures {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *CommitSig) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.BlockIdFlag != 0 {
n += 1 + sovTypes(uint64(m.BlockIdFlag))
}
l = len(m.ValidatorAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovTypes(uint64(l))
l = len(m.Signature)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *ExtendedCommit) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
if m.Round != 0 {
n += 1 + sovTypes(uint64(m.Round))
}
l = m.BlockID.Size()
n += 1 + l + sovTypes(uint64(l))
if len(m.ExtendedSignatures) > 0 {
for _, e := range m.ExtendedSignatures {
l = e.Size()
n += 1 + l + sovTypes(uint64(l))
}
}
return n
}
func (m *ExtendedCommitSig) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.BlockIdFlag != 0 {
n += 1 + sovTypes(uint64(m.BlockIdFlag))
}
l = len(m.ValidatorAddress)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovTypes(uint64(l))
l = len(m.Signature)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Extension)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.ExtensionSignature)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *Proposal) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Type != 0 {
n += 1 + sovTypes(uint64(m.Type))
}
if m.Height != 0 {
n += 1 + sovTypes(uint64(m.Height))
}
if m.Round != 0 {
n += 1 + sovTypes(uint64(m.Round))
}
if m.PolRound != 0 {
n += 1 + sovTypes(uint64(m.PolRound))
}
l = m.BlockID.Size()
n += 1 + l + sovTypes(uint64(l))
l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovTypes(uint64(l))
l = len(m.Signature)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *SignedHeader) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Header != nil {
l = m.Header.Size()
n += 1 + l + sovTypes(uint64(l))
}
if m.Commit != nil {
l = m.Commit.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *LightBlock) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.SignedHeader != nil {
l = m.SignedHeader.Size()
n += 1 + l + sovTypes(uint64(l))
}
if m.ValidatorSet != nil {
l = m.ValidatorSet.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func (m *BlockMeta) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.BlockID.Size()
n += 1 + l + sovTypes(uint64(l))
if m.BlockSize != 0 {
n += 1 + sovTypes(uint64(m.BlockSize))
}
l = m.Header.Size()
n += 1 + l + sovTypes(uint64(l))
if m.NumTxs != 0 {
n += 1 + sovTypes(uint64(m.NumTxs))
}
return n
}
func (m *TxProof) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.RootHash)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
l = len(m.Data)
if l > 0 {
n += 1 + l + sovTypes(uint64(l))
}
if m.Proof != nil {
l = m.Proof.Size()
n += 1 + l + sovTypes(uint64(l))
}
return n
}
func sovTypes(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozTypes(x uint64) (n int) {
return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *PartSetHeader) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PartSetHeader: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PartSetHeader: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType)
}
m.Total = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Total |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...)
if m.Hash == nil {
m.Hash = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Part) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Part: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Part: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Bytes", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Bytes = append(m.Bytes[:0], dAtA[iNdEx:postIndex]...)
if m.Bytes == nil {
m.Bytes = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Proof.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *BlockID) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: BlockID: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: BlockID: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...)
if m.Hash == nil {
m.Hash = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field PartSetHeader", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.PartSetHeader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Header) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Header: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Header: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Version.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ChainID", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ChainID = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Time, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LastBlockId", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.LastBlockId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LastCommitHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.LastCommitHash = append(m.LastCommitHash[:0], dAtA[iNdEx:postIndex]...)
if m.LastCommitHash == nil {
m.LastCommitHash = []byte{}
}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DataHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.DataHash = append(m.DataHash[:0], dAtA[iNdEx:postIndex]...)
if m.DataHash == nil {
m.DataHash = []byte{}
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidatorsHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ValidatorsHash = append(m.ValidatorsHash[:0], dAtA[iNdEx:postIndex]...)
if m.ValidatorsHash == nil {
m.ValidatorsHash = []byte{}
}
iNdEx = postIndex
case 9:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...)
if m.NextValidatorsHash == nil {
m.NextValidatorsHash = []byte{}
}
iNdEx = postIndex
case 10:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ConsensusHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ConsensusHash = append(m.ConsensusHash[:0], dAtA[iNdEx:postIndex]...)
if m.ConsensusHash == nil {
m.ConsensusHash = []byte{}
}
iNdEx = postIndex
case 11:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AppHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AppHash = append(m.AppHash[:0], dAtA[iNdEx:postIndex]...)
if m.AppHash == nil {
m.AppHash = []byte{}
}
iNdEx = postIndex
case 12:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LastResultsHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.LastResultsHash = append(m.LastResultsHash[:0], dAtA[iNdEx:postIndex]...)
if m.LastResultsHash == nil {
m.LastResultsHash = []byte{}
}
iNdEx = postIndex
case 13:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field EvidenceHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.EvidenceHash = append(m.EvidenceHash[:0], dAtA[iNdEx:postIndex]...)
if m.EvidenceHash == nil {
m.EvidenceHash = []byte{}
}
iNdEx = postIndex
case 14:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposerAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ProposerAddress = append(m.ProposerAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ProposerAddress == nil {
m.ProposerAddress = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Data) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Data: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Data: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, make([]byte, postIndex-iNdEx))
copy(m.Txs[len(m.Txs)-1], dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Vote) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Vote: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Vote: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
m.Type = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Type |= SignedMsgType(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType)
}
m.Round = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Round |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ValidatorAddress = append(m.ValidatorAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ValidatorAddress == nil {
m.ValidatorAddress = []byte{}
}
iNdEx = postIndex
case 7:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidatorIndex", wireType)
}
m.ValidatorIndex = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.ValidatorIndex |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...)
if m.Signature == nil {
m.Signature = []byte{}
}
iNdEx = postIndex
case 9:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Extension = append(m.Extension[:0], dAtA[iNdEx:postIndex]...)
if m.Extension == nil {
m.Extension = []byte{}
}
iNdEx = postIndex
case 10:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ExtensionSignature", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ExtensionSignature = append(m.ExtensionSignature[:0], dAtA[iNdEx:postIndex]...)
if m.ExtensionSignature == nil {
m.ExtensionSignature = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Commit) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Commit: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Commit: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType)
}
m.Round = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Round |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Signatures", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Signatures = append(m.Signatures, CommitSig{})
if err := m.Signatures[len(m.Signatures)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *CommitSig) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: CommitSig: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: CommitSig: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockIdFlag", wireType)
}
m.BlockIdFlag = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BlockIdFlag |= BlockIDFlag(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ValidatorAddress = append(m.ValidatorAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ValidatorAddress == nil {
m.ValidatorAddress = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...)
if m.Signature == nil {
m.Signature = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ExtendedCommit) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ExtendedCommit: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ExtendedCommit: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType)
}
m.Round = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Round |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ExtendedSignatures", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ExtendedSignatures = append(m.ExtendedSignatures, ExtendedCommitSig{})
if err := m.ExtendedSignatures[len(m.ExtendedSignatures)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ExtendedCommitSig) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ExtendedCommitSig: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ExtendedCommitSig: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockIdFlag", wireType)
}
m.BlockIdFlag = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BlockIdFlag |= BlockIDFlag(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ValidatorAddress = append(m.ValidatorAddress[:0], dAtA[iNdEx:postIndex]...)
if m.ValidatorAddress == nil {
m.ValidatorAddress = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...)
if m.Signature == nil {
m.Signature = []byte{}
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Extension = append(m.Extension[:0], dAtA[iNdEx:postIndex]...)
if m.Extension == nil {
m.Extension = []byte{}
}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ExtensionSignature", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ExtensionSignature = append(m.ExtensionSignature[:0], dAtA[iNdEx:postIndex]...)
if m.ExtensionSignature == nil {
m.ExtensionSignature = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Proposal) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Proposal: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Proposal: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
m.Type = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Type |= SignedMsgType(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Round", wireType)
}
m.Round = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Round |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field PolRound", wireType)
}
m.PolRound = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.PolRound |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...)
if m.Signature == nil {
m.Signature = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SignedHeader) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SignedHeader: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SignedHeader: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Header == nil {
m.Header = &Header{}
}
if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Commit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Commit == nil {
m.Commit = &Commit{}
}
if err := m.Commit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *LightBlock) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: LightBlock: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: LightBlock: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field SignedHeader", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.SignedHeader == nil {
m.SignedHeader = &SignedHeader{}
}
if err := m.SignedHeader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSet", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.ValidatorSet == nil {
m.ValidatorSet = &ValidatorSet{}
}
if err := m.ValidatorSet.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *BlockMeta) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: BlockMeta: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: BlockMeta: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockID", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.BlockID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockSize", wireType)
}
m.BlockSize = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BlockSize |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field NumTxs", wireType)
}
m.NumTxs = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.NumTxs |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxProof) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxProof: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxProof: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field RootHash", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.RootHash = append(m.RootHash[:0], dAtA[iNdEx:postIndex]...)
if m.RootHash == nil {
m.RootHash = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTypes
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTypes
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTypes
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Proof == nil {
m.Proof = &crypto.Proof{}
}
if err := m.Proof.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTypes(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTypes
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipTypes(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTypes
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthTypes
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupTypes
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthTypes
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group")
)
package proxy
import (
"context"
"time"
"github.com/go-kit/kit/metrics"
abcicli "github.com/cometbft/cometbft/abci/client"
"github.com/cometbft/cometbft/abci/types"
)
//go:generate ../scripts/mockery_generate.sh AppConnConsensus|AppConnMempool|AppConnQuery|AppConnSnapshot
//----------------------------------------------------------------------------------------
// Enforce which abci msgs can be sent on a connection at the type level
type AppConnConsensus interface {
Error() error
InitChain(context.Context, *types.RequestInitChain) (*types.ResponseInitChain, error)
PrepareProposal(context.Context, *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error)
ProcessProposal(context.Context, *types.RequestProcessProposal) (*types.ResponseProcessProposal, error)
ExtendVote(context.Context, *types.RequestExtendVote) (*types.ResponseExtendVote, error)
VerifyVoteExtension(context.Context, *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error)
FinalizeBlock(context.Context, *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error)
Commit(context.Context) (*types.ResponseCommit, error)
}
type AppConnMempool interface {
SetResponseCallback(abcicli.Callback)
Error() error
CheckTx(context.Context, *types.RequestCheckTx) (*types.ResponseCheckTx, error)
CheckTxAsync(context.Context, *types.RequestCheckTx) (*abcicli.ReqRes, error)
Flush(context.Context) error
}
type AppConnQuery interface {
Error() error
Echo(context.Context, string) (*types.ResponseEcho, error)
Info(context.Context, *types.RequestInfo) (*types.ResponseInfo, error)
Query(context.Context, *types.RequestQuery) (*types.ResponseQuery, error)
}
type AppConnSnapshot interface {
Error() error
ListSnapshots(context.Context, *types.RequestListSnapshots) (*types.ResponseListSnapshots, error)
OfferSnapshot(context.Context, *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error)
LoadSnapshotChunk(context.Context, *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error)
ApplySnapshotChunk(context.Context, *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error)
}
//-----------------------------------------------------------------------------------------
// Implements AppConnConsensus (subset of abcicli.Client)
type appConnConsensus struct {
metrics *Metrics
appConn abcicli.Client
}
var _ AppConnConsensus = (*appConnConsensus)(nil)
func NewAppConnConsensus(appConn abcicli.Client, metrics *Metrics) AppConnConsensus {
return &appConnConsensus{
metrics: metrics,
appConn: appConn,
}
}
func (app *appConnConsensus) Error() error {
return app.appConn.Error()
}
func (app *appConnConsensus) InitChain(ctx context.Context, req *types.RequestInitChain) (*types.ResponseInitChain, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "init_chain", "type", "sync"))()
return app.appConn.InitChain(ctx, req)
}
func (app *appConnConsensus) PrepareProposal(ctx context.Context,
req *types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "prepare_proposal", "type", "sync"))()
return app.appConn.PrepareProposal(ctx, req)
}
func (app *appConnConsensus) ProcessProposal(ctx context.Context, req *types.RequestProcessProposal) (*types.ResponseProcessProposal, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "process_proposal", "type", "sync"))()
return app.appConn.ProcessProposal(ctx, req)
}
func (app *appConnConsensus) ExtendVote(ctx context.Context, req *types.RequestExtendVote) (*types.ResponseExtendVote, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "extend_vote", "type", "sync"))()
return app.appConn.ExtendVote(ctx, req)
}
func (app *appConnConsensus) VerifyVoteExtension(ctx context.Context, req *types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "verify_vote_extension", "type", "sync"))()
return app.appConn.VerifyVoteExtension(ctx, req)
}
func (app *appConnConsensus) FinalizeBlock(ctx context.Context, req *types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "finalize_block", "type", "sync"))()
return app.appConn.FinalizeBlock(ctx, req)
}
func (app *appConnConsensus) Commit(ctx context.Context) (*types.ResponseCommit, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "commit", "type", "sync"))()
return app.appConn.Commit(ctx, &types.RequestCommit{})
}
//------------------------------------------------
// Implements AppConnMempool (subset of abcicli.Client)
type appConnMempool struct {
metrics *Metrics
appConn abcicli.Client
}
func NewAppConnMempool(appConn abcicli.Client, metrics *Metrics) AppConnMempool {
return &appConnMempool{
metrics: metrics,
appConn: appConn,
}
}
func (app *appConnMempool) SetResponseCallback(cb abcicli.Callback) {
app.appConn.SetResponseCallback(cb)
}
func (app *appConnMempool) Error() error {
return app.appConn.Error()
}
func (app *appConnMempool) Flush(ctx context.Context) error {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "flush", "type", "sync"))()
return app.appConn.Flush(ctx)
}
func (app *appConnMempool) CheckTx(ctx context.Context, req *types.RequestCheckTx) (*types.ResponseCheckTx, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "check_tx", "type", "sync"))()
return app.appConn.CheckTx(ctx, req)
}
func (app *appConnMempool) CheckTxAsync(ctx context.Context, req *types.RequestCheckTx) (*abcicli.ReqRes, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "check_tx", "type", "async"))()
return app.appConn.CheckTxAsync(ctx, req)
}
//------------------------------------------------
// Implements AppConnQuery (subset of abcicli.Client)
type appConnQuery struct {
metrics *Metrics
appConn abcicli.Client
}
func NewAppConnQuery(appConn abcicli.Client, metrics *Metrics) AppConnQuery {
return &appConnQuery{
metrics: metrics,
appConn: appConn,
}
}
func (app *appConnQuery) Error() error {
return app.appConn.Error()
}
func (app *appConnQuery) Echo(ctx context.Context, msg string) (*types.ResponseEcho, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "echo", "type", "sync"))()
return app.appConn.Echo(ctx, msg)
}
func (app *appConnQuery) Info(ctx context.Context, req *types.RequestInfo) (*types.ResponseInfo, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "info", "type", "sync"))()
return app.appConn.Info(ctx, req)
}
func (app *appConnQuery) Query(ctx context.Context, req *types.RequestQuery) (*types.ResponseQuery, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "query", "type", "sync"))()
return app.appConn.Query(ctx, req)
}
//------------------------------------------------
// Implements AppConnSnapshot (subset of abcicli.Client)
type appConnSnapshot struct {
metrics *Metrics
appConn abcicli.Client
}
func NewAppConnSnapshot(appConn abcicli.Client, metrics *Metrics) AppConnSnapshot {
return &appConnSnapshot{
metrics: metrics,
appConn: appConn,
}
}
func (app *appConnSnapshot) Error() error {
return app.appConn.Error()
}
func (app *appConnSnapshot) ListSnapshots(ctx context.Context, req *types.RequestListSnapshots) (*types.ResponseListSnapshots, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "list_snapshots", "type", "sync"))()
return app.appConn.ListSnapshots(ctx, req)
}
func (app *appConnSnapshot) OfferSnapshot(ctx context.Context, req *types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "offer_snapshot", "type", "sync"))()
return app.appConn.OfferSnapshot(ctx, req)
}
func (app *appConnSnapshot) LoadSnapshotChunk(ctx context.Context, req *types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "load_snapshot_chunk", "type", "sync"))()
return app.appConn.LoadSnapshotChunk(ctx, req)
}
func (app *appConnSnapshot) ApplySnapshotChunk(ctx context.Context, req *types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) {
defer addTimeSample(app.metrics.MethodTimingSeconds.With("method", "apply_snapshot_chunk", "type", "sync"))()
return app.appConn.ApplySnapshotChunk(ctx, req)
}
// addTimeSample returns a function that, when called, adds an observation to m.
// The observation added to m is the number of seconds ellapsed since addTimeSample
// was initially called. addTimeSample is meant to be called in a defer to calculate
// the amount of time a function takes to complete.
func addTimeSample(m metrics.Histogram) func() {
start := time.Now()
return func() { m.Observe(time.Since(start).Seconds()) }
}
package core
import (
"context"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/bytes"
"github.com/cometbft/cometbft/proxy"
ctypes "github.com/cometbft/cometbft/rpc/core/types"
rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types"
)
// ABCIQuery queries the application for some information.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/ABCI/abci_query
func (env *Environment) ABCIQuery(
_ *rpctypes.Context,
path string,
data bytes.HexBytes,
height int64,
prove bool,
) (*ctypes.ResultABCIQuery, error) {
resQuery, err := env.ProxyAppQuery.Query(context.TODO(), &abci.RequestQuery{
Path: path,
Data: data,
Height: height,
Prove: prove,
})
if err != nil {
return nil, err
}
return &ctypes.ResultABCIQuery{Response: *resQuery}, nil
}
// ABCIInfo gets some info about the application.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/ABCI/abci_info
func (env *Environment) ABCIInfo(_ *rpctypes.Context) (*ctypes.ResultABCIInfo, error) {
resInfo, err := env.ProxyAppQuery.Info(context.TODO(), proxy.RequestInfo)
if err != nil {
return nil, err
}
return &ctypes.ResultABCIInfo{Response: *resInfo}, nil
}
package core
import (
"errors"
"fmt"
"sort"
"github.com/cometbft/cometbft/libs/bytes"
cmtmath "github.com/cometbft/cometbft/libs/math"
cmtquery "github.com/cometbft/cometbft/libs/pubsub/query"
ctypes "github.com/cometbft/cometbft/rpc/core/types"
rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types"
blockidxnull "github.com/cometbft/cometbft/state/indexer/block/null"
"github.com/cometbft/cometbft/types"
)
// BlockchainInfo gets block headers for minHeight <= height <= maxHeight.
//
// If maxHeight does not yet exist, blocks up to the current height will be
// returned. If minHeight does not exist (due to pruning), earliest existing
// height will be used.
//
// At most 20 items will be returned. Block headers are returned in descending
// order (highest first).
//
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/blockchain
func (env *Environment) BlockchainInfo(
_ *rpctypes.Context,
minHeight, maxHeight int64,
) (*ctypes.ResultBlockchainInfo, error) {
const limit int64 = 20
var err error
minHeight, maxHeight, err = filterMinMax(
env.BlockStore.Base(),
env.BlockStore.Height(),
minHeight,
maxHeight,
limit)
if err != nil {
return nil, err
}
env.Logger.Debug("BlockchainInfoHandler", "maxHeight", maxHeight, "minHeight", minHeight)
blockMetas := []*types.BlockMeta{}
for height := maxHeight; height >= minHeight; height-- {
blockMeta := env.BlockStore.LoadBlockMeta(height)
blockMetas = append(blockMetas, blockMeta)
}
return &ctypes.ResultBlockchainInfo{
LastHeight: env.BlockStore.Height(),
BlockMetas: blockMetas,
}, nil
}
// error if either min or max are negative or min > max
// if 0, use blockstore base for min, latest block height for max
// enforce limit.
func filterMinMax(base, height, min, max, limit int64) (int64, int64, error) {
// filter negatives
if min < 0 || max < 0 {
return min, max, fmt.Errorf("heights must be non-negative")
}
// adjust for default values
if min == 0 {
min = 1
}
if max == 0 {
max = height
}
// limit max to the height
max = cmtmath.MinInt64(height, max)
// limit min to the base
min = cmtmath.MaxInt64(base, min)
// limit min to within `limit` of max
// so the total number of blocks returned will be `limit`
min = cmtmath.MaxInt64(min, max-limit+1)
if min > max {
return min, max, fmt.Errorf("min height %d can't be greater than max height %d", min, max)
}
return min, max, nil
}
// Header gets block header at a given height.
// If no height is provided, it will fetch the latest header.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/header
func (env *Environment) Header(_ *rpctypes.Context, heightPtr *int64) (*ctypes.ResultHeader, error) {
height, err := env.getHeight(env.BlockStore.Height(), heightPtr)
if err != nil {
return nil, err
}
blockMeta := env.BlockStore.LoadBlockMeta(height)
if blockMeta == nil {
return &ctypes.ResultHeader{}, nil
}
return &ctypes.ResultHeader{Header: &blockMeta.Header}, nil
}
// HeaderByHash gets header by hash.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/header_by_hash
func (env *Environment) HeaderByHash(_ *rpctypes.Context, hash bytes.HexBytes) (*ctypes.ResultHeader, error) {
// N.B. The hash parameter is HexBytes so that the reflective parameter
// decoding logic in the HTTP service will correctly translate from JSON.
// See https://github.com/tendermint/tendermint/issues/6802 for context.
blockMeta := env.BlockStore.LoadBlockMetaByHash(hash)
if blockMeta == nil {
return &ctypes.ResultHeader{}, nil
}
return &ctypes.ResultHeader{Header: &blockMeta.Header}, nil
}
// Block gets block at a given height.
// If no height is provided, it will fetch the latest block.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/block
func (env *Environment) Block(_ *rpctypes.Context, heightPtr *int64) (*ctypes.ResultBlock, error) {
height, err := env.getHeight(env.BlockStore.Height(), heightPtr)
if err != nil {
return nil, err
}
block := env.BlockStore.LoadBlock(height)
blockMeta := env.BlockStore.LoadBlockMeta(height)
if blockMeta == nil {
return &ctypes.ResultBlock{BlockID: types.BlockID{}, Block: block}, nil
}
return &ctypes.ResultBlock{BlockID: blockMeta.BlockID, Block: block}, nil
}
// BlockByHash gets block by hash.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/block_by_hash
func (env *Environment) BlockByHash(_ *rpctypes.Context, hash []byte) (*ctypes.ResultBlock, error) {
block := env.BlockStore.LoadBlockByHash(hash)
if block == nil {
return &ctypes.ResultBlock{BlockID: types.BlockID{}, Block: nil}, nil
}
// If block is not nil, then blockMeta can't be nil.
blockMeta := env.BlockStore.LoadBlockMeta(block.Height)
return &ctypes.ResultBlock{BlockID: blockMeta.BlockID, Block: block}, nil
}
// Commit gets block commit at a given height.
// If no height is provided, it will fetch the commit for the latest block.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/commit
func (env *Environment) Commit(_ *rpctypes.Context, heightPtr *int64) (*ctypes.ResultCommit, error) {
height, err := env.getHeight(env.BlockStore.Height(), heightPtr)
if err != nil {
return nil, err
}
blockMeta := env.BlockStore.LoadBlockMeta(height)
if blockMeta == nil {
return nil, nil
}
header := blockMeta.Header
// If the next block has not been committed yet,
// use a non-canonical commit
if height == env.BlockStore.Height() {
commit := env.BlockStore.LoadSeenCommit(height)
return ctypes.NewResultCommit(&header, commit, false), nil
}
// Return the canonical commit (comes from the block at height+1)
commit := env.BlockStore.LoadBlockCommit(height)
return ctypes.NewResultCommit(&header, commit, true), nil
}
// BlockResults gets ABCIResults at a given height.
// If no height is provided, it will fetch results for the latest block.
//
// Results are for the height of the block containing the txs.
// Thus response.results.deliver_tx[5] is the results of executing
// getBlock(h).Txs[5]
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/block_results
func (env *Environment) BlockResults(_ *rpctypes.Context, heightPtr *int64) (*ctypes.ResultBlockResults, error) {
height, err := env.getHeight(env.BlockStore.Height(), heightPtr)
if err != nil {
return nil, err
}
results, err := env.StateStore.LoadFinalizeBlockResponse(height)
if err != nil {
env.Logger.Error("failed to LoadFinalizeBlockResponse", "err", err)
return nil, err
}
return &ctypes.ResultBlockResults{
Height: height,
TxsResults: results.TxResults,
FinalizeBlockEvents: results.Events,
ValidatorUpdates: results.ValidatorUpdates,
ConsensusParamUpdates: results.ConsensusParamUpdates,
EventPlaintext: true,
AppHash: results.AppHash,
}, nil
}
// BlockSearch searches for a paginated set of blocks matching
// FinalizeBlock event search criteria.
func (env *Environment) BlockSearch(
ctx *rpctypes.Context,
query string,
pagePtr, perPagePtr *int,
orderBy string,
) (*ctypes.ResultBlockSearch, error) {
// skip if block indexing is disabled
if _, ok := env.BlockIndexer.(*blockidxnull.BlockerIndexer); ok {
return nil, errors.New("block indexing is disabled")
}
q, err := cmtquery.New(query)
if err != nil {
return nil, err
}
results, err := env.BlockIndexer.Search(ctx.Context(), q)
if err != nil {
return nil, err
}
// sort results (must be done before pagination)
switch orderBy {
case "desc", "":
sort.Slice(results, func(i, j int) bool { return results[i] > results[j] })
case "asc":
sort.Slice(results, func(i, j int) bool { return results[i] < results[j] })
default:
return nil, errors.New("expected order_by to be either `asc` or `desc` or empty")
}
// paginate results
totalCount := len(results)
perPage := env.validatePerPage(perPagePtr)
page, err := validatePage(pagePtr, perPage, totalCount)
if err != nil {
return nil, err
}
skipCount := validateSkipCount(page, perPage)
pageSize := cmtmath.MinInt(perPage, totalCount-skipCount)
apiResults := make([]*ctypes.ResultBlock, 0, pageSize)
for i := skipCount; i < skipCount+pageSize; i++ {
block := env.BlockStore.LoadBlock(results[i])
if block != nil {
blockMeta := env.BlockStore.LoadBlockMeta(block.Height)
if blockMeta != nil {
apiResults = append(apiResults, &ctypes.ResultBlock{
Block: block,
BlockID: blockMeta.BlockID,
})
}
}
}
return &ctypes.ResultBlockSearch{Blocks: apiResults, TotalCount: totalCount}, nil
}
package core
import (
"encoding/base64"
"fmt"
"time"
cfg "github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/crypto"
cmtjson "github.com/cometbft/cometbft/libs/json"
"github.com/cometbft/cometbft/libs/log"
mempl "github.com/cometbft/cometbft/mempool"
"github.com/cometbft/cometbft/p2p"
"github.com/cometbft/cometbft/proxy"
sm "github.com/cometbft/cometbft/state"
"github.com/cometbft/cometbft/state/indexer"
"github.com/cometbft/cometbft/state/txindex"
"github.com/cometbft/cometbft/types"
)
const (
// see README
defaultPerPage = 30
maxPerPage = 100
// SubscribeTimeout is the maximum time we wait to subscribe for an event.
// must be less than the server's write timeout (see rpcserver.DefaultConfig)
SubscribeTimeout = 5 * time.Second
// genesisChunkSize is the maximum size, in bytes, of each
// chunk in the genesis structure for the chunked API
genesisChunkSize = 16 * 1024 * 1024 // 16
)
//----------------------------------------------
// These interfaces are used by RPC and must be thread safe
type Consensus interface {
GetState() sm.State
GetValidators() (int64, []*types.Validator)
GetLastHeight() int64
GetRoundStateJSON() ([]byte, error)
GetRoundStateSimpleJSON() ([]byte, error)
}
type transport interface {
Listeners() []string
IsListening() bool
NodeInfo() p2p.NodeInfo
}
type peers interface {
AddPersistentPeers([]string) error
AddUnconditionalPeerIDs([]string) error
AddPrivatePeerIDs([]string) error
DialPeersAsync([]string) error
Peers() p2p.IPeerSet
}
type consensusReactor interface {
WaitSync() bool
}
// ----------------------------------------------
// Environment contains objects and interfaces used by the RPC. It is expected
// to be setup once during startup.
type Environment struct {
// external, thread safe interfaces
ProxyAppQuery proxy.AppConnQuery
ProxyAppMempool proxy.AppConnMempool
// interfaces defined in types and above
StateStore sm.Store
BlockStore sm.BlockStore
EvidencePool sm.EvidencePool
ConsensusState Consensus
ConsensusReactor consensusReactor
P2PPeers peers
P2PTransport transport
// objects
PubKey crypto.PubKey
GenDoc *types.GenesisDoc // cache the genesis structure
TxIndexer txindex.TxIndexer
BlockIndexer indexer.BlockIndexer
EventBus *types.EventBus // thread safe
Mempool mempl.Mempool
Logger log.Logger
Config cfg.RPCConfig
// cache of chunked genesis data.
genChunks []string
}
//----------------------------------------------
func validatePage(pagePtr *int, perPage, totalCount int) (int, error) {
if perPage < 1 {
panic(fmt.Sprintf("zero or negative perPage: %d", perPage))
}
if pagePtr == nil { // no page parameter
return 1, nil
}
pages := ((totalCount - 1) / perPage) + 1
if pages == 0 {
pages = 1 // one page (even if it's empty)
}
page := *pagePtr
if page <= 0 || page > pages {
return 1, fmt.Errorf("page should be within [1, %d] range, given %d", pages, page)
}
return page, nil
}
func (env *Environment) validatePerPage(perPagePtr *int) int {
if perPagePtr == nil { // no per_page parameter
return defaultPerPage
}
perPage := *perPagePtr
if perPage < 1 {
return defaultPerPage
} else if perPage > maxPerPage {
return maxPerPage
}
return perPage
}
// InitGenesisChunks configures the environment and should be called on service
// startup.
func (env *Environment) InitGenesisChunks() error {
if env.genChunks != nil {
return nil
}
if env.GenDoc == nil {
return nil
}
data, err := cmtjson.Marshal(env.GenDoc)
if err != nil {
return err
}
for i := 0; i < len(data); i += genesisChunkSize {
end := i + genesisChunkSize
if end > len(data) {
end = len(data)
}
env.genChunks = append(env.genChunks, base64.StdEncoding.EncodeToString(data[i:end]))
}
return nil
}
func validateSkipCount(page, perPage int) int {
skipCount := (page - 1) * perPage
if skipCount < 0 {
return 0
}
return skipCount
}
// latestHeight can be either latest committed or uncommitted (+1) height.
func (env *Environment) getHeight(latestHeight int64, heightPtr *int64) (int64, error) {
if heightPtr != nil {
height := *heightPtr
if height <= 0 {
return 0, fmt.Errorf("height must be greater than 0, but got %d", height)
}
if height > latestHeight {
return 0, fmt.Errorf("height %d must be less than or equal to the current blockchain height %d",
height, latestHeight)
}
base := env.BlockStore.Base()
if height < base {
return 0, fmt.Errorf("height %d is not available, lowest height is %d",
height, base)
}
return height, nil
}
return latestHeight, nil
}
func (env *Environment) latestUncommittedHeight() int64 {
nodeIsSyncing := env.ConsensusReactor.WaitSync()
if nodeIsSyncing {
return env.BlockStore.Height()
}
return env.BlockStore.Height() + 1
}
package core
import (
"context"
"errors"
"fmt"
"time"
abci "github.com/cometbft/cometbft/abci/types"
mempl "github.com/cometbft/cometbft/mempool"
ctypes "github.com/cometbft/cometbft/rpc/core/types"
rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types"
"github.com/cometbft/cometbft/types"
)
//-----------------------------------------------------------------------------
// NOTE: tx should be signed, but this is only checked at the app level (not by CometBFT!)
// BroadcastTxAsync returns right away, with no response. Does not wait for
// CheckTx nor transaction results.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Tx/broadcast_tx_async
func (env *Environment) BroadcastTxAsync(_ *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
err := env.Mempool.CheckTx(tx, nil, mempl.TxInfo{})
if err != nil {
return nil, err
}
return &ctypes.ResultBroadcastTx{Hash: tx.Hash()}, nil
}
// BroadcastTxSync returns with the response from CheckTx. Does not wait for
// the transaction result.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Tx/broadcast_tx_sync
func (env *Environment) BroadcastTxSync(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
resCh := make(chan *abci.ResponseCheckTx, 1)
err := env.Mempool.CheckTx(tx, func(res *abci.ResponseCheckTx) {
select {
case <-ctx.Context().Done():
case resCh <- res:
}
}, mempl.TxInfo{})
if err != nil {
return nil, err
}
select {
case <-ctx.Context().Done():
return nil, fmt.Errorf("broadcast confirmation not received: %w", ctx.Context().Err())
case res := <-resCh:
return &ctypes.ResultBroadcastTx{
Code: res.Code,
Data: res.Data,
Log: res.Log,
Codespace: res.Codespace,
Hash: tx.Hash(),
}, nil
}
}
// BroadcastTxCommit returns with the responses from CheckTx and ExecTxResult.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Tx/broadcast_tx_commit
func (env *Environment) BroadcastTxCommit(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) {
subscriber := ctx.RemoteAddr()
if env.EventBus.NumClients() >= env.Config.MaxSubscriptionClients {
return nil, fmt.Errorf("max_subscription_clients %d reached", env.Config.MaxSubscriptionClients)
} else if env.EventBus.NumClientSubscriptions(subscriber) >= env.Config.MaxSubscriptionsPerClient {
return nil, fmt.Errorf("max_subscriptions_per_client %d reached", env.Config.MaxSubscriptionsPerClient)
}
// Subscribe to tx being committed in block.
subCtx, cancel := context.WithTimeout(ctx.Context(), SubscribeTimeout)
defer cancel()
q := types.EventQueryTxFor(tx)
txSub, err := env.EventBus.Subscribe(subCtx, subscriber, q)
if err != nil {
err = fmt.Errorf("failed to subscribe to tx: %w", err)
env.Logger.Error("Error on broadcast_tx_commit", "err", err)
return nil, err
}
defer func() {
if err := env.EventBus.Unsubscribe(context.Background(), subscriber, q); err != nil {
env.Logger.Error("Error unsubscribing from eventBus", "err", err)
}
}()
// Broadcast tx and wait for CheckTx result
checkTxResCh := make(chan *abci.ResponseCheckTx, 1)
err = env.Mempool.CheckTx(tx, func(res *abci.ResponseCheckTx) {
select {
case <-ctx.Context().Done():
case checkTxResCh <- res:
}
}, mempl.TxInfo{})
if err != nil {
env.Logger.Error("Error on broadcastTxCommit", "err", err)
return nil, fmt.Errorf("error on broadcastTxCommit: %v", err)
}
select {
case <-ctx.Context().Done():
return nil, fmt.Errorf("broadcast confirmation not received: %w", ctx.Context().Err())
case checkTxRes := <-checkTxResCh:
if checkTxRes.Code != abci.CodeTypeOK {
return &ctypes.ResultBroadcastTxCommit{
CheckTx: *checkTxRes,
TxResult: abci.ExecTxResult{},
Hash: tx.Hash(),
}, nil
}
// Wait for the tx to be included in a block or timeout.
select {
case msg := <-txSub.Out(): // The tx was included in a block.
txResultEvent := msg.Data().(types.EventDataTx)
return &ctypes.ResultBroadcastTxCommit{
CheckTx: *checkTxRes,
TxResult: txResultEvent.Result,
Hash: tx.Hash(),
Height: txResultEvent.Height,
}, nil
case <-txSub.Canceled():
var reason string
if txSub.Err() == nil {
reason = "CometBFT exited"
} else {
reason = txSub.Err().Error()
}
err = fmt.Errorf("txSub was canceled (reason: %s)", reason)
env.Logger.Error("Error on broadcastTxCommit", "err", err)
return &ctypes.ResultBroadcastTxCommit{
CheckTx: *checkTxRes,
TxResult: abci.ExecTxResult{},
Hash: tx.Hash(),
}, err
case <-time.After(env.Config.TimeoutBroadcastTxCommit):
err = errors.New("timed out waiting for tx to be included in a block")
env.Logger.Error("Error on broadcastTxCommit", "err", err)
return &ctypes.ResultBroadcastTxCommit{
CheckTx: *checkTxRes,
TxResult: abci.ExecTxResult{},
Hash: tx.Hash(),
}, err
}
}
}
// UnconfirmedTxs gets unconfirmed transactions (maximum ?limit entries)
// including their number.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/unconfirmed_txs
func (env *Environment) UnconfirmedTxs(_ *rpctypes.Context, limitPtr *int) (*ctypes.ResultUnconfirmedTxs, error) {
// reuse per_page validator
limit := env.validatePerPage(limitPtr)
txs := env.Mempool.ReapMaxTxs(limit)
return &ctypes.ResultUnconfirmedTxs{
Count: len(txs),
Total: env.Mempool.Size(),
TotalBytes: env.Mempool.SizeBytes(),
Txs: txs,
}, nil
}
// NumUnconfirmedTxs gets number of unconfirmed transactions.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/num_unconfirmed_txs
func (env *Environment) NumUnconfirmedTxs(*rpctypes.Context) (*ctypes.ResultUnconfirmedTxs, error) {
return &ctypes.ResultUnconfirmedTxs{
Count: env.Mempool.Size(),
Total: env.Mempool.Size(),
TotalBytes: env.Mempool.SizeBytes(),
}, nil
}
// CheckTx checks the transaction without executing it. The transaction won't
// be added to the mempool either.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Tx/check_tx
func (env *Environment) CheckTx(_ *rpctypes.Context, tx types.Tx) (*ctypes.ResultCheckTx, error) {
res, err := env.ProxyAppMempool.CheckTx(context.TODO(), &abci.RequestCheckTx{Tx: tx})
if err != nil {
return nil, err
}
return &ctypes.ResultCheckTx{ResponseCheckTx: *res}, nil
}
package core
import (
"errors"
"fmt"
"sort"
cmtmath "github.com/cometbft/cometbft/libs/math"
cmtquery "github.com/cometbft/cometbft/libs/pubsub/query"
ctypes "github.com/cometbft/cometbft/rpc/core/types"
rpctypes "github.com/cometbft/cometbft/rpc/jsonrpc/types"
"github.com/cometbft/cometbft/state/txindex/null"
"github.com/cometbft/cometbft/types"
)
// Tx allows you to query the transaction results. `nil` could mean the
// transaction is in the mempool, invalidated, or was not sent in the first
// place.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/tx
func (env *Environment) Tx(_ *rpctypes.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) {
// if index is disabled, return error
if _, ok := env.TxIndexer.(*null.TxIndex); ok {
return nil, fmt.Errorf("transaction indexing is disabled")
}
r, err := env.TxIndexer.Get(hash)
if err != nil {
return nil, err
}
if r == nil {
return nil, fmt.Errorf("tx (%X) not found", hash)
}
var proof types.TxProof
if prove {
block := env.BlockStore.LoadBlock(r.Height)
if block != nil {
proof = block.Data.Txs.Proof(int(r.Index))
}
}
return &ctypes.ResultTx{
Hash: hash,
Height: r.Height,
Index: r.Index,
TxResult: r.Result,
Tx: r.Tx,
Proof: proof,
}, nil
}
// TxSearch allows you to query for multiple transactions results. It returns a
// list of transactions (maximum ?per_page entries) and the total count.
// More: https://docs.cometbft.com/v0.38.x/rpc/#/Info/tx_search
func (env *Environment) TxSearch(
ctx *rpctypes.Context,
query string,
prove bool,
pagePtr, perPagePtr *int,
orderBy string,
) (*ctypes.ResultTxSearch, error) {
// if index is disabled, return error
if _, ok := env.TxIndexer.(*null.TxIndex); ok {
return nil, errors.New("transaction indexing is disabled")
} else if len(query) > maxQueryLength {
return nil, errors.New("maximum query length exceeded")
}
q, err := cmtquery.New(query)
if err != nil {
return nil, err
}
results, err := env.TxIndexer.Search(ctx.Context(), q)
if err != nil {
return nil, err
}
// sort results (must be done before pagination)
switch orderBy {
case "desc":
sort.Slice(results, func(i, j int) bool {
if results[i].Height == results[j].Height {
return results[i].Index > results[j].Index
}
return results[i].Height > results[j].Height
})
case "asc", "":
sort.Slice(results, func(i, j int) bool {
if results[i].Height == results[j].Height {
return results[i].Index < results[j].Index
}
return results[i].Height < results[j].Height
})
default:
return nil, errors.New("expected order_by to be either `asc` or `desc` or empty")
}
// paginate results
totalCount := len(results)
perPage := env.validatePerPage(perPagePtr)
page, err := validatePage(pagePtr, perPage, totalCount)
if err != nil {
return nil, err
}
skipCount := validateSkipCount(page, perPage)
pageSize := cmtmath.MinInt(perPage, totalCount-skipCount)
apiResults := make([]*ctypes.ResultTx, 0, pageSize)
for i := skipCount; i < skipCount+pageSize; i++ {
r := results[i]
var proof types.TxProof
if prove {
block := env.BlockStore.LoadBlock(r.Height)
if block != nil {
proof = block.Data.Txs.Proof(int(r.Index))
}
}
apiResults = append(apiResults, &ctypes.ResultTx{
Hash: types.Tx(r.Tx).Hash(),
Height: r.Height,
Index: r.Index,
TxResult: r.Result,
Tx: r.Tx,
Proof: proof,
})
}
return &ctypes.ResultTxSearch{Txs: apiResults, TotalCount: totalCount}, nil
}
package server
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"sort"
cmtjson "github.com/cometbft/cometbft/libs/json"
"github.com/cometbft/cometbft/libs/log"
types "github.com/cometbft/cometbft/rpc/jsonrpc/types"
)
// HTTP + JSON handler
// jsonrpc calls grab the given method's function info and runs reflect.Call
func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
b, err := io.ReadAll(r.Body)
if err != nil {
res := types.RPCInvalidRequestError(nil,
fmt.Errorf("error reading request body: %w", err),
)
if wErr := WriteRPCResponseHTTPError(w, http.StatusBadRequest, res); wErr != nil {
logger.Error("failed to write response", "err", wErr)
}
return
}
// if it's an empty request (like from a browser), just display a list of
// functions
if len(b) == 0 {
writeListOfEndpoints(w, r, funcMap)
return
}
// first try to unmarshal the incoming request as an array of RPC requests
var (
requests []types.RPCRequest
responses []types.RPCResponse
)
if err := json.Unmarshal(b, &requests); err != nil {
// next, try to unmarshal as a single request
var request types.RPCRequest
if err := json.Unmarshal(b, &request); err != nil {
res := types.RPCParseError(fmt.Errorf("error unmarshaling request: %w", err))
if wErr := WriteRPCResponseHTTPError(w, http.StatusInternalServerError, res); wErr != nil {
logger.Error("failed to write response", "err", wErr)
}
return
}
requests = []types.RPCRequest{request}
}
// Set the default response cache to true unless
// 1. Any RPC request error.
// 2. Any RPC request doesn't allow to be cached.
// 3. Any RPC request has the height argument and the value is 0 (the default).
cache := true
for _, request := range requests {
request := request
// A Notification is a Request object without an "id" member.
// The Server MUST NOT reply to a Notification, including those that are within a batch request.
if request.ID == nil {
logger.Debug(
"HTTPJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)",
"req", request,
)
continue
}
if len(r.URL.Path) > 1 {
responses = append(
responses,
types.RPCInvalidRequestError(request.ID, fmt.Errorf("path %s is invalid", r.URL.Path)),
)
cache = false
continue
}
rpcFunc, ok := funcMap[request.Method]
if !ok || (rpcFunc.ws) {
responses = append(responses, types.RPCMethodNotFoundError(request.ID))
cache = false
continue
}
ctx := &types.Context{JSONReq: &request, HTTPReq: r}
args := []reflect.Value{reflect.ValueOf(ctx)}
if len(request.Params) > 0 {
fnArgs, err := jsonParamsToArgs(rpcFunc, request.Params)
if err != nil {
responses = append(
responses,
types.RPCInvalidParamsError(request.ID, fmt.Errorf("error converting json params to arguments: %w", err)),
)
cache = false
continue
}
args = append(args, fnArgs...)
}
if cache && !rpcFunc.cacheableWithArgs(args) {
cache = false
}
returns := rpcFunc.f.Call(args)
result, err := unreflectResult(returns)
if err != nil {
responses = append(responses, types.RPCInternalError(request.ID, err))
continue
}
responses = append(responses, types.NewRPCSuccessResponse(request.ID, result))
}
if len(responses) > 0 {
var wErr error
if cache {
wErr = WriteCacheableRPCResponseHTTP(w, responses...)
} else {
wErr = WriteRPCResponseHTTP(w, responses...)
}
if wErr != nil {
logger.Error("failed to write responses", "err", wErr)
}
}
}
}
func handleInvalidJSONRPCPaths(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Since the pattern "/" matches all paths not matched by other registered patterns,
// we check whether the path is indeed "/", otherwise return a 404 error
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
next(w, r)
}
}
func mapParamsToArgs(
rpcFunc *RPCFunc,
params map[string]json.RawMessage,
argsOffset int,
) ([]reflect.Value, error) {
values := make([]reflect.Value, len(rpcFunc.argNames))
for i, argName := range rpcFunc.argNames {
argType := rpcFunc.args[i+argsOffset]
if p, ok := params[argName]; ok && p != nil && len(p) > 0 {
val := reflect.New(argType)
err := cmtjson.Unmarshal(p, val.Interface())
if err != nil {
return nil, err
}
values[i] = val.Elem()
} else { // use default for that type
values[i] = reflect.Zero(argType)
}
}
return values, nil
}
func arrayParamsToArgs(
rpcFunc *RPCFunc,
params []json.RawMessage,
argsOffset int,
) ([]reflect.Value, error) {
if len(rpcFunc.argNames) != len(params) {
return nil, fmt.Errorf("expected %v parameters (%v), got %v (%v)",
len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)
}
values := make([]reflect.Value, len(params))
for i, p := range params {
argType := rpcFunc.args[i+argsOffset]
val := reflect.New(argType)
err := cmtjson.Unmarshal(p, val.Interface())
if err != nil {
return nil, err
}
values[i] = val.Elem()
}
return values, nil
}
// raw is unparsed json (from json.RawMessage) encoding either a map or an
// array.
//
// Example:
//
// rpcFunc.args = [rpctypes.Context string]
// rpcFunc.argNames = ["arg"]
func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte) ([]reflect.Value, error) {
const argsOffset = 1
// TODO: Make more efficient, perhaps by checking the first character for '{' or '['?
// First, try to get the map.
var m map[string]json.RawMessage
err := json.Unmarshal(raw, &m)
if err == nil {
return mapParamsToArgs(rpcFunc, m, argsOffset)
}
// Otherwise, try an array.
var a []json.RawMessage
err = json.Unmarshal(raw, &a)
if err == nil {
return arrayParamsToArgs(rpcFunc, a, argsOffset)
}
// Otherwise, bad format, we cannot parse
return nil, fmt.Errorf("unknown type for JSON params: %v. Expected map or array", err)
}
// writes a list of available rpc endpoints as an html page
func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) {
noArgNames := []string{}
argNames := []string{}
for name, funcData := range funcMap {
if len(funcData.args) == 0 {
noArgNames = append(noArgNames, name)
} else {
argNames = append(argNames, name)
}
}
sort.Strings(noArgNames)
sort.Strings(argNames)
buf := new(bytes.Buffer)
buf.WriteString("<html><body>")
buf.WriteString("<br>Available endpoints:<br>")
for _, name := range noArgNames {
link := fmt.Sprintf("//%s/%s", r.Host, name)
buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
}
buf.WriteString("<br>Endpoints that require arguments:<br>")
for _, name := range argNames {
link := fmt.Sprintf("//%s/%s?", r.Host, name)
funcData := funcMap[name]
for i, argName := range funcData.argNames {
link += argName + "=_"
if i < len(funcData.argNames)-1 {
link += "&"
}
}
buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
}
buf.WriteString("</body></html>")
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(200)
w.Write(buf.Bytes()) //nolint: errcheck
}
// Commons for HTTP handling
package server
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"runtime/debug"
"strings"
"time"
"golang.org/x/net/netutil"
"github.com/cometbft/cometbft/libs/log"
types "github.com/cometbft/cometbft/rpc/jsonrpc/types"
)
// Config is a RPC server configuration.
type Config struct {
// see netutil.LimitListener
MaxOpenConnections int
// mirrors http.Server#ReadTimeout
ReadTimeout time.Duration
// mirrors http.Server#WriteTimeout
WriteTimeout time.Duration
// MaxBodyBytes controls the maximum number of bytes the
// server will read parsing the request body.
MaxBodyBytes int64
// mirrors http.Server#MaxHeaderBytes
MaxHeaderBytes int
// maximum number of requests in a batch request
MaxRequestBatchSize int
}
// DefaultConfig returns a default configuration.
func DefaultConfig() *Config {
return &Config{
MaxOpenConnections: 0, // unlimited
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxBodyBytes: int64(1000000), // 1MB
MaxHeaderBytes: 1 << 20, // same as the net/http default
MaxRequestBatchSize: 10, // default to max 10 requests per batch
}
}
// Serve creates a http.Server and calls Serve with the given listener. It
// wraps handler with RecoverAndLogHandler and a handler, which limits the max
// body size to config.MaxBodyBytes.
//
// NOTE: This function blocks - you may want to call it in a go-routine.
func Serve(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error {
logger.Info("serve", "msg", log.NewLazySprintf("Starting RPC HTTP server on %s", listener.Addr()))
s := &http.Server{
Handler: PreChecksHandler(RecoverAndLogHandler(defaultHandler{h: handler}, logger), config),
ReadTimeout: config.ReadTimeout,
ReadHeaderTimeout: config.ReadTimeout,
WriteTimeout: config.WriteTimeout,
MaxHeaderBytes: config.MaxHeaderBytes,
}
err := s.Serve(listener)
logger.Info("RPC HTTP server stopped", "err", err)
return err
}
// ServeTLS creates a http.Server and calls ServeTLS with the given listener,
// certFile and keyFile. It wraps handler with RecoverAndLogHandler and a
// handler, which limits the max body size to config.MaxBodyBytes.
//
// NOTE: This function blocks - you may want to call it in a go-routine.
func ServeTLS(
listener net.Listener,
handler http.Handler,
certFile, keyFile string,
logger log.Logger,
config *Config,
) error {
logger.Info("serve tls", "msg", log.NewLazySprintf("Starting RPC HTTPS server on %s (cert: %q, key: %q)",
listener.Addr(), certFile, keyFile))
s := &http.Server{
Handler: PreChecksHandler(RecoverAndLogHandler(defaultHandler{h: handler}, logger), config),
ReadTimeout: config.ReadTimeout,
ReadHeaderTimeout: config.ReadTimeout,
WriteTimeout: config.WriteTimeout,
MaxHeaderBytes: config.MaxHeaderBytes,
}
err := s.ServeTLS(listener, certFile, keyFile)
logger.Error("RPC HTTPS server stopped", "err", err)
return err
}
// WriteRPCResponseHTTPError marshals res as JSON (with indent) and writes it
// to w.
//
// source: https://www.jsonrpc.org/historical/json-rpc-over-http.html
func WriteRPCResponseHTTPError(
w http.ResponseWriter,
httpCode int,
res types.RPCResponse,
) error {
if res.Error == nil {
panic("tried to write http error response without RPC error")
}
jsonBytes, err := json.Marshal(res)
if err != nil {
return fmt.Errorf("json marshal: %w", err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(httpCode)
_, err = w.Write(jsonBytes)
return err
}
// WriteRPCResponseHTTP marshals res as JSON (with indent) and writes it to w.
func WriteRPCResponseHTTP(w http.ResponseWriter, res ...types.RPCResponse) error {
return writeRPCResponseHTTP(w, []httpHeader{}, res...)
}
// WriteCacheableRPCResponseHTTP marshals res as JSON (with indent) and writes
// it to w. Adds cache-control to the response header and sets the expiry to
// one day.
func WriteCacheableRPCResponseHTTP(w http.ResponseWriter, res ...types.RPCResponse) error {
return writeRPCResponseHTTP(w, []httpHeader{{"Cache-Control", "public, max-age=86400"}}, res...)
}
type httpHeader struct {
name string
value string
}
func writeRPCResponseHTTP(w http.ResponseWriter, headers []httpHeader, res ...types.RPCResponse) error {
var v interface{}
if len(res) == 1 {
v = res[0]
} else {
v = res
}
jsonBytes, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("json marshal: %w", err)
}
w.Header().Set("Content-Type", "application/json")
for _, header := range headers {
w.Header().Set(header.name, header.value)
}
w.WriteHeader(200)
_, err = w.Write(jsonBytes)
return err
}
//-----------------------------------------------------------------------------
// RecoverAndLogHandler wraps an HTTP handler, adding error logging.
// If the inner function panics, the outer function recovers, logs, sends an
// HTTP 500 error response.
func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Wrap the ResponseWriter to remember the status
rww := &responseWriterWrapper{-1, w}
begin := time.Now()
rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
defer func() {
// Handle any panics in the panic handler below. Does not use the logger, since we want
// to avoid any further panics. However, we try to return a 500, since it otherwise
// defaults to 200 and there is no other way to terminate the connection. If that
// should panic for whatever reason then the Go HTTP server will handle it and
// terminate the connection - panicing is the de-facto and only way to get the Go HTTP
// server to terminate the request and close the connection/stream:
// https://github.com/golang/go/issues/17790#issuecomment-258481416
if e := recover(); e != nil {
fmt.Fprintf(os.Stderr, "Panic during RPC panic recovery: %v\n%v\n", e, string(debug.Stack()))
w.WriteHeader(500)
}
}()
defer func() {
// Send a 500 error if a panic happens during a handler.
// Without this, Chrome & Firefox were retrying aborted ajax requests,
// at least to my localhost.
if e := recover(); e != nil {
// If RPCResponse
if res, ok := e.(types.RPCResponse); ok {
if wErr := WriteRPCResponseHTTP(rww, res); wErr != nil {
logger.Error("failed to write response", "err", wErr)
}
} else {
// Panics can contain anything, attempt to normalize it as an error.
var err error
switch e := e.(type) {
case error:
err = e
case string:
err = errors.New(e)
case fmt.Stringer:
err = errors.New(e.String())
default:
}
logger.Error("panic in RPC HTTP handler", "err", e, "stack", string(debug.Stack()))
res := types.RPCInternalError(types.JSONRPCIntID(-1), err)
if wErr := WriteRPCResponseHTTPError(rww, http.StatusInternalServerError, res); wErr != nil {
logger.Error("failed to write response", "err", wErr)
}
}
}
// Finally, log.
durationMS := time.Since(begin).Nanoseconds() / 1000000
if rww.Status == -1 {
rww.Status = 200
}
logger.Debug("served RPC HTTP response",
"method", r.Method,
"url", r.URL,
"status", rww.Status,
"duration", durationMS,
"remoteAddr", r.RemoteAddr,
)
}()
handler.ServeHTTP(rww, r)
})
}
// Remember the status for logging
type responseWriterWrapper struct {
Status int
http.ResponseWriter
}
func (w *responseWriterWrapper) WriteHeader(status int) {
w.Status = status
w.ResponseWriter.WriteHeader(status)
}
// implements http.Hijacker
func (w *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.ResponseWriter.(http.Hijacker).Hijack()
}
type defaultHandler struct {
h http.Handler
}
func (h defaultHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.h.ServeHTTP(w, r)
}
// Listen starts a new net.Listener on the given address.
// It returns an error if the address is invalid or the call to Listen() fails.
func Listen(addr string, maxOpenConnections int) (listener net.Listener, err error) {
parts := strings.SplitN(addr, "://", 2)
if len(parts) != 2 {
return nil, fmt.Errorf(
"invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)",
addr,
)
}
proto, addr := parts[0], parts[1]
listener, err = net.Listen(proto, addr)
if err != nil {
return nil, fmt.Errorf("failed to listen on %v: %v", addr, err)
}
if maxOpenConnections > 0 {
listener = netutil.LimitListener(listener, maxOpenConnections)
}
return listener, nil
}
// Middleware
// PreChecksHandler is a middleware function that checks the size of batch requests and returns an error
// if it exceeds the maximum configured size. It also checks if the request body is not greater than the
// configured maximum request body bytes limit.
func PreChecksHandler(next http.Handler, config *Config) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ensure that the current request body bytes is not greater than the configured maximum request body bytes
r.Body = http.MaxBytesReader(w, r.Body, config.MaxBodyBytes)
// if maxBatchSize is 0 then don't constraint the limit of requests per batch
// It cannot be negative because the config.toml validation requires it to be
// greater than or equal to 0
if config.MaxRequestBatchSize > 0 {
var requests []types.RPCRequest
var responses []types.RPCResponse
var err error
data, err := io.ReadAll(r.Body)
if err != nil {
res := types.RPCInvalidRequestError(nil, fmt.Errorf("error reading request body: %w", err))
_ = WriteRPCResponseHTTPError(w, http.StatusBadRequest, res)
return
}
err = json.Unmarshal(data, &requests)
// if no err it means multiple requests, check if the number of request exceeds
// the maximum batch size configured
if err == nil {
// if the number of requests in batch exceed the maximum configured then return an error
if len(requests) > config.MaxRequestBatchSize {
res := types.RPCInvalidRequestError(nil, fmt.Errorf("batch request exceeds maximum (%d) allowed number of requests", config.MaxRequestBatchSize))
responses = append(responses, res)
_ = WriteRPCResponseHTTP(w, responses...)
return
}
}
// ensure the request body can be read again by other handlers
r.Body = io.NopCloser(bytes.NewBuffer(data))
}
// next handler
next.ServeHTTP(w, r)
})
}
package server
import (
"fmt"
"net/http"
"reflect"
"strings"
"github.com/cometbft/cometbft/libs/log"
)
// RegisterRPCFuncs adds a route for each function in the funcMap, as well as
// general jsonrpc and websocket handlers for all functions. "result" is the
// interface on which the result objects are registered, and is popualted with
// every RPCResponse
func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, logger log.Logger) {
// HTTP endpoints
for funcName, rpcFunc := range funcMap {
mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc, logger))
}
// JSONRPC endpoints
mux.HandleFunc("/", handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, logger)))
}
type Option func(*RPCFunc)
// Cacheable enables returning a cache control header from RPC functions to
// which it is applied.
//
// `noCacheDefArgs` is a list of argument names that, if omitted or set to
// their defaults when calling the RPC function, will skip the response
// caching.
func Cacheable(noCacheDefArgs ...string) Option {
return func(r *RPCFunc) {
r.cacheable = true
r.noCacheDefArgs = make(map[string]interface{})
for _, arg := range noCacheDefArgs {
r.noCacheDefArgs[arg] = nil
}
}
}
// Ws enables WebSocket communication.
func Ws() Option {
return func(r *RPCFunc) {
r.ws = true
}
}
// RPCFunc contains the introspected type information for a function
type RPCFunc struct {
f reflect.Value // underlying rpc function
args []reflect.Type // type of each function arg
returns []reflect.Type // type of each return arg
argNames []string // name of each argument
cacheable bool // enable cache control
ws bool // enable websocket communication
noCacheDefArgs map[string]interface{} // a lookup table of args that, if not supplied or are set to default values, cause us to not cache
}
// NewRPCFunc wraps a function for introspection.
// f is the function, args are comma separated argument names
func NewRPCFunc(f interface{}, args string, options ...Option) *RPCFunc {
return newRPCFunc(f, args, options...)
}
// NewWSRPCFunc wraps a function for introspection and use in the websockets.
func NewWSRPCFunc(f interface{}, args string, options ...Option) *RPCFunc {
options = append(options, Ws())
return newRPCFunc(f, args, options...)
}
// cacheableWithArgs returns whether or not a call to this function is cacheable,
// given the specified arguments.
func (f *RPCFunc) cacheableWithArgs(args []reflect.Value) bool {
if !f.cacheable {
return false
}
// Skip the context variable common to all RPC functions
for i := 1; i < len(f.args); i++ {
// f.argNames does not include the context variable
argName := f.argNames[i-1]
if _, hasDefault := f.noCacheDefArgs[argName]; hasDefault {
// Argument with default value was not supplied
if i >= len(args) {
return false
}
// Argument with default value is set to its zero value
if args[i].IsZero() {
return false
}
}
}
return true
}
func newRPCFunc(f interface{}, args string, options ...Option) *RPCFunc {
var argNames []string
if args != "" {
argNames = strings.Split(args, ",")
}
r := &RPCFunc{
f: reflect.ValueOf(f),
args: funcArgTypes(f),
returns: funcReturnTypes(f),
argNames: argNames,
}
for _, opt := range options {
opt(r)
}
return r
}
// return a function's argument types
func funcArgTypes(f interface{}) []reflect.Type {
t := reflect.TypeOf(f)
n := t.NumIn()
typez := make([]reflect.Type, n)
for i := 0; i < n; i++ {
typez[i] = t.In(i)
}
return typez
}
// return a function's return types
func funcReturnTypes(f interface{}) []reflect.Type {
t := reflect.TypeOf(f)
n := t.NumOut()
typez := make([]reflect.Type, n)
for i := 0; i < n; i++ {
typez[i] = t.Out(i)
}
return typez
}
//-------------------------------------------------------------
// NOTE: assume returns is result struct and error. If error is not nil, return it
func unreflectResult(returns []reflect.Value) (interface{}, error) {
errV := returns[1]
if errV.Interface() != nil {
return nil, fmt.Errorf("%v", errV.Interface())
}
rv := returns[0]
// the result is a registered interface,
// we need a pointer to it so we can marshal with type byte
rvp := reflect.New(rv.Type())
rvp.Elem().Set(rv)
return rvp.Interface(), nil
}
package types
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
cmtjson "github.com/cometbft/cometbft/libs/json"
)
// a wrapper to emulate a sum type: jsonrpcid = string | int
// TODO: refactor when Go 2.0 arrives https://github.com/golang/go/issues/19412
type jsonrpcid interface {
isJSONRPCID()
}
// JSONRPCStringID a wrapper for JSON-RPC string IDs
type JSONRPCStringID string
func (JSONRPCStringID) isJSONRPCID() {}
func (id JSONRPCStringID) String() string { return string(id) }
// JSONRPCIntID a wrapper for JSON-RPC integer IDs
type JSONRPCIntID int
func (JSONRPCIntID) isJSONRPCID() {}
func (id JSONRPCIntID) String() string { return fmt.Sprintf("%d", id) }
func idFromInterface(idInterface interface{}) (jsonrpcid, error) {
switch id := idInterface.(type) {
case string:
return JSONRPCStringID(id), nil
case float64:
// json.Unmarshal uses float64 for all numbers
// (https://golang.org/pkg/encoding/json/#Unmarshal),
// but the JSONRPC2.0 spec says the id SHOULD NOT contain
// decimals - so we truncate the decimals here.
return JSONRPCIntID(int(id)), nil
default:
typ := reflect.TypeOf(id)
return nil, fmt.Errorf("json-rpc ID (%v) is of unknown type (%v)", id, typ)
}
}
//----------------------------------------
// REQUEST
type RPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID jsonrpcid `json:"id,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params"` // must be map[string]interface{} or []interface{}
}
// UnmarshalJSON custom JSON unmarshalling due to jsonrpcid being string or int
func (req *RPCRequest) UnmarshalJSON(data []byte) error {
unsafeReq := struct {
JSONRPC string `json:"jsonrpc"`
ID interface{} `json:"id,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params"` // must be map[string]interface{} or []interface{}
}{}
err := json.Unmarshal(data, &unsafeReq)
if err != nil {
return err
}
if unsafeReq.ID == nil { // notification
return nil
}
req.JSONRPC = unsafeReq.JSONRPC
req.Method = unsafeReq.Method
req.Params = unsafeReq.Params
id, err := idFromInterface(unsafeReq.ID)
if err != nil {
return err
}
req.ID = id
return nil
}
func NewRPCRequest(id jsonrpcid, method string, params json.RawMessage) RPCRequest {
return RPCRequest{
JSONRPC: "2.0",
ID: id,
Method: method,
Params: params,
}
}
func (req RPCRequest) String() string {
return fmt.Sprintf("RPCRequest{%s %s/%X}", req.ID, req.Method, req.Params)
}
func MapToRequest(id jsonrpcid, method string, params map[string]interface{}) (RPCRequest, error) {
var paramsMap = make(map[string]json.RawMessage, len(params))
for name, value := range params {
valueJSON, err := cmtjson.Marshal(value)
if err != nil {
return RPCRequest{}, err
}
paramsMap[name] = valueJSON
}
payload, err := json.Marshal(paramsMap)
if err != nil {
return RPCRequest{}, err
}
return NewRPCRequest(id, method, payload), nil
}
func ArrayToRequest(id jsonrpcid, method string, params []interface{}) (RPCRequest, error) {
var paramsMap = make([]json.RawMessage, len(params))
for i, value := range params {
valueJSON, err := cmtjson.Marshal(value)
if err != nil {
return RPCRequest{}, err
}
paramsMap[i] = valueJSON
}
payload, err := json.Marshal(paramsMap)
if err != nil {
return RPCRequest{}, err
}
return NewRPCRequest(id, method, payload), nil
}
//----------------------------------------
// RESPONSE
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data string `json:"data,omitempty"`
}
func (err RPCError) Error() string {
const baseFormat = "RPC error %v - %s"
if err.Data != "" {
return fmt.Sprintf(baseFormat+": %s", err.Code, err.Message, err.Data)
}
return fmt.Sprintf(baseFormat, err.Code, err.Message)
}
type RPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID jsonrpcid `json:"id,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}
// UnmarshalJSON custom JSON unmarshalling due to jsonrpcid being string or int
func (resp *RPCResponse) UnmarshalJSON(data []byte) error {
unsafeResp := &struct {
JSONRPC string `json:"jsonrpc"`
ID interface{} `json:"id,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}{}
err := json.Unmarshal(data, &unsafeResp)
if err != nil {
return err
}
resp.JSONRPC = unsafeResp.JSONRPC
resp.Error = unsafeResp.Error
resp.Result = unsafeResp.Result
if unsafeResp.ID == nil {
return nil
}
id, err := idFromInterface(unsafeResp.ID)
if err != nil {
return err
}
resp.ID = id
return nil
}
func NewRPCSuccessResponse(id jsonrpcid, res interface{}) RPCResponse {
var rawMsg json.RawMessage
if res != nil {
var js []byte
js, err := cmtjson.Marshal(res)
if err != nil {
return RPCInternalError(id, fmt.Errorf("error marshaling response: %w", err))
}
rawMsg = json.RawMessage(js)
}
return RPCResponse{JSONRPC: "2.0", ID: id, Result: rawMsg}
}
func NewRPCErrorResponse(id jsonrpcid, code int, msg string, data string) RPCResponse {
return RPCResponse{
JSONRPC: "2.0",
ID: id,
Error: &RPCError{Code: code, Message: msg, Data: data},
}
}
func (resp RPCResponse) String() string {
if resp.Error == nil {
return fmt.Sprintf("RPCResponse{%s %X}", resp.ID, resp.Result)
}
return fmt.Sprintf("RPCResponse{%s %v}", resp.ID, resp.Error)
}
// From the JSON-RPC 2.0 spec:
//
// If there was an error in detecting the id in the Request object (e.g. Parse
// error/Invalid Request), it MUST be Null.
func RPCParseError(err error) RPCResponse {
return NewRPCErrorResponse(nil, -32700, "Parse error. Invalid JSON", err.Error())
}
// From the JSON-RPC 2.0 spec:
//
// If there was an error in detecting the id in the Request object (e.g. Parse
// error/Invalid Request), it MUST be Null.
func RPCInvalidRequestError(id jsonrpcid, err error) RPCResponse {
return NewRPCErrorResponse(id, -32600, "Invalid Request", err.Error())
}
func RPCMethodNotFoundError(id jsonrpcid) RPCResponse {
return NewRPCErrorResponse(id, -32601, "Method not found", "")
}
func RPCInvalidParamsError(id jsonrpcid, err error) RPCResponse {
return NewRPCErrorResponse(id, -32602, "Invalid params", err.Error())
}
func RPCInternalError(id jsonrpcid, err error) RPCResponse {
return NewRPCErrorResponse(id, -32603, "Internal error", err.Error())
}
func RPCServerError(id jsonrpcid, err error) RPCResponse {
return NewRPCErrorResponse(id, -32000, "Server error", err.Error())
}
//----------------------------------------
// WSRPCConnection represents a websocket connection.
type WSRPCConnection interface {
// GetRemoteAddr returns a remote address of the connection.
GetRemoteAddr() string
// WriteRPCResponse writes the response onto connection (BLOCKING).
WriteRPCResponse(context.Context, RPCResponse) error
// TryWriteRPCResponse tries to write the response onto connection (NON-BLOCKING).
TryWriteRPCResponse(RPCResponse) bool
// Context returns the connection's context.
Context() context.Context
}
// Context is the first parameter for all functions. It carries a json-rpc
// request, http request and websocket connection.
//
// - JSONReq is non-nil when JSONRPC is called over websocket or HTTP.
// - WSConn is non-nil when we're connected via a websocket.
// - HTTPReq is non-nil when URI or JSONRPC is called over HTTP.
type Context struct {
// json-rpc request
JSONReq *RPCRequest
// websocket connection
WSConn WSRPCConnection
// http request
HTTPReq *http.Request
}
// RemoteAddr returns the remote address (usually a string "IP:port").
// If neither HTTPReq nor WSConn is set, an empty string is returned.
// HTTP:
//
// http.Request#RemoteAddr
//
// WS:
//
// result of GetRemoteAddr
func (ctx *Context) RemoteAddr() string {
if ctx.HTTPReq != nil {
return ctx.HTTPReq.RemoteAddr
} else if ctx.WSConn != nil {
return ctx.WSConn.GetRemoteAddr()
}
return ""
}
// Context returns the request's context.
// The returned context is always non-nil; it defaults to the background context.
// HTTP:
//
// The context is canceled when the client's connection closes, the request
// is canceled (with HTTP/2), or when the ServeHTTP method returns.
//
// WS:
//
// The context is canceled when the client's connections closes.
func (ctx *Context) Context() context.Context {
if ctx.HTTPReq != nil {
return ctx.HTTPReq.Context()
} else if ctx.WSConn != nil {
return ctx.WSConn.Context()
}
return context.Background()
}
//----------------------------------------
// SOCKETS
// Determine if its a unix or tcp socket.
// If tcp, must specify the port; `0.0.0.0` will return incorrectly as "unix" since there's no port
// TODO: deprecate
func SocketType(listenAddr string) string {
socketType := "unix"
if len(strings.Split(listenAddr, ":")) >= 2 {
socketType = "tcp"
}
return socketType
}
package kv
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/gogoproto/proto"
dbm "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
idxutil "github.com/cometbft/cometbft/internal/indexer"
"github.com/cometbft/cometbft/libs/pubsub/query"
"github.com/cometbft/cometbft/libs/pubsub/query/syntax"
"github.com/cometbft/cometbft/state/indexer"
"github.com/cometbft/cometbft/state/txindex"
"github.com/cometbft/cometbft/types"
)
const (
tagKeySeparator = "/"
tagKeySeparatorRune = '/'
eventSeqSeparator = "$es$"
)
var _ txindex.TxIndexer = (*TxIndex)(nil)
// TxIndex is the simplest possible indexer, backed by key-value storage (levelDB).
type TxIndex struct {
store dbm.DB
// Number the events in the event list
eventSeq int64
log log.Logger
}
// NewTxIndex creates new KV indexer.
func NewTxIndex(store dbm.DB) *TxIndex {
return &TxIndex{
store: store,
}
}
func (txi *TxIndex) SetLogger(l log.Logger) {
txi.log = l
}
// Get gets transaction from the TxIndex storage and returns it or nil if the
// transaction is not found.
func (txi *TxIndex) Get(hash []byte) (*abci.TxResult, error) {
if len(hash) == 0 {
return nil, txindex.ErrorEmptyHash
}
rawBytes, err := txi.store.Get(hash)
if err != nil {
panic(err)
}
if rawBytes == nil {
return nil, nil
}
txResult := new(abci.TxResult)
err = proto.Unmarshal(rawBytes, txResult)
if err != nil {
return nil, fmt.Errorf("error reading TxResult: %v", err)
}
return txResult, nil
}
// AddBatch indexes a batch of transactions using the given list of events. Each
// key that indexed from the tx's events is a composite of the event type and
// the respective attribute's key delimited by a "." (eg. "account.number").
// Any event with an empty type is not indexed.
func (txi *TxIndex) AddBatch(b *txindex.Batch) error {
storeBatch := txi.store.NewBatch()
defer storeBatch.Close()
for _, result := range b.Ops {
hash := types.Tx(result.Tx).Hash()
// index tx by events
err := txi.indexEvents(result, hash, storeBatch)
if err != nil {
return err
}
// index by height (always)
err = storeBatch.Set(keyForHeight(result), hash)
if err != nil {
return err
}
rawBytes, err := proto.Marshal(result)
if err != nil {
return err
}
// index by hash (always)
err = storeBatch.Set(hash, rawBytes)
if err != nil {
return err
}
}
return storeBatch.WriteSync()
}
// Index indexes a single transaction using the given list of events. Each key
// that indexed from the tx's events is a composite of the event type and the
// respective attribute's key delimited by a "." (eg. "account.number").
// Any event with an empty type is not indexed.
//
// If a transaction is indexed with the same hash as a previous transaction, it will
// be overwritten unless the tx result was NOT OK and the prior result was OK i.e.
// more transactions that successfully executed overwrite transactions that failed
// or successful yet older transactions.
func (txi *TxIndex) Index(result *abci.TxResult) error {
b := txi.store.NewBatch()
defer b.Close()
hash := types.Tx(result.Tx).Hash()
if !result.Result.IsOK() {
oldResult, err := txi.Get(hash)
if err != nil {
return err
}
// if the new transaction failed and it's already indexed in an older block and was successful
// we skip it as we want users to get the older successful transaction when they query.
if oldResult != nil && oldResult.Result.Code == abci.CodeTypeOK {
return nil
}
}
// index tx by events
err := txi.indexEvents(result, hash, b)
if err != nil {
return err
}
// index by height (always)
err = b.Set(keyForHeight(result), hash)
if err != nil {
return err
}
rawBytes, err := proto.Marshal(result)
if err != nil {
return err
}
// index by hash (always)
err = b.Set(hash, rawBytes)
if err != nil {
return err
}
return b.WriteSync()
}
func (txi *TxIndex) indexEvents(result *abci.TxResult, hash []byte, store dbm.Batch) error {
for _, event := range result.Result.Events {
txi.eventSeq = txi.eventSeq + 1
// only index events with a non-empty type
if len(event.Type) == 0 {
continue
}
for _, attr := range event.Attributes {
if len(attr.Key) == 0 {
continue
}
// index if `index: true` is set
compositeTag := fmt.Sprintf("%s.%s", event.Type, attr.Key)
// ensure event does not conflict with a reserved prefix key
if compositeTag == types.TxHashKey || compositeTag == types.TxHeightKey {
return fmt.Errorf("event type and attribute key \"%s\" is reserved; please use a different key", compositeTag)
}
if attr.GetIndex() {
err := store.Set(keyForEvent(compositeTag, attr.Value, result, txi.eventSeq), hash)
if err != nil {
return err
}
}
}
}
return nil
}
// Search performs a search using the given query.
//
// It breaks the query into conditions (like "tx.height > 5"). For each
// condition, it queries the DB index. One special use cases here: (1) if
// "tx.hash" is found, it returns tx result for it (2) for range queries it is
// better for the client to provide both lower and upper bounds, so we are not
// performing a full scan. Results from querying indexes are then intersected
// and returned to the caller, in no particular order.
//
// Search will exit early and return any result fetched so far,
// when a message is received on the context chan.
func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) {
select {
case <-ctx.Done():
return make([]*abci.TxResult, 0), nil
default:
}
var hashesInitialized bool
filteredHashes := make(map[string][]byte)
// get a list of conditions (like "tx.height > 5")
conditions := q.Syntax()
// if there is a hash condition, return the result immediately
hash, ok, err := lookForHash(conditions)
if err != nil {
return nil, fmt.Errorf("error during searching for a hash in the query: %w", err)
} else if ok {
res, err := txi.Get(hash)
switch {
case err != nil:
return []*abci.TxResult{}, fmt.Errorf("error while retrieving the result: %w", err)
case res == nil:
return []*abci.TxResult{}, nil
default:
return []*abci.TxResult{res}, nil
}
}
// conditions to skip because they're handled before "everything else"
skipIndexes := make([]int, 0)
var heightInfo HeightInfo
// If we are not matching events and tx.height = 3 occurs more than once, the later value will
// overwrite the first one.
conditions, heightInfo = dedupHeight(conditions)
if !heightInfo.onlyHeightEq {
skipIndexes = append(skipIndexes, heightInfo.heightEqIdx)
}
// extract ranges
// if both upper and lower bounds exist, it's better to get them in order not
// no iterate over kvs that are not within range.
ranges, rangeIndexes, heightRange := indexer.LookForRangesWithHeight(conditions)
heightInfo.heightRange = heightRange
if len(ranges) > 0 {
skipIndexes = append(skipIndexes, rangeIndexes...)
for _, qr := range ranges {
// If we have a query range over height and want to still look for
// specific event values we do not want to simply return all
// transactios in this height range. We remember the height range info
// and pass it on to match() to take into account when processing events.
if qr.Key == types.TxHeightKey && !heightInfo.onlyHeightRange {
continue
}
if !hashesInitialized {
filteredHashes = txi.matchRange(ctx, qr, startKey(qr.Key), filteredHashes, true, heightInfo)
hashesInitialized = true
// Ignore any remaining conditions if the first condition resulted
// in no matches (assuming implicit AND operand).
if len(filteredHashes) == 0 {
break
}
} else {
filteredHashes = txi.matchRange(ctx, qr, startKey(qr.Key), filteredHashes, false, heightInfo)
}
}
}
// if there is a height condition ("tx.height=3"), extract it
// for all other conditions
for i, c := range conditions {
if intInSlice(i, skipIndexes) {
continue
}
if !hashesInitialized {
filteredHashes = txi.match(ctx, c, startKeyForCondition(c, heightInfo.height), filteredHashes, true, heightInfo)
hashesInitialized = true
// Ignore any remaining conditions if the first condition resulted
// in no matches (assuming implicit AND operand).
if len(filteredHashes) == 0 {
break
}
} else {
filteredHashes = txi.match(ctx, c, startKeyForCondition(c, heightInfo.height), filteredHashes, false, heightInfo)
}
}
results := make([]*abci.TxResult, 0, len(filteredHashes))
resultMap := make(map[string]struct{})
RESULTS_LOOP:
for _, h := range filteredHashes {
res, err := txi.Get(h)
if err != nil {
return nil, fmt.Errorf("failed to get Tx{%X}: %w", h, err)
}
hashString := string(h)
if _, ok := resultMap[hashString]; !ok {
resultMap[hashString] = struct{}{}
results = append(results, res)
}
// Potentially exit early.
select {
case <-ctx.Done():
break RESULTS_LOOP
default:
}
}
return results, nil
}
func lookForHash(conditions []syntax.Condition) (hash []byte, ok bool, err error) {
for _, c := range conditions {
if c.Tag == types.TxHashKey {
decoded, err := hex.DecodeString(c.Arg.Value())
return decoded, true, err
}
}
return
}
func (*TxIndex) setTmpHashes(tmpHeights map[string][]byte, key, value []byte) {
eventSeq := extractEventSeqFromKey(key)
// Copy the value because the iterator will be reused.
valueCopy := make([]byte, len(value))
copy(valueCopy, value)
tmpHeights[string(valueCopy)+eventSeq] = valueCopy
}
// match returns all matching txs by hash that meet a given condition and start
// key. An already filtered result (filteredHashes) is provided such that any
// non-intersecting matches are removed.
//
// NOTE: filteredHashes may be empty if no previous condition has matched.
func (txi *TxIndex) match(
ctx context.Context,
c syntax.Condition,
startKeyBz []byte,
filteredHashes map[string][]byte,
firstRun bool,
heightInfo HeightInfo,
) map[string][]byte {
// A previous match was attempted but resulted in no matches, so we return
// no matches (assuming AND operand).
if !firstRun && len(filteredHashes) == 0 {
return filteredHashes
}
tmpHashes := make(map[string][]byte)
switch {
case c.Op == syntax.TEq:
it, err := dbm.IteratePrefix(txi.store, startKeyBz)
if err != nil {
panic(err)
}
defer it.Close()
EQ_LOOP:
for ; it.Valid(); it.Next() {
// If we have a height range in a query, we need only transactions
// for this height
key := it.Key()
keyHeight, err := extractHeightFromKey(key)
if err != nil {
txi.log.Error("failure to parse height from key:", err)
continue
}
withinBounds, err := checkHeightConditions(heightInfo, keyHeight)
if err != nil {
txi.log.Error("failure checking for height bounds:", err)
continue
}
if !withinBounds {
continue
}
txi.setTmpHashes(tmpHashes, key, it.Value())
// Potentially exit early.
select {
case <-ctx.Done():
break EQ_LOOP
default:
}
}
if err := it.Error(); err != nil {
panic(err)
}
case c.Op == syntax.TExists:
// XXX: can't use startKeyBz here because c.Operand is nil
// (e.g. "account.owner/<nil>/" won't match w/ a single row)
it, err := dbm.IteratePrefix(txi.store, startKey(c.Tag))
if err != nil {
panic(err)
}
defer it.Close()
EXISTS_LOOP:
for ; it.Valid(); it.Next() {
key := it.Key()
keyHeight, err := extractHeightFromKey(key)
if err != nil {
txi.log.Error("failure to parse height from key:", err)
continue
}
withinBounds, err := checkHeightConditions(heightInfo, keyHeight)
if err != nil {
txi.log.Error("failure checking for height bounds:", err)
continue
}
if !withinBounds {
continue
}
txi.setTmpHashes(tmpHashes, key, it.Value())
// Potentially exit early.
select {
case <-ctx.Done():
break EXISTS_LOOP
default:
}
}
if err := it.Error(); err != nil {
panic(err)
}
case c.Op == syntax.TContains:
// XXX: startKey does not apply here.
// For example, if startKey = "account.owner/an/" and search query = "account.owner CONTAINS an"
// we can't iterate with prefix "account.owner/an/" because we might miss keys like "account.owner/Ulan/"
it, err := dbm.IteratePrefix(txi.store, startKey(c.Tag))
if err != nil {
panic(err)
}
defer it.Close()
CONTAINS_LOOP:
for ; it.Valid(); it.Next() {
if !isTagKey(it.Key()) {
continue
}
if strings.Contains(extractValueFromKey(it.Key()), c.Arg.Value()) {
key := it.Key()
keyHeight, err := extractHeightFromKey(key)
if err != nil {
txi.log.Error("failure to parse height from key:", err)
continue
}
withinBounds, err := checkHeightConditions(heightInfo, keyHeight)
if err != nil {
txi.log.Error("failure checking for height bounds:", err)
continue
}
if !withinBounds {
continue
}
txi.setTmpHashes(tmpHashes, key, it.Value())
}
// Potentially exit early.
select {
case <-ctx.Done():
break CONTAINS_LOOP
default:
}
}
if err := it.Error(); err != nil {
panic(err)
}
default:
panic("other operators should be handled already")
}
if len(tmpHashes) == 0 || firstRun {
// Either:
//
// 1. Regardless if a previous match was attempted, which may have had
// results, but no match was found for the current condition, then we
// return no matches (assuming AND operand).
//
// 2. A previous match was not attempted, so we return all results.
return tmpHashes
}
// Remove/reduce matches in filteredHashes that were not found in this
// match (tmpHashes).
REMOVE_LOOP:
for k, v := range filteredHashes {
tmpHash := tmpHashes[k]
if tmpHash == nil || !bytes.Equal(tmpHash, v) {
delete(filteredHashes, k)
// Potentially exit early.
select {
case <-ctx.Done():
break REMOVE_LOOP
default:
}
}
}
return filteredHashes
}
// matchRange returns all matching txs by hash that meet a given queryRange and
// start key. An already filtered result (filteredHashes) is provided such that
// any non-intersecting matches are removed.
//
// NOTE: filteredHashes may be empty if no previous condition has matched.
func (txi *TxIndex) matchRange(
ctx context.Context,
qr indexer.QueryRange,
startKey []byte,
filteredHashes map[string][]byte,
firstRun bool,
heightInfo HeightInfo,
) map[string][]byte {
// A previous match was attempted but resulted in no matches, so we return
// no matches (assuming AND operand).
if !firstRun && len(filteredHashes) == 0 {
return filteredHashes
}
tmpHashes := make(map[string][]byte)
it, err := dbm.IteratePrefix(txi.store, startKey)
if err != nil {
panic(err)
}
defer it.Close()
bigIntValue := new(big.Int)
LOOP:
for ; it.Valid(); it.Next() {
// TODO: We need to make a function for getting it.Key() as a byte slice with no copies.
// It currently copies the source data (which can change on a subsequent .Next() call) but that
// is not an issue for us.
key := it.Key()
if !isTagKey(key) {
continue
}
if _, ok := qr.AnyBound().(*big.Float); ok {
value := extractValueFromKey(key)
v, ok := bigIntValue.SetString(value, 10)
var vF *big.Float
if !ok {
vF, _, err = big.ParseFloat(value, 10, 125, big.ToNearestEven)
if err != nil {
continue LOOP
}
}
if qr.Key != types.TxHeightKey {
keyHeight, err := extractHeightFromKey(key)
if err != nil {
txi.log.Error("failure to parse height from key:", err)
continue
}
withinBounds, err := checkHeightConditions(heightInfo, keyHeight)
if err != nil {
txi.log.Error("failure checking for height bounds:", err)
continue
}
if !withinBounds {
continue
}
}
var withinBounds bool
var err error
if !ok {
withinBounds, err = idxutil.CheckBounds(qr, vF)
} else {
withinBounds, err = idxutil.CheckBounds(qr, v)
}
if err != nil {
txi.log.Error("failed to parse bounds:", err)
} else if withinBounds {
txi.setTmpHashes(tmpHashes, key, it.Value())
}
// XXX: passing time in a ABCI Events is not yet implemented
// case time.Time:
// v := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64)
// if v == r.upperBound {
// break
// }
}
// Potentially exit early.
select {
case <-ctx.Done():
break LOOP
default:
}
}
if err := it.Error(); err != nil {
panic(err)
}
if len(tmpHashes) == 0 || firstRun {
// Either:
//
// 1. Regardless if a previous match was attempted, which may have had
// results, but no match was found for the current condition, then we
// return no matches (assuming AND operand).
//
// 2. A previous match was not attempted, so we return all results.
return tmpHashes
}
// Remove/reduce matches in filteredHashes that were not found in this
// match (tmpHashes).
REMOVE_LOOP:
for k, v := range filteredHashes {
tmpHash := tmpHashes[k]
if tmpHash == nil || !bytes.Equal(tmpHashes[k], v) {
delete(filteredHashes, k)
// Potentially exit early.
select {
case <-ctx.Done():
break REMOVE_LOOP
default:
}
}
}
return filteredHashes
}
// Keys
func isTagKey(key []byte) bool {
// Normally, if the event was indexed with an event sequence, the number of
// tags should 4. Alternatively it should be 3 if the event was not indexed
// with the corresponding event sequence. However, some attribute values in
// production can contain the tag separator. Therefore, the condition is >= 3.
numTags := 0
for i := 0; i < len(key); i++ {
if key[i] == tagKeySeparatorRune {
numTags++
if numTags >= 3 {
return true
}
}
}
return false
}
func extractHeightFromKey(key []byte) (int64, error) {
// the height is the second last element in the key.
// Find the position of the last occurrence of tagKeySeparator
endPos := bytes.LastIndexByte(key, tagKeySeparatorRune)
if endPos == -1 {
return 0, errors.New("separator not found")
}
// Find the position of the second last occurrence of tagKeySeparator
startPos := bytes.LastIndexByte(key[:endPos-1], tagKeySeparatorRune)
if startPos == -1 {
return 0, errors.New("second last separator not found")
}
// Extract the height part of the key
height, err := strconv.ParseInt(string(key[startPos+1:endPos]), 10, 64)
if err != nil {
return 0, err
}
return height, nil
}
func extractValueFromKey(key []byte) string {
// Find the positions of tagKeySeparator in the byte slice
var indices []int
for i, b := range key {
if b == tagKeySeparatorRune {
indices = append(indices, i)
}
}
// If there are less than 2 occurrences of tagKeySeparator, return an empty string
if len(indices) < 2 {
return ""
}
// Extract the value between the first and second last occurrence of tagKeySeparator
value := key[indices[0]+1 : indices[len(indices)-2]]
// Trim any leading or trailing whitespace
value = bytes.TrimSpace(value)
// TODO: Do an unsafe cast to avoid an extra allocation here
return string(value)
}
func extractEventSeqFromKey(key []byte) string {
parts := strings.SplitN(string(key), tagKeySeparator, -1)
lastEl := parts[len(parts)-1]
if strings.Contains(lastEl, eventSeqSeparator) {
return strings.SplitN(lastEl, eventSeqSeparator, 2)[1]
}
return "0"
}
func keyForEvent(key string, value string, result *abci.TxResult, eventSeq int64) []byte {
return []byte(fmt.Sprintf("%s/%s/%d/%d%s",
key,
value,
result.Height,
result.Index,
eventSeqSeparator+strconv.FormatInt(eventSeq, 10),
))
}
func keyForHeight(result *abci.TxResult) []byte {
return []byte(fmt.Sprintf("%s/%d/%d/%d%s",
types.TxHeightKey,
result.Height,
result.Height,
result.Index,
// Added to facilitate having the eventSeq in event keys
// Otherwise queries break expecting 5 entries
eventSeqSeparator+"0",
))
}
func startKeyForCondition(c syntax.Condition, height int64) []byte {
if height > 0 {
return startKey(c.Tag, c.Arg.Value(), height)
}
return startKey(c.Tag, c.Arg.Value())
}
func startKey(fields ...interface{}) []byte {
var b bytes.Buffer
for _, f := range fields {
b.Write([]byte(fmt.Sprintf("%v", f) + tagKeySeparator))
}
return b.Bytes()
}
package store
import (
"errors"
"fmt"
"strconv"
"github.com/cosmos/gogoproto/proto"
lru "github.com/hashicorp/golang-lru/v2"
dbm "github.com/cometbft/cometbft-db"
"github.com/cometbft/cometbft/evidence"
cmtsync "github.com/cometbft/cometbft/libs/sync"
cmtstore "github.com/cometbft/cometbft/proto/tendermint/store"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
sm "github.com/cometbft/cometbft/state"
"github.com/cometbft/cometbft/types"
)
// Assuming the length of a block part is 64kB (`types.BlockPartSizeBytes`),
// the maximum size of a block, that will be batch saved, is 640kB. The
// benchmarks have shown that `goleveldb` still performs well with blocks of
// this size. However, if the block is larger than 1MB, the performance degrades.
const maxBlockPartsToBatch = 10
/*
BlockStore is a simple low level store for blocks.
There are three types of information stored:
- BlockMeta: Meta information about each block
- Block part: Parts of each block, aggregated w/ PartSet
- Commit: The commit part of each block, for gossiping precommit votes
Currently the precommit signatures are duplicated in the Block parts as
well as the Commit. In the future this may change, perhaps by moving
the Commit data outside the Block. (TODO)
The store can be assumed to contain all contiguous blocks between base and height (inclusive).
// NOTE: BlockStore methods will panic if they encounter errors
// deserializing loaded data, indicating probable corruption on disk.
*/
type BlockStore struct {
db dbm.DB
// mtx guards access to the struct fields listed below it. Although we rely on the database
// to enforce fine-grained concurrency control for its data, we need to make sure that
// no external observer can get data from the database that is not in sync with the fields below,
// and vice-versa. Hence, when updating the fields below, we use the mutex to make sure
// that the database is also up to date. This prevents any concurrent external access from
// obtaining inconsistent data.
// The only reason for keeping these fields in the struct is that the data
// can't efficiently be queried from the database since the key encoding we use is not
// lexicographically ordered (see https://github.com/tendermint/tendermint/issues/4567).
mtx cmtsync.RWMutex
base int64
height int64
seenCommitCache *lru.Cache[int64, *types.Commit]
blockCommitCache *lru.Cache[int64, *types.Commit]
blockExtendedCommitCache *lru.Cache[int64, *types.ExtendedCommit]
}
// NewBlockStore returns a new BlockStore with the given DB,
// initialized to the last height that was committed to the DB.
func NewBlockStore(db dbm.DB) *BlockStore {
bs := LoadBlockStoreState(db)
bStore := &BlockStore{
base: bs.Base,
height: bs.Height,
db: db,
}
bStore.addCaches()
return bStore
}
func (bs *BlockStore) addCaches() {
var err error
// err can only occur if the argument is non-positive, so is impossible in context.
bs.blockCommitCache, err = lru.New[int64, *types.Commit](100)
if err != nil {
panic(err)
}
bs.blockExtendedCommitCache, err = lru.New[int64, *types.ExtendedCommit](100)
if err != nil {
panic(err)
}
bs.seenCommitCache, err = lru.New[int64, *types.Commit](100)
if err != nil {
panic(err)
}
}
func (bs *BlockStore) IsEmpty() bool {
bs.mtx.RLock()
defer bs.mtx.RUnlock()
return bs.base == bs.height && bs.base == 0
}
// Base returns the first known contiguous block height, or 0 for empty block stores.
func (bs *BlockStore) Base() int64 {
bs.mtx.RLock()
defer bs.mtx.RUnlock()
return bs.base
}
// Height returns the last known contiguous block height, or 0 for empty block stores.
func (bs *BlockStore) Height() int64 {
bs.mtx.RLock()
defer bs.mtx.RUnlock()
return bs.height
}
// Size returns the number of blocks in the block store.
func (bs *BlockStore) Size() int64 {
bs.mtx.RLock()
defer bs.mtx.RUnlock()
if bs.height == 0 {
return 0
}
return bs.height - bs.base + 1
}
// LoadBase atomically loads the base block meta, or returns nil if no base is found.
func (bs *BlockStore) LoadBaseMeta() *types.BlockMeta {
bs.mtx.RLock()
defer bs.mtx.RUnlock()
if bs.base == 0 {
return nil
}
return bs.LoadBlockMeta(bs.base)
}
// LoadBlock returns the block with the given height.
// If no block is found for that height, it returns nil.
func (bs *BlockStore) LoadBlock(height int64) *types.Block {
blockMeta := bs.LoadBlockMeta(height)
if blockMeta == nil {
return nil
}
pbb := new(cmtproto.Block)
buf := []byte{}
for i := 0; i < int(blockMeta.BlockID.PartSetHeader.Total); i++ {
part := bs.LoadBlockPart(height, i)
// If the part is missing (e.g. since it has been deleted after we
// loaded the block meta) we consider the whole block to be missing.
if part == nil {
return nil
}
buf = append(buf, part.Bytes...)
}
err := proto.Unmarshal(buf, pbb)
if err != nil {
// NOTE: The existence of meta should imply the existence of the
// block. So, make sure meta is only saved after blocks are saved.
panic(fmt.Sprintf("Error reading block: %v", err))
}
block, err := types.BlockFromProto(pbb)
if err != nil {
panic(fmt.Errorf("error from proto block: %w", err))
}
return block
}
// LoadBlockByHash returns the block with the given hash.
// If no block is found for that hash, it returns nil.
// Panics if it fails to parse height associated with the given hash.
func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block {
bz, err := bs.db.Get(calcBlockHashKey(hash))
if err != nil {
panic(err)
}
if len(bz) == 0 {
return nil
}
s := string(bz)
height, err := strconv.ParseInt(s, 10, 64)
if err != nil {
panic(fmt.Sprintf("failed to extract height from %s: %v", s, err))
}
return bs.LoadBlock(height)
}
// LoadBlockPart returns the Part at the given index
// from the block at the given height.
// If no part is found for the given height and index, it returns nil.
func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part {
pbpart := new(cmtproto.Part)
bz, err := bs.db.Get(calcBlockPartKey(height, index))
if err != nil {
panic(err)
}
if len(bz) == 0 {
return nil
}
err = proto.Unmarshal(bz, pbpart)
if err != nil {
panic(fmt.Errorf("unmarshal to cmtproto.Part failed: %w", err))
}
part, err := types.PartFromProto(pbpart)
if err != nil {
panic(fmt.Sprintf("Error reading block part: %v", err))
}
return part
}
// LoadBlockMeta returns the BlockMeta for the given height.
// If no block is found for the given height, it returns nil.
func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
pbbm := new(cmtproto.BlockMeta)
bz, err := bs.db.Get(calcBlockMetaKey(height))
if err != nil {
panic(err)
}
if len(bz) == 0 {
return nil
}
err = proto.Unmarshal(bz, pbbm)
if err != nil {
panic(fmt.Errorf("unmarshal to cmtproto.BlockMeta: %w", err))
}
blockMeta, err := types.BlockMetaFromTrustedProto(pbbm)
if err != nil {
panic(fmt.Errorf("error from proto blockMeta: %w", err))
}
return blockMeta
}
// LoadBlockMetaByHash returns the blockmeta who's header corresponds to the given
// hash. If none is found, returns nil.
func (bs *BlockStore) LoadBlockMetaByHash(hash []byte) *types.BlockMeta {
bz, err := bs.db.Get(calcBlockHashKey(hash))
if err != nil {
panic(err)
}
if len(bz) == 0 {
return nil
}
s := string(bz)
height, err := strconv.ParseInt(s, 10, 64)
if err != nil {
panic(fmt.Sprintf("failed to extract height from %s: %v", s, err))
}
return bs.LoadBlockMeta(height)
}
// LoadBlockCommit returns the Commit for the given height.
// This commit consists of the +2/3 and other Precommit-votes for block at `height`,
// and it comes from the block.LastCommit for `height+1`.
// If no commit is found for the given height, it returns nil.
func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit {
comm, ok := bs.blockCommitCache.Get(height)
if ok {
return comm.Clone()
}
pbc := new(cmtproto.Commit)
bz, err := bs.db.Get(calcBlockCommitKey(height))
if err != nil {
panic(err)
}
if len(bz) == 0 {
return nil
}
err = proto.Unmarshal(bz, pbc)
if err != nil {
panic(fmt.Errorf("error reading block commit: %w", err))
}
commit, err := types.CommitFromProto(pbc)
if err != nil {
panic(fmt.Errorf("converting commit to proto: %w", err))
}
bs.blockCommitCache.Add(height, commit)
return commit.Clone()
}
// LoadExtendedCommit returns the ExtendedCommit for the given height.
// The extended commit is not guaranteed to contain the same +2/3 precommits data
// as the commit in the block.
func (bs *BlockStore) LoadBlockExtendedCommit(height int64) *types.ExtendedCommit {
comm, ok := bs.blockExtendedCommitCache.Get(height)
if ok {
return comm.Clone()
}
pbec := new(cmtproto.ExtendedCommit)
bz, err := bs.db.Get(calcExtCommitKey(height))
if err != nil {
panic(fmt.Errorf("fetching extended commit: %w", err))
}
if len(bz) == 0 {
return nil
}
err = proto.Unmarshal(bz, pbec)
if err != nil {
panic(fmt.Errorf("decoding extended commit: %w", err))
}
extCommit, err := types.ExtendedCommitFromProto(pbec)
if err != nil {
panic(fmt.Errorf("converting extended commit: %w", err))
}
bs.blockExtendedCommitCache.Add(height, extCommit)
return extCommit.Clone()
}
// LoadSeenCommit returns the locally seen Commit for the given height.
// This is useful when we've seen a commit, but there has not yet been
// a new block at `height + 1` that includes this commit in its block.LastCommit.
func (bs *BlockStore) LoadSeenCommit(height int64) *types.Commit {
comm, ok := bs.seenCommitCache.Get(height)
if ok {
return comm.Clone()
}
pbc := new(cmtproto.Commit)
bz, err := bs.db.Get(calcSeenCommitKey(height))
if err != nil {
panic(err)
}
if len(bz) == 0 {
return nil
}
err = proto.Unmarshal(bz, pbc)
if err != nil {
panic(fmt.Sprintf("error reading block seen commit: %v", err))
}
commit, err := types.CommitFromProto(pbc)
if err != nil {
panic(fmt.Errorf("converting seen commit: %w", err))
}
bs.seenCommitCache.Add(height, commit)
return commit.Clone()
}
// PruneBlocks removes block up to (but not including) a height. It returns number of blocks pruned and the evidence retain height - the height at which data needed to prove evidence must not be removed.
func (bs *BlockStore) PruneBlocks(height int64, state sm.State) (uint64, int64, error) {
if height <= 0 {
return 0, -1, fmt.Errorf("height must be greater than 0")
}
bs.mtx.RLock()
if height > bs.height {
bs.mtx.RUnlock()
return 0, -1, fmt.Errorf("cannot prune beyond the latest height %v", bs.height)
}
base := bs.base
bs.mtx.RUnlock()
if height < base {
return 0, -1, fmt.Errorf("cannot prune to height %v, it is lower than base height %v",
height, base)
}
pruned := uint64(0)
batch := bs.db.NewBatch()
defer batch.Close()
flush := func(batch dbm.Batch, base int64) error {
// We can't trust batches to be atomic, so update base first to make sure noone
// tries to access missing blocks.
bs.mtx.Lock()
defer batch.Close()
defer bs.mtx.Unlock()
bs.base = base
return bs.saveStateAndWriteDB(batch, "failed to prune")
}
evidencePoint := height
for h := base; h < height; h++ {
meta := bs.LoadBlockMeta(h)
if meta == nil { // assume already deleted
continue
}
// This logic is in place to protect data that proves malicious behavior.
// If the height is within the evidence age, we continue to persist the header and commit data.
if evidencePoint == height && !evidence.IsEvidenceExpired(state.LastBlockHeight, state.LastBlockTime, h, meta.Header.Time, state.ConsensusParams.Evidence) {
evidencePoint = h
}
// if height is beyond the evidence point we dont delete the header
if h < evidencePoint {
if err := batch.Delete(calcBlockMetaKey(h)); err != nil {
return 0, -1, err
}
}
if err := batch.Delete(calcBlockHashKey(meta.BlockID.Hash)); err != nil {
return 0, -1, err
}
// if height is beyond the evidence point we dont delete the commit data
if h < evidencePoint {
if err := batch.Delete(calcBlockCommitKey(h)); err != nil {
return 0, -1, err
}
}
if err := batch.Delete(calcSeenCommitKey(h)); err != nil {
return 0, -1, err
}
for p := 0; p < int(meta.BlockID.PartSetHeader.Total); p++ {
if err := batch.Delete(calcBlockPartKey(h, p)); err != nil {
return 0, -1, err
}
}
pruned++
// flush every 1000 blocks to avoid batches becoming too large
if pruned%1000 == 0 && pruned > 0 {
err := flush(batch, h)
if err != nil {
return 0, -1, err
}
batch = bs.db.NewBatch()
defer batch.Close()
}
}
err := flush(batch, height)
if err != nil {
return 0, -1, err
}
return pruned, evidencePoint, nil
}
// SaveBlock persists the given block, blockParts, and seenCommit to the underlying db.
// blockParts: Must be parts of the block
// seenCommit: The +2/3 precommits that were seen which committed at height.
//
// If all the nodes restart after committing a block,
// we need this to reload the precommits to catch-up nodes to the
// most recent height. Otherwise they'd stall at H-1.
func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
if block == nil {
panic("BlockStore can only save a non-nil block")
}
batch := bs.db.NewBatch()
defer batch.Close()
if err := bs.saveBlockToBatch(block, blockParts, seenCommit, batch); err != nil {
panic(err)
}
bs.mtx.Lock()
defer bs.mtx.Unlock()
bs.height = block.Height
if bs.base == 0 {
bs.base = block.Height
}
// Save new BlockStoreState descriptor. This also flushes the database.
err := bs.saveStateAndWriteDB(batch, "failed to save block")
if err != nil {
panic(err)
}
}
// SaveBlockWithExtendedCommit persists the given block, blockParts, and
// seenExtendedCommit to the underlying db. seenExtendedCommit is stored under
// two keys in the database: as the seenCommit and as the ExtendedCommit data for the
// height. This allows the vote extension data to be persisted for all blocks
// that are saved.
func (bs *BlockStore) SaveBlockWithExtendedCommit(block *types.Block, blockParts *types.PartSet, seenExtendedCommit *types.ExtendedCommit) {
if block == nil {
panic("BlockStore can only save a non-nil block")
}
if err := seenExtendedCommit.EnsureExtensions(true); err != nil {
panic(fmt.Errorf("problems saving block with extensions: %w", err))
}
batch := bs.db.NewBatch()
defer batch.Close()
if err := bs.saveBlockToBatch(block, blockParts, seenExtendedCommit.ToCommit(), batch); err != nil {
panic(err)
}
height := block.Height
pbec := seenExtendedCommit.ToProto()
extCommitBytes := mustEncode(pbec)
if err := batch.Set(calcExtCommitKey(height), extCommitBytes); err != nil {
panic(err)
}
bs.mtx.Lock()
defer bs.mtx.Unlock()
bs.height = height
if bs.base == 0 {
bs.base = height
}
// Save new BlockStoreState descriptor. This also flushes the database.
err := bs.saveStateAndWriteDB(batch, "failed to save block with extended commit")
if err != nil {
panic(err)
}
}
func (bs *BlockStore) saveBlockToBatch(
block *types.Block,
blockParts *types.PartSet,
seenCommit *types.Commit,
batch dbm.Batch,
) error {
if block == nil {
panic("BlockStore can only save a non-nil block")
}
height := block.Height
hash := block.Hash()
if g, w := height, bs.Height()+1; bs.Base() > 0 && g != w {
return fmt.Errorf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g)
}
if !blockParts.IsComplete() {
return errors.New("BlockStore can only save complete block part sets")
}
if height != seenCommit.Height {
return fmt.Errorf("BlockStore cannot save seen commit of a different height (block: %d, commit: %d)", height, seenCommit.Height)
}
// If the block is small, batch save the block parts. Otherwise, save the
// parts individually.
saveBlockPartsToBatch := blockParts.Count() <= maxBlockPartsToBatch
// Save block parts. This must be done before the block meta, since callers
// typically load the block meta first as an indication that the block exists
// and then go on to load block parts - we must make sure the block is
// complete as soon as the block meta is written.
for i := 0; i < int(blockParts.Total()); i++ {
part := blockParts.GetPart(i)
bs.saveBlockPart(height, i, part, batch, saveBlockPartsToBatch)
}
// Save block meta
blockMeta := types.NewBlockMeta(block, blockParts)
pbm := blockMeta.ToProto()
if pbm == nil {
return errors.New("nil blockmeta")
}
metaBytes := mustEncode(pbm)
if err := batch.Set(calcBlockMetaKey(height), metaBytes); err != nil {
return err
}
if err := batch.Set(calcBlockHashKey(hash), []byte(fmt.Sprintf("%d", height))); err != nil {
return err
}
// Save block commit (duplicate and separate from the Block)
pbc := block.LastCommit.ToProto()
blockCommitBytes := mustEncode(pbc)
if err := batch.Set(calcBlockCommitKey(height-1), blockCommitBytes); err != nil {
return err
}
// Save seen commit (seen +2/3 precommits for block)
// NOTE: we can delete this at a later height
pbsc := seenCommit.ToProto()
seenCommitBytes := mustEncode(pbsc)
if err := batch.Set(calcSeenCommitKey(height), seenCommitBytes); err != nil {
return err
}
return nil
}
func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part, batch dbm.Batch, saveBlockPartsToBatch bool) {
pbp, err := part.ToProto()
if err != nil {
panic(fmt.Errorf("unable to make part into proto: %w", err))
}
partBytes := mustEncode(pbp)
if saveBlockPartsToBatch {
err = batch.Set(calcBlockPartKey(height, index), partBytes)
} else {
err = bs.db.Set(calcBlockPartKey(height, index), partBytes)
}
if err != nil {
panic(err)
}
}
// Contract: the caller MUST have, at least, a read lock on `bs`.
func (bs *BlockStore) saveStateAndWriteDB(batch dbm.Batch, errMsg string) error {
bss := cmtstore.BlockStoreState{
Base: bs.base,
Height: bs.height,
}
SaveBlockStoreStateBatch(&bss, batch)
err := batch.WriteSync()
if err != nil {
return fmt.Errorf("error writing batch to DB %q: (base %d, height %d): %w",
errMsg, bs.base, bs.height, err)
}
return nil
}
// SaveSeenCommit saves a seen commit, used by e.g. the state sync reactor when bootstrapping node.
func (bs *BlockStore) SaveSeenCommit(height int64, seenCommit *types.Commit) error {
pbc := seenCommit.ToProto()
seenCommitBytes, err := proto.Marshal(pbc)
if err != nil {
return fmt.Errorf("unable to marshal commit: %w", err)
}
return bs.db.Set(calcSeenCommitKey(height), seenCommitBytes)
}
func (bs *BlockStore) Close() error {
return bs.db.Close()
}
//-----------------------------------------------------------------------------
func calcBlockMetaKey(height int64) []byte {
return []byte(fmt.Sprintf("H:%v", height))
}
func calcBlockPartKey(height int64, partIndex int) []byte {
return []byte(fmt.Sprintf("P:%v:%v", height, partIndex))
}
func calcBlockCommitKey(height int64) []byte {
return []byte(fmt.Sprintf("C:%v", height))
}
func calcSeenCommitKey(height int64) []byte {
return []byte(fmt.Sprintf("SC:%v", height))
}
func calcExtCommitKey(height int64) []byte {
return []byte(fmt.Sprintf("EC:%v", height))
}
func calcBlockHashKey(hash []byte) []byte {
return []byte(fmt.Sprintf("BH:%x", hash))
}
//-----------------------------------------------------------------------------
var blockStoreKey = []byte("blockStore")
// SaveBlockStoreState persists the blockStore state to the database.
// deprecated: still present in this version for API compatibility
func SaveBlockStoreState(bsj *cmtstore.BlockStoreState, db dbm.DB) {
saveBlockStoreStateBatchInternal(bsj, db, nil)
}
// SaveBlockStoreStateBatch persists the blockStore state to the database.
// It uses the DB batch passed as parameter
func SaveBlockStoreStateBatch(bsj *cmtstore.BlockStoreState, batch dbm.Batch) {
saveBlockStoreStateBatchInternal(bsj, nil, batch)
}
func saveBlockStoreStateBatchInternal(bsj *cmtstore.BlockStoreState, db dbm.DB, batch dbm.Batch) {
bytes, err := proto.Marshal(bsj)
if err != nil {
panic(fmt.Sprintf("could not marshal state bytes: %v", err))
}
if batch != nil {
err = batch.Set(blockStoreKey, bytes)
} else {
if db == nil {
panic("both 'db' and 'batch' cannot be nil")
}
err = db.SetSync(blockStoreKey, bytes)
}
if err != nil {
panic(err)
}
}
// LoadBlockStoreState returns the BlockStoreState as loaded from disk.
// If no BlockStoreState was previously persisted, it returns the zero value.
func LoadBlockStoreState(db dbm.DB) cmtstore.BlockStoreState {
bytes, err := db.Get(blockStoreKey)
if err != nil {
panic(err)
}
if len(bytes) == 0 {
return cmtstore.BlockStoreState{
Base: 0,
Height: 0,
}
}
var bsj cmtstore.BlockStoreState
if err := proto.Unmarshal(bytes, &bsj); err != nil {
panic(fmt.Sprintf("Could not unmarshal bytes: %X", bytes))
}
// Backwards compatibility with persisted data from before Base existed.
if bsj.Height > 0 && bsj.Base == 0 {
bsj.Base = 1
}
return bsj
}
// mustEncode proto encodes a proto.message and panics if fails
func mustEncode(pb proto.Message) []byte {
bz, err := proto.Marshal(pb)
if err != nil {
panic(fmt.Errorf("unable to marshal: %w", err))
}
return bz
}
//-----------------------------------------------------------------------------
// DeleteLatestBlock removes the block pointed to by height,
// lowering height by one.
func (bs *BlockStore) DeleteLatestBlock() error {
bs.mtx.RLock()
targetHeight := bs.height
bs.mtx.RUnlock()
batch := bs.db.NewBatch()
defer batch.Close()
// delete what we can, skipping what's already missing, to ensure partial
// blocks get deleted fully.
if meta := bs.LoadBlockMeta(targetHeight); meta != nil {
if err := batch.Delete(calcBlockHashKey(meta.BlockID.Hash)); err != nil {
return err
}
for p := 0; p < int(meta.BlockID.PartSetHeader.Total); p++ {
if err := batch.Delete(calcBlockPartKey(targetHeight, p)); err != nil {
return err
}
}
}
if err := batch.Delete(calcBlockCommitKey(targetHeight)); err != nil {
return err
}
if err := batch.Delete(calcSeenCommitKey(targetHeight)); err != nil {
return err
}
// delete last, so as to not leave keys built on meta.BlockID dangling
if err := batch.Delete(calcBlockMetaKey(targetHeight)); err != nil {
return err
}
bs.mtx.Lock()
defer bs.mtx.Unlock()
bs.height = targetHeight - 1
return bs.saveStateAndWriteDB(batch, "failed to delete the latest block")
}
package types
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"github.com/cometbft/cometbft/crypto/merkle"
"github.com/cometbft/cometbft/crypto/tmhash"
cmtbytes "github.com/cometbft/cometbft/libs/bytes"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
)
// TxKeySize is the size of the transaction key index
const TxKeySize = sha256.Size
type (
// Tx is an arbitrary byte array.
// NOTE: Tx has no types at this level, so when wire encoded it's just length-prefixed.
// Might we want types here ?
Tx []byte
// TxKey is the fixed length array key used as an index.
TxKey [TxKeySize]byte
)
// Hash computes the TMHASH hash of the wire encoded transaction.
func (tx Tx) Hash() []byte {
return tmhash.Sum(tx)
}
func (tx Tx) Key() TxKey {
return sha256.Sum256(tx)
}
// String returns the hex-encoded transaction as a string.
func (tx Tx) String() string {
return fmt.Sprintf("Tx{%X}", []byte(tx))
}
// Txs is a slice of Tx.
type Txs []Tx
// Hash returns the Merkle root hash of the transaction hashes.
// i.e. the leaves of the tree are the hashes of the txs.
func (txs Txs) Hash() []byte {
hl := txs.hashList()
return merkle.HashFromByteSlices(hl)
}
// Index returns the index of this transaction in the list, or -1 if not found
func (txs Txs) Index(tx Tx) int {
for i := range txs {
if bytes.Equal(txs[i], tx) {
return i
}
}
return -1
}
// IndexByHash returns the index of this transaction hash in the list, or -1 if not found
func (txs Txs) IndexByHash(hash []byte) int {
for i := range txs {
if bytes.Equal(txs[i].Hash(), hash) {
return i
}
}
return -1
}
func (txs Txs) Proof(i int) TxProof {
hl := txs.hashList()
root, proofs := merkle.ProofsFromByteSlices(hl)
return TxProof{
RootHash: root,
Data: txs[i],
Proof: *proofs[i],
}
}
func (txs Txs) hashList() [][]byte {
hl := make([][]byte, len(txs))
for i := 0; i < len(txs); i++ {
hl[i] = txs[i].Hash()
}
return hl
}
// Txs is a slice of transactions. Sorting a Txs value orders the transactions
// lexicographically.
func (txs Txs) Len() int { return len(txs) }
func (txs Txs) Swap(i, j int) { txs[i], txs[j] = txs[j], txs[i] }
func (txs Txs) Less(i, j int) bool {
return bytes.Compare(txs[i], txs[j]) == -1
}
func ToTxs(txl [][]byte) Txs {
txs := make([]Tx, 0, len(txl))
for _, tx := range txl {
txs = append(txs, tx)
}
return txs
}
func (txs Txs) Validate(maxSizeBytes int64) error {
var size int64
for _, tx := range txs {
size += ComputeProtoSizeForTxs([]Tx{tx})
if size > maxSizeBytes {
return fmt.Errorf("transaction data size exceeds maximum %d", maxSizeBytes)
}
}
return nil
}
// ToSliceOfBytes converts a Txs to slice of byte slices.
func (txs Txs) ToSliceOfBytes() [][]byte {
txBzs := make([][]byte, len(txs))
for i := 0; i < len(txs); i++ {
txBzs[i] = txs[i]
}
return txBzs
}
// TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree.
type TxProof struct {
RootHash cmtbytes.HexBytes `json:"root_hash"`
Data Tx `json:"data"`
Proof merkle.Proof `json:"proof"`
}
// Leaf returns the hash(tx), which is the leaf in the merkle tree which this proof refers to.
func (tp TxProof) Leaf() []byte {
return tp.Data.Hash()
}
// Validate verifies the proof. It returns nil if the RootHash matches the dataHash argument,
// and if the proof is internally consistent. Otherwise, it returns a sensible error.
func (tp TxProof) Validate(dataHash []byte) error {
if !bytes.Equal(dataHash, tp.RootHash) {
return errors.New("proof matches different data hash")
}
if tp.Proof.Index < 0 {
return errors.New("proof index cannot be negative")
}
if tp.Proof.Total <= 0 {
return errors.New("proof total must be positive")
}
valid := tp.Proof.Verify(tp.RootHash, tp.Leaf())
if valid != nil {
return errors.New("proof is not internally consistent")
}
return nil
}
func (tp TxProof) ToProto() cmtproto.TxProof {
pbProof := tp.Proof.ToProto()
pbtp := cmtproto.TxProof{
RootHash: tp.RootHash,
Data: tp.Data,
Proof: pbProof,
}
return pbtp
}
func TxProofFromProto(pb cmtproto.TxProof) (TxProof, error) {
pbProof, err := merkle.ProofFromProto(pb.Proof)
if err != nil {
return TxProof{}, err
}
pbtp := TxProof{
RootHash: pb.RootHash,
Data: pb.Data,
Proof: *pbProof,
}
return pbtp, nil
}
// ComputeProtoSizeForTxs wraps the transactions in cmtproto.Data{} and calculates the size.
// https://developers.google.com/protocol-buffers/docs/encoding
func ComputeProtoSizeForTxs(txs []Tx) int64 {
data := Data{Txs: txs}
pdData := data.ToProto()
return int64(pdData.Size())
}
package db
import (
"fmt"
"path/filepath"
"github.com/spf13/cast"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/errors"
"github.com/syndtr/goleveldb/leveldb/filter"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/util"
)
func init() {
dbCreator := func(name string, dir string, opts Options) (DB, error) {
return NewGoLevelDB(name, dir, opts)
}
registerDBCreator(GoLevelDBBackend, dbCreator, false)
}
type GoLevelDB struct {
db *leveldb.DB
}
var _ DB = (*GoLevelDB)(nil)
func NewGoLevelDB(name string, dir string, opts Options) (*GoLevelDB, error) {
defaultOpts := &opt.Options{
Filter: filter.NewBloomFilter(10), // by default, goleveldb doesn't use a bloom filter.
}
if opts != nil {
files := cast.ToInt(opts.Get("maxopenfiles"))
if files > 0 {
defaultOpts.OpenFilesCacheCapacity = files
}
}
return NewGoLevelDBWithOpts(name, dir, defaultOpts)
}
func NewGoLevelDBWithOpts(name string, dir string, o *opt.Options) (*GoLevelDB, error) {
dbPath := filepath.Join(dir, name+DBFileSuffix)
db, err := leveldb.OpenFile(dbPath, o)
if err != nil {
return nil, err
}
database := &GoLevelDB{
db: db,
}
return database, nil
}
// Get implements DB.
func (db *GoLevelDB) Get(key []byte) ([]byte, error) {
if len(key) == 0 {
return nil, errKeyEmpty
}
res, err := db.db.Get(key, nil)
if err != nil {
if err == errors.ErrNotFound {
return nil, nil
}
return nil, err
}
return res, nil
}
// Has implements DB.
func (db *GoLevelDB) Has(key []byte) (bool, error) {
bytes, err := db.Get(key)
if err != nil {
return false, err
}
return bytes != nil, nil
}
// Set implements DB.
func (db *GoLevelDB) Set(key []byte, value []byte) error {
if len(key) == 0 {
return errKeyEmpty
}
if value == nil {
return errValueNil
}
if err := db.db.Put(key, value, nil); err != nil {
return err
}
return nil
}
// SetSync implements DB.
func (db *GoLevelDB) SetSync(key []byte, value []byte) error {
if len(key) == 0 {
return errKeyEmpty
}
if value == nil {
return errValueNil
}
if err := db.db.Put(key, value, &opt.WriteOptions{Sync: true}); err != nil {
return err
}
return nil
}
// Delete implements DB.
func (db *GoLevelDB) Delete(key []byte) error {
if len(key) == 0 {
return errKeyEmpty
}
if err := db.db.Delete(key, nil); err != nil {
return err
}
return nil
}
// DeleteSync implements DB.
func (db *GoLevelDB) DeleteSync(key []byte) error {
if len(key) == 0 {
return errKeyEmpty
}
err := db.db.Delete(key, &opt.WriteOptions{Sync: true})
if err != nil {
return err
}
return nil
}
func (db *GoLevelDB) DB() *leveldb.DB {
return db.db
}
// Close implements DB.
func (db *GoLevelDB) Close() error {
if err := db.db.Close(); err != nil {
return err
}
return nil
}
// Print implements DB.
func (db *GoLevelDB) Print() error {
str, err := db.db.GetProperty("leveldb.stats")
if err != nil {
return err
}
fmt.Printf("%v\n", str)
itr := db.db.NewIterator(nil, nil)
for itr.Next() {
key := itr.Key()
value := itr.Value()
fmt.Printf("[%X]:\t[%X]\n", key, value)
}
return nil
}
// Stats implements DB.
func (db *GoLevelDB) Stats() map[string]string {
keys := []string{
"leveldb.num-files-at-level{n}",
"leveldb.stats",
"leveldb.sstables",
"leveldb.blockpool",
"leveldb.cachedblock",
"leveldb.openedtables",
"leveldb.alivesnaps",
"leveldb.aliveiters",
}
stats := make(map[string]string)
for _, key := range keys {
str, err := db.db.GetProperty(key)
if err == nil {
stats[key] = str
}
}
return stats
}
func (db *GoLevelDB) ForceCompact(start, limit []byte) error {
return db.db.CompactRange(util.Range{Start: start, Limit: limit})
}
// NewBatch implements DB.
func (db *GoLevelDB) NewBatch() Batch {
return newGoLevelDBBatch(db)
}
// NewBatchWithSize implements DB.
func (db *GoLevelDB) NewBatchWithSize(size int) Batch {
return newGoLevelDBBatchWithSize(db, size)
}
// Iterator implements DB.
func (db *GoLevelDB) Iterator(start, end []byte) (Iterator, error) {
if (start != nil && len(start) == 0) || (end != nil && len(end) == 0) {
return nil, errKeyEmpty
}
itr := db.db.NewIterator(&util.Range{Start: start, Limit: end}, nil)
return newGoLevelDBIterator(itr, start, end, false), nil
}
// ReverseIterator implements DB.
func (db *GoLevelDB) ReverseIterator(start, end []byte) (Iterator, error) {
if (start != nil && len(start) == 0) || (end != nil && len(end) == 0) {
return nil, errKeyEmpty
}
itr := db.db.NewIterator(&util.Range{Start: start, Limit: end}, nil)
return newGoLevelDBIterator(itr, start, end, true), nil
}
package baseapp
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/InjectiveLabs/metrics"
"github.com/cockroachdb/errors"
abci "github.com/cometbft/cometbft/abci/types"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
"github.com/cosmos/gogoproto/proto"
"google.golang.org/grpc/codes"
grpcstatus "google.golang.org/grpc/status"
coreheader "cosmossdk.io/core/header"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/store/rootmulti"
snapshottypes "cosmossdk.io/store/snapshots/types"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
// Supported ABCI Query prefixes and paths
const (
QueryPathApp = "app"
QueryPathCustom = "custom"
QueryPathP2P = "p2p"
QueryPathStore = "store"
QueryPathBroadcastTx = "/cosmos.tx.v1beta1.Service/BroadcastTx"
)
func (app *BaseApp) InitChain(req *abci.RequestInitChain) (*abci.ResponseInitChain, error) {
if req.ChainId != app.chainID {
return nil, fmt.Errorf("invalid chain-id on InitChain; expected: %s, got: %s", app.chainID, req.ChainId)
}
// On a new chain, we consider the init chain block height as 0, even though
// req.InitialHeight is 1 by default.
initHeader := cmtproto.Header{ChainID: req.ChainId, Time: req.Time}
app.logger.Info("InitChain", "initialHeight", req.InitialHeight, "chainID", req.ChainId)
// Set the initial height, which will be used to determine if we are proposing
// or processing the first block or not.
app.initialHeight = req.InitialHeight
if app.initialHeight == 0 { // If initial height is 0, set it to 1
app.initialHeight = 1
}
// if req.InitialHeight is > 1, then we set the initial version on all stores
if req.InitialHeight > 1 {
initHeader.Height = req.InitialHeight
if err := app.cms.SetInitialVersion(req.InitialHeight); err != nil {
return nil, err
}
}
// initialize states with a correct header
app.setState(execModeFinalize, initHeader)
app.setState(execModeCheck, initHeader)
// Store the consensus params in the BaseApp's param store. Note, this must be
// done after the finalizeBlockState and context have been set as it's persisted
// to state.
if req.ConsensusParams != nil {
err := app.StoreConsensusParams(app.finalizeBlockState.Context(), *req.ConsensusParams)
if err != nil {
return nil, err
}
}
defer func() {
// InitChain represents the state of the application BEFORE the first block,
// i.e. the genesis block. This means that when processing the app's InitChain
// handler, the block height is zero by default. However, after Commit is called
// the height needs to reflect the true block height.
initHeader.Height = req.InitialHeight
app.checkState.SetContext(app.checkState.Context().WithBlockHeader(initHeader).
WithHeaderInfo(coreheader.Info{
ChainID: req.ChainId,
Height: req.InitialHeight,
Time: req.Time,
}))
app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().WithBlockHeader(initHeader).
WithHeaderInfo(coreheader.Info{
ChainID: req.ChainId,
Height: req.InitialHeight,
Time: req.Time,
}))
}()
if app.initChainer == nil {
return &abci.ResponseInitChain{}, nil
}
// add block gas meter for any genesis transactions (allow infinite gas)
app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().WithBlockGasMeter(storetypes.NewInfiniteGasMeter()))
res, err := app.initChainer(app.finalizeBlockState.Context(), req)
if err != nil {
return nil, err
}
if len(req.Validators) > 0 {
if len(req.Validators) != len(res.Validators) {
return nil, fmt.Errorf(
"len(RequestInitChain.Validators) != len(GenesisValidators) (%d != %d)",
len(req.Validators), len(res.Validators),
)
}
sort.Sort(abci.ValidatorUpdates(req.Validators))
sort.Sort(abci.ValidatorUpdates(res.Validators))
for i := range res.Validators {
if !proto.Equal(&res.Validators[i], &req.Validators[i]) {
return nil, fmt.Errorf("genesisValidators[%d] != req.Validators[%d] ", i, i)
}
}
}
// NOTE: We don't commit, but FinalizeBlock for block InitialHeight starts from
// this FinalizeBlockState.
return &abci.ResponseInitChain{
ConsensusParams: res.ConsensusParams,
Validators: res.Validators,
AppHash: app.LastCommitID().Hash,
}, nil
}
func (app *BaseApp) Info(_ *abci.RequestInfo) (*abci.ResponseInfo, error) {
lastCommitID := app.cms.LastCommitID()
return &abci.ResponseInfo{
Data: app.name,
Version: app.version,
AppVersion: app.appVersion,
LastBlockHeight: lastCommitID.Version,
LastBlockAppHash: lastCommitID.Hash,
}, nil
}
// Query implements the ABCI interface. It delegates to CommitMultiStore if it
// implements Queryable.
func (app *BaseApp) Query(_ context.Context, req *abci.RequestQuery) (resp *abci.ResponseQuery, err error) {
// add panic recovery for all queries
//
// Ref: https://github.com/cosmos/cosmos-sdk/pull/8039
defer func() {
if r := recover(); r != nil {
resp = sdkerrors.QueryResult(errorsmod.Wrapf(sdkerrors.ErrPanic, "%v", r), app.trace)
}
}()
// when a client did not provide a query height, manually inject the latest
if req.Height == 0 {
req.Height = app.LastBlockHeight()
}
telemetry.IncrCounter(1, "query", "count")
telemetry.IncrCounter(1, "query", req.Path)
defer telemetry.MeasureSince(telemetry.Now(), req.Path)
if req.Path == QueryPathBroadcastTx {
return sdkerrors.QueryResult(errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "can't route a broadcast tx message"), app.trace), nil
}
// handle gRPC routes first rather than calling splitPath because '/' characters
// are used as part of gRPC paths
if grpcHandler := app.grpcQueryRouter.Route(req.Path); grpcHandler != nil {
return app.handleQueryGRPC(grpcHandler, req), nil
}
path := SplitABCIQueryPath(req.Path)
if len(path) == 0 {
return sdkerrors.QueryResult(errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "no query path provided"), app.trace), nil
}
switch path[0] {
case QueryPathApp:
// "/app" prefix for special application queries
resp = handleQueryApp(app, path, req)
case QueryPathStore:
resp = handleQueryStore(app, path, *req)
case QueryPathP2P:
resp = handleQueryP2P(app, path)
default:
resp = sdkerrors.QueryResult(errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "unknown query path"), app.trace)
}
return resp, nil
}
// ListSnapshots implements the ABCI interface. It delegates to app.snapshotManager if set.
func (app *BaseApp) ListSnapshots(req *abci.RequestListSnapshots) (*abci.ResponseListSnapshots, error) {
resp := &abci.ResponseListSnapshots{Snapshots: []*abci.Snapshot{}}
if app.snapshotManager == nil {
return resp, nil
}
snapshots, err := app.snapshotManager.List()
if err != nil {
app.logger.Error("failed to list snapshots", "err", err)
return nil, err
}
for _, snapshot := range snapshots {
abciSnapshot, err := snapshot.ToABCI()
if err != nil {
app.logger.Error("failed to convert ABCI snapshots", "err", err)
return nil, err
}
resp.Snapshots = append(resp.Snapshots, &abciSnapshot)
}
return resp, nil
}
// LoadSnapshotChunk implements the ABCI interface. It delegates to app.snapshotManager if set.
func (app *BaseApp) LoadSnapshotChunk(req *abci.RequestLoadSnapshotChunk) (*abci.ResponseLoadSnapshotChunk, error) {
if app.snapshotManager == nil {
return &abci.ResponseLoadSnapshotChunk{}, nil
}
chunk, err := app.snapshotManager.LoadChunk(req.Height, req.Format, req.Chunk)
if err != nil {
app.logger.Error(
"failed to load snapshot chunk",
"height", req.Height,
"format", req.Format,
"chunk", req.Chunk,
"err", err,
)
return nil, err
}
return &abci.ResponseLoadSnapshotChunk{Chunk: chunk}, nil
}
// OfferSnapshot implements the ABCI interface. It delegates to app.snapshotManager if set.
func (app *BaseApp) OfferSnapshot(req *abci.RequestOfferSnapshot) (*abci.ResponseOfferSnapshot, error) {
if app.snapshotManager == nil {
app.logger.Error("snapshot manager not configured")
return &abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ABORT}, nil
}
if req.Snapshot == nil {
app.logger.Error("received nil snapshot")
return &abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil
}
snapshot, err := snapshottypes.SnapshotFromABCI(req.Snapshot)
if err != nil {
app.logger.Error("failed to decode snapshot metadata", "err", err)
return &abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil
}
err = app.snapshotManager.Restore(snapshot)
switch {
case err == nil:
return &abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ACCEPT}, nil
case errors.Is(err, snapshottypes.ErrUnknownFormat):
return &abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT_FORMAT}, nil
case errors.Is(err, snapshottypes.ErrInvalidMetadata):
app.logger.Error(
"rejecting invalid snapshot",
"height", req.Snapshot.Height,
"format", req.Snapshot.Format,
"err", err,
)
return &abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil
default:
app.logger.Error(
"failed to restore snapshot",
"height", req.Snapshot.Height,
"format", req.Snapshot.Format,
"err", err,
)
// We currently don't support resetting the IAVL stores and retrying a
// different snapshot, so we ask CometBFT to abort all snapshot restoration.
return &abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ABORT}, nil
}
}
// ApplySnapshotChunk implements the ABCI interface. It delegates to app.snapshotManager if set.
func (app *BaseApp) ApplySnapshotChunk(req *abci.RequestApplySnapshotChunk) (*abci.ResponseApplySnapshotChunk, error) {
if app.snapshotManager == nil {
app.logger.Error("snapshot manager not configured")
return &abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ABORT}, nil
}
_, err := app.snapshotManager.RestoreChunk(req.Chunk)
switch {
case err == nil:
return &abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil
case errors.Is(err, snapshottypes.ErrChunkHashMismatch):
app.logger.Error(
"chunk checksum mismatch; rejecting sender and requesting refetch",
"chunk", req.Index,
"sender", req.Sender,
"err", err,
)
return &abci.ResponseApplySnapshotChunk{
Result: abci.ResponseApplySnapshotChunk_RETRY,
RefetchChunks: []uint32{req.Index},
RejectSenders: []string{req.Sender},
}, nil
default:
app.logger.Error("failed to restore snapshot", "err", err)
return &abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ABORT}, nil
}
}
// CheckTx implements the ABCI interface and executes a tx in CheckTx mode. In
// CheckTx mode, messages are not executed. This means messages are only validated
// and only the AnteHandler is executed. State is persisted to the BaseApp's
// internal CheckTx state if the AnteHandler passes. Otherwise, the ResponseCheckTx
// will contain relevant error information. Regardless of tx execution outcome,
// the ResponseCheckTx will contain relevant gas execution context.
func (app *BaseApp) CheckTx(req *abci.RequestCheckTx) (*abci.ResponseCheckTx, error) {
var mode execMode
switch {
case req.Type == abci.CheckTxType_New:
mode = execModeCheck
case req.Type == abci.CheckTxType_Recheck:
mode = execModeReCheck
default:
return nil, fmt.Errorf("unknown RequestCheckTx type: %s", req.Type)
}
gInfo, result, anteEvents, err := app.runTx(mode, req.Tx)
if err != nil {
return sdkerrors.ResponseCheckTxWithEvents(err, gInfo.GasWanted, gInfo.GasUsed, anteEvents, app.trace), nil
}
return &abci.ResponseCheckTx{
GasWanted: int64(gInfo.GasWanted), // TODO: Should type accept unsigned ints?
GasUsed: int64(gInfo.GasUsed), // TODO: Should type accept unsigned ints?
Log: result.Log,
Data: result.Data,
Events: sdk.MarkEventsToIndex(result.Events, app.indexEvents),
}, nil
}
// PrepareProposal implements the PrepareProposal ABCI method and returns a
// ResponsePrepareProposal object to the client. The PrepareProposal method is
// responsible for allowing the block proposer to perform application-dependent
// work in a block before proposing it.
//
// Transactions can be modified, removed, or added by the application. Since the
// application maintains its own local mempool, it will ignore the transactions
// provided to it in RequestPrepareProposal. Instead, it will determine which
// transactions to return based on the mempool's semantics and the MaxTxBytes
// provided by the client's request.
//
// Ref: https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-060-abci-1.0.md
// Ref: https://github.com/cometbft/cometbft/blob/main/spec/abci/abci%2B%2B_basic_concepts.md
func (app *BaseApp) PrepareProposal(req *abci.RequestPrepareProposal) (resp *abci.ResponsePrepareProposal, err error) {
if app.prepareProposal == nil {
return nil, errors.New("PrepareProposal handler not set")
}
// Always reset state given that PrepareProposal can timeout and be called
// again in a subsequent round.
header := cmtproto.Header{
ChainID: app.chainID,
Height: req.Height,
Time: req.Time,
ProposerAddress: req.ProposerAddress,
NextValidatorsHash: req.NextValidatorsHash,
AppHash: app.LastCommitID().Hash,
}
app.setState(execModePrepareProposal, header)
// CometBFT must never call PrepareProposal with a height of 0.
//
// Ref: https://github.com/cometbft/cometbft/blob/059798a4f5b0c9f52aa8655fa619054a0154088c/spec/core/state.md?plain=1#L37-L38
if req.Height < 1 {
return nil, errors.New("PrepareProposal called with invalid height")
}
app.prepareProposalState.SetContext(app.getContextForProposal(app.prepareProposalState.Context(), req.Height).
WithVoteInfos(toVoteInfo(req.LocalLastCommit.Votes)). // this is a set of votes that are not finalized yet, wait for commit
WithBlockHeight(req.Height).
WithBlockTime(req.Time).
WithProposer(req.ProposerAddress).
WithExecMode(sdk.ExecModePrepareProposal).
WithCometInfo(prepareProposalInfo{req}).
WithHeaderInfo(coreheader.Info{
ChainID: app.chainID,
Height: req.Height,
Time: req.Time,
}))
app.prepareProposalState.SetContext(app.prepareProposalState.Context().
WithConsensusParams(app.GetConsensusParams(app.prepareProposalState.Context())).
WithBlockGasMeter(app.getBlockGasMeter(app.prepareProposalState.Context())))
defer func() {
if err := recover(); err != nil {
app.logger.Error(
"panic recovered in PrepareProposal",
"height", req.Height,
"time", req.Time,
"panic", err,
)
resp = &abci.ResponsePrepareProposal{Txs: req.Txs}
}
}()
resp, err = app.prepareProposal(app.prepareProposalState.Context(), req)
if err != nil {
app.logger.Error("failed to prepare proposal", "height", req.Height, "time", req.Time, "err", err)
return &abci.ResponsePrepareProposal{Txs: req.Txs}, nil
}
return resp, nil
}
// ProcessProposal implements the ProcessProposal ABCI method and returns a
// ResponseProcessProposal object to the client. The ProcessProposal method is
// responsible for allowing execution of application-dependent work in a proposed
// block. Note, the application defines the exact implementation details of
// ProcessProposal. In general, the application must at the very least ensure
// that all transactions are valid. If all transactions are valid, then we inform
// CometBFT that the Status is ACCEPT. However, the application is also able
// to implement optimizations such as executing the entire proposed block
// immediately.
//
// If a panic is detected during execution of an application's ProcessProposal
// handler, it will be recovered and we will reject the proposal.
//
// Ref: https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-060-abci-1.0.md
// Ref: https://github.com/cometbft/cometbft/blob/main/spec/abci/abci%2B%2B_basic_concepts.md
func (app *BaseApp) ProcessProposal(req *abci.RequestProcessProposal) (resp *abci.ResponseProcessProposal, err error) {
if app.processProposal == nil {
return nil, errors.New("ProcessProposal handler not set")
}
// CometBFT must never call ProcessProposal with a height of 0.
// Ref: https://github.com/cometbft/cometbft/blob/059798a4f5b0c9f52aa8655fa619054a0154088c/spec/core/state.md?plain=1#L37-L38
if req.Height < 1 {
return nil, errors.New("ProcessProposal called with invalid height")
}
// Always reset state given that ProcessProposal can timeout and be called
// again in a subsequent round.
header := cmtproto.Header{
ChainID: app.chainID,
Height: req.Height,
Time: req.Time,
ProposerAddress: req.ProposerAddress,
NextValidatorsHash: req.NextValidatorsHash,
AppHash: app.LastCommitID().Hash,
}
app.setState(execModeProcessProposal, header)
// Since the application can get access to FinalizeBlock state and write to it,
// we must be sure to reset it in case ProcessProposal timeouts and is called
// again in a subsequent round. However, we only want to do this after we've
// processed the first block, as we want to avoid overwriting the finalizeState
// after state changes during InitChain.
if req.Height > app.initialHeight {
// abort any running OE
app.optimisticExec.Abort()
app.setState(execModeFinalize, header)
}
// metrics and trace
heightStr := strconv.Itoa(int(req.Height))
metricsCtx, doneFn := metrics.ReportFuncCallAndTimingSdkCtx(app.processProposalState.Context(), metrics.Tags{"svc": "app", "height": heightStr})
defer doneFn()
if app.traceFlightRecorder != nil {
defer app.traceFlightRecorder.StartRegion("process-proposal", heightStr)()
}
app.processProposalState.SetContext(metricsCtx)
app.processProposalState.SetContext(app.getContextForProposal(app.processProposalState.Context(), req.Height).
WithVoteInfos(req.ProposedLastCommit.Votes). // this is a set of votes that are not finalized yet, wait for commit
WithBlockHeight(req.Height).
WithBlockTime(req.Time).
WithHeaderHash(req.Hash).
WithProposer(req.ProposerAddress).
WithCometInfo(cometInfo{ProposerAddress: req.ProposerAddress, ValidatorsHash: req.NextValidatorsHash, Misbehavior: req.Misbehavior, LastCommit: req.ProposedLastCommit}).
WithExecMode(sdk.ExecModeProcessProposal).
WithHeaderInfo(coreheader.Info{
ChainID: app.chainID,
Height: req.Height,
Time: req.Time,
}))
app.processProposalState.SetContext(app.processProposalState.Context().
WithConsensusParams(app.GetConsensusParams(app.processProposalState.Context())).
WithBlockGasMeter(app.getBlockGasMeter(app.processProposalState.Context())))
defer func() {
if err := recover(); err != nil {
app.logger.Error(
"panic recovered in ProcessProposal",
"height", req.Height,
"time", req.Time,
"hash", fmt.Sprintf("%X", req.Hash),
"panic", err,
)
resp = &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}
}
}()
resp, err = app.processProposal(app.processProposalState.Context(), req)
if err != nil {
app.logger.Error("failed to process proposal", "height", req.Height, "time", req.Time, "hash", fmt.Sprintf("%X", req.Hash), "err", err)
return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil
}
// Only execute optimistic execution if the proposal is accepted, OE is
// enabled and the block height is greater than the initial height. During
// the first block we'll be carrying state from InitChain, so it would be
// impossible for us to easily revert.
// After the first block has been processed, the next blocks will get executed
// optimistically, so that when the ABCI client calls `FinalizeBlock` the app
// can have a response ready.
if resp.Status == abci.ResponseProcessProposal_ACCEPT &&
app.optimisticExec.Enabled() &&
req.Height > app.initialHeight {
app.optimisticExec.Execute(req)
}
return resp, nil
}
// ExtendVote implements the ExtendVote ABCI method and returns a ResponseExtendVote.
// It calls the application's ExtendVote handler which is responsible for performing
// application-specific business logic when sending a pre-commit for the NEXT
// block height. The extensions response may be non-deterministic but must always
// be returned, even if empty.
//
// Agreed upon vote extensions are made available to the proposer of the next
// height and are committed in the subsequent height, i.e. H+2. An error is
// returned if vote extensions are not enabled or if extendVote fails or panics.
func (app *BaseApp) ExtendVote(_ context.Context, req *abci.RequestExtendVote) (resp *abci.ResponseExtendVote, err error) {
// Always reset state given that ExtendVote and VerifyVoteExtension can timeout
// and be called again in a subsequent round.
var ctx sdk.Context
// If we're extending the vote for the initial height, we need to use the
// finalizeBlockState context, otherwise we don't get the uncommitted data
// from InitChain.
if req.Height == app.initialHeight {
ctx, _ = app.finalizeBlockState.Context().CacheContext()
} else {
emptyHeader := cmtproto.Header{ChainID: app.chainID, Height: req.Height}
ms := app.cms.CacheMultiStore()
ctx = sdk.NewContext(ms, emptyHeader, false, app.logger).WithStreamingManager(app.streamingManager)
}
if app.extendVote == nil {
return nil, errors.New("application ExtendVote handler not set")
}
// If vote extensions are not enabled, as a safety precaution, we return an
// error.
cp := app.GetConsensusParams(ctx)
// Note: In this case, we do want to extend vote if the height is equal or
// greater than VoteExtensionsEnableHeight. This defers from the check done
// in ValidateVoteExtensions and PrepareProposal in which we'll check for
// vote extensions on VoteExtensionsEnableHeight+1.
extsEnabled := cp.Abci != nil && req.Height >= cp.Abci.VoteExtensionsEnableHeight && cp.Abci.VoteExtensionsEnableHeight != 0
if !extsEnabled {
return nil, fmt.Errorf("vote extensions are not enabled; unexpected call to ExtendVote at height %d", req.Height)
}
ctx = ctx.
WithConsensusParams(cp).
WithBlockGasMeter(storetypes.NewInfiniteGasMeter()).
WithBlockHeight(req.Height).
WithHeaderHash(req.Hash).
WithExecMode(sdk.ExecModeVoteExtension).
WithHeaderInfo(coreheader.Info{
ChainID: app.chainID,
Height: req.Height,
Hash: req.Hash,
})
// add a deferred recover handler in case extendVote panics
defer func() {
if r := recover(); r != nil {
app.logger.Error(
"panic recovered in ExtendVote",
"height", req.Height,
"hash", fmt.Sprintf("%X", req.Hash),
"panic", err,
)
err = fmt.Errorf("recovered application panic in ExtendVote: %v", r)
}
}()
resp, err = app.extendVote(ctx, req)
if err != nil {
app.logger.Error("failed to extend vote", "height", req.Height, "hash", fmt.Sprintf("%X", req.Hash), "err", err)
return &abci.ResponseExtendVote{VoteExtension: []byte{}}, nil
}
return resp, err
}
// VerifyVoteExtension implements the VerifyVoteExtension ABCI method and returns
// a ResponseVerifyVoteExtension. It calls the applications' VerifyVoteExtension
// handler which is responsible for performing application-specific business
// logic in verifying a vote extension from another validator during the pre-commit
// phase. The response MUST be deterministic. An error is returned if vote
// extensions are not enabled or if verifyVoteExt fails or panics.
func (app *BaseApp) VerifyVoteExtension(req *abci.RequestVerifyVoteExtension) (resp *abci.ResponseVerifyVoteExtension, err error) {
if app.verifyVoteExt == nil {
return nil, errors.New("application VerifyVoteExtension handler not set")
}
var ctx sdk.Context
// If we're verifying the vote for the initial height, we need to use the
// finalizeBlockState context, otherwise we don't get the uncommitted data
// from InitChain.
if req.Height == app.initialHeight {
ctx, _ = app.finalizeBlockState.Context().CacheContext()
} else {
emptyHeader := cmtproto.Header{ChainID: app.chainID, Height: req.Height}
ms := app.cms.CacheMultiStore()
ctx = sdk.NewContext(ms, emptyHeader, false, app.logger).WithStreamingManager(app.streamingManager)
}
// If vote extensions are not enabled, as a safety precaution, we return an
// error.
cp := app.GetConsensusParams(ctx)
// Note: we verify votes extensions on VoteExtensionsEnableHeight+1. Check
// comment in ExtendVote and ValidateVoteExtensions for more details.
extsEnabled := cp.Abci != nil && req.Height >= cp.Abci.VoteExtensionsEnableHeight && cp.Abci.VoteExtensionsEnableHeight != 0
if !extsEnabled {
return nil, fmt.Errorf("vote extensions are not enabled; unexpected call to VerifyVoteExtension at height %d", req.Height)
}
// add a deferred recover handler in case verifyVoteExt panics
defer func() {
if r := recover(); r != nil {
app.logger.Error(
"panic recovered in VerifyVoteExtension",
"height", req.Height,
"hash", fmt.Sprintf("%X", req.Hash),
"validator", fmt.Sprintf("%X", req.ValidatorAddress),
"panic", r,
)
err = fmt.Errorf("recovered application panic in VerifyVoteExtension: %v", r)
}
}()
ctx = ctx.
WithConsensusParams(cp).
WithBlockGasMeter(storetypes.NewInfiniteGasMeter()).
WithBlockHeight(req.Height).
WithHeaderHash(req.Hash).
WithExecMode(sdk.ExecModeVerifyVoteExtension).
WithHeaderInfo(coreheader.Info{
ChainID: app.chainID,
Height: req.Height,
Hash: req.Hash,
})
resp, err = app.verifyVoteExt(ctx, req)
if err != nil {
app.logger.Error("failed to verify vote extension", "height", req.Height, "err", err)
return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_REJECT}, nil
}
return resp, err
}
// internalFinalizeBlock executes the block, called by the Optimistic
// Execution flow or by the FinalizeBlock ABCI method. The context received is
// only used to handle early cancellation, for anything related to state app.finalizeBlockState.Context()
// must be used.
func (app *BaseApp) internalFinalizeBlock(ctx context.Context, req *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) {
var events []abci.Event
if err := app.checkHalt(req.Height, req.Time); err != nil {
return nil, err
}
if err := app.validateFinalizeBlockHeight(req); err != nil {
return nil, err
}
if app.cms.TracingEnabled() {
app.cms.SetTracingContext(storetypes.TraceContext(
map[string]any{"blockHeight": req.Height},
))
}
header := cmtproto.Header{
ChainID: app.chainID,
Height: req.Height,
Time: req.Time,
ProposerAddress: req.ProposerAddress,
NextValidatorsHash: req.NextValidatorsHash,
AppHash: app.LastCommitID().Hash,
}
// finalizeBlockState should be set on InitChain or ProcessProposal. If it is
// nil, it means we are replaying this block and we need to set the state here
// given that during block replay ProcessProposal is not executed by CometBFT.
if app.finalizeBlockState == nil {
app.setState(execModeFinalize, header)
}
// metrics and trace
heightStr := strconv.Itoa(int(req.Height))
metricsCtx, doneFn := metrics.ReportFuncCallAndTimingSdkCtx(app.finalizeBlockState.Context(), metrics.Tags{"svc": "app", "height": heightStr})
defer doneFn()
if app.traceFlightRecorder != nil {
defer app.traceFlightRecorder.StartRegion("finalize-block", heightStr)()
}
app.finalizeBlockState.SetContext(metricsCtx)
// Context is now updated with Header information.
app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().
WithBlockHeader(header).
WithHeaderHash(req.Hash).
WithHeaderInfo(coreheader.Info{
ChainID: app.chainID,
Height: req.Height,
Time: req.Time,
Hash: req.Hash,
AppHash: app.LastCommitID().Hash,
}).
WithConsensusParams(app.GetConsensusParams(app.finalizeBlockState.Context())).
WithVoteInfos(req.DecidedLastCommit.Votes).
WithExecMode(sdk.ExecModeFinalize).
WithCometInfo(cometInfo{
Misbehavior: req.Misbehavior,
ValidatorsHash: req.NextValidatorsHash,
ProposerAddress: req.ProposerAddress,
LastCommit: req.DecidedLastCommit,
}))
// GasMeter must be set after we get a context with updated consensus params.
gasMeter := app.getBlockGasMeter(app.finalizeBlockState.Context())
app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().WithBlockGasMeter(gasMeter))
if app.checkState != nil {
app.checkState.SetContext(app.checkState.Context().
WithBlockGasMeter(gasMeter).
WithHeaderHash(req.Hash))
}
preblockEvents, err := app.preBlock(req)
if err != nil {
return nil, err
}
events = append(events, preblockEvents...)
beginBlock, err := app.beginBlock(req)
if err != nil {
return nil, err
}
// First check for an abort signal after beginBlock, as it's the first place
// we spend any significant amount of time.
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// continue
}
events = append(events, beginBlock.Events...)
// Reset the gas meter so that the AnteHandlers aren't required to
gasMeter = app.getBlockGasMeter(app.finalizeBlockState.Context())
app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().WithBlockGasMeter(gasMeter))
// Iterate over all raw transactions in the proposal and attempt to execute
// them, gathering the execution results.
//
// NOTE: Not all raw transactions may adhere to the sdk.Tx interface, e.g.
// vote extensions, so skip those.
txResults := make([]*abci.ExecTxResult, 0, len(req.Txs))
for _, rawTx := range req.Txs {
var response *abci.ExecTxResult
if _, err := app.txDecoder(rawTx); err == nil {
response = app.deliverTx(rawTx)
} else {
// In the case where a transaction included in a block proposal is malformed,
// we still want to return a default response to comet. This is because comet
// expects a response for each transaction included in a block proposal.
response = sdkerrors.ResponseExecTxResultWithEvents(
sdkerrors.ErrTxDecode,
0,
0,
nil,
false,
)
}
// check after every tx if we should abort
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// continue
}
txResults = append(txResults, response)
}
if app.finalizeBlockState.ms.TracingEnabled() {
app.finalizeBlockState.ms = app.finalizeBlockState.ms.SetTracingContext(nil).(storetypes.CacheMultiStore)
}
endBlock, err := app.endBlock(app.finalizeBlockState.Context())
if err != nil {
return nil, err
}
// check after endBlock if we should abort, to avoid propagating the result
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// continue
}
events = append(events, endBlock.Events...)
cp := app.GetConsensusParams(app.finalizeBlockState.Context())
return &abci.ResponseFinalizeBlock{
Events: events,
TxResults: txResults,
ValidatorUpdates: endBlock.ValidatorUpdates,
ConsensusParamUpdates: &cp,
}, nil
}
// FinalizeBlock will execute the block proposal provided by RequestFinalizeBlock.
// Specifically, it will execute an application's BeginBlock (if defined), followed
// by the transactions in the proposal, finally followed by the application's
// EndBlock (if defined).
//
// For each raw transaction, i.e. a byte slice, BaseApp will only execute it if
// it adheres to the sdk.Tx interface. Otherwise, the raw transaction will be
// skipped. This is to support compatibility with proposers injecting vote
// extensions into the proposal, which should not themselves be executed in cases
// where they adhere to the sdk.Tx interface.
func (app *BaseApp) FinalizeBlock(req *abci.RequestFinalizeBlock) (res *abci.ResponseFinalizeBlock, err error) {
defer func() {
// call the streaming service hooks with the FinalizeBlock messages
for _, streamingListener := range app.streamingManager.ABCIListeners {
if err := streamingListener.ListenFinalizeBlock(app.finalizeBlockState.Context(), *req, *res); err != nil {
app.logger.Error("ListenFinalizeBlock listening hook failed", "height", req.Height, "err", err)
}
}
}()
if app.optimisticExec.Initialized() {
// check if the hash we got is the same as the one we are executing
aborted := app.optimisticExec.AbortIfNeeded(req.Hash)
// Wait for the OE to finish, regardless of whether it was aborted or not
res, err = app.optimisticExec.WaitResult()
// only return if we are not aborting
if !aborted {
if res != nil {
res.AppHash = app.workingHash()
}
return res, err
}
// if it was aborted, we need to reset the state
app.finalizeBlockState = nil
app.optimisticExec.Reset()
}
// if no OE is running, just run the block (this is either a block replay or a OE that got aborted)
res, err = app.internalFinalizeBlock(context.Background(), req)
if res != nil {
res.AppHash = app.workingHash()
}
return res, err
}
// checkHalt checkes if height or time exceeds halt-height or halt-time respectively.
func (app *BaseApp) checkHalt(height int64, time time.Time) error {
var halt bool
switch {
case app.haltHeight > 0 && uint64(height) > app.haltHeight:
halt = true
case app.haltTime > 0 && time.Unix() > int64(app.haltTime):
halt = true
}
if halt {
return fmt.Errorf("halt per configuration height %d time %d", app.haltHeight, app.haltTime)
}
return nil
}
// Commit implements the ABCI interface. It will commit all state that exists in
// the deliver state's multi-store and includes the resulting commit ID in the
// returned abci.ResponseCommit. Commit will set the check state based on the
// latest header and reset the deliver state. Also, if a non-zero halt height is
// defined in config, Commit will execute a deferred function call to check
// against that height and gracefully halt if it matches the latest committed
// height.
func (app *BaseApp) Commit() (*abci.ResponseCommit, error) {
header := app.finalizeBlockState.Context().BlockHeader()
retainHeight := app.GetBlockRetentionHeight(header.Height)
if app.precommiter != nil {
app.precommiter(app.finalizeBlockState.Context())
}
rms, ok := app.cms.(*rootmulti.Store)
if ok {
rms.SetCommitHeader(header)
}
app.cms.Commit()
resp := &abci.ResponseCommit{
RetainHeight: retainHeight,
}
abciListeners := app.streamingManager.ABCIListeners
if len(abciListeners) > 0 {
ctx := app.finalizeBlockState.Context()
blockHeight := ctx.BlockHeight()
changeSet := app.cms.PopStateCache()
for _, abciListener := range abciListeners {
if err := abciListener.ListenCommit(ctx, *resp, changeSet); err != nil {
app.logger.Error("Commit listening hook failed", "height", blockHeight, "err", err)
}
}
}
// Reset the CheckTx state to the latest committed.
//
// NOTE: This is safe because CometBFT holds a lock on the mempool for
// Commit. Use the header from this latest block.
app.setState(execModeCheck, header)
app.finalizeBlockState = nil
if app.prepareCheckStater != nil {
app.prepareCheckStater(app.checkState.Context())
}
// The SnapshotIfApplicable method will create the snapshot by starting the goroutine
app.snapshotManager.SnapshotIfApplicable(header.Height)
return resp, nil
}
// workingHash gets the apphash that will be finalized in commit.
// These writes will be persisted to the root multi-store (app.cms) and flushed to
// disk in the Commit phase. This means when the ABCI client requests Commit(), the application
// state transitions will be flushed to disk and as a result, but we already have
// an application Merkle root.
func (app *BaseApp) workingHash() []byte {
// Write the FinalizeBlock state into branched storage and commit the MultiStore.
// The write to the FinalizeBlock state writes all state transitions to the root
// MultiStore (app.cms) so when Commit() is called it persists those values.
app.finalizeBlockState.ms.Write()
// Get the hash of all writes in order to return the apphash to the comet in finalizeBlock.
commitHash := app.cms.WorkingHash()
app.logger.Debug("hash of all writes", "workingHash", fmt.Sprintf("%X", commitHash))
return commitHash
}
func handleQueryApp(app *BaseApp, path []string, req *abci.RequestQuery) *abci.ResponseQuery {
if len(path) >= 2 {
switch path[1] {
case "simulate":
txBytes := req.Data
gInfo, res, err := app.Simulate(txBytes)
if err != nil {
return sdkerrors.QueryResult(errorsmod.Wrap(err, "failed to simulate tx"), app.trace)
}
simRes := &sdk.SimulationResponse{
GasInfo: gInfo,
Result: res,
}
bz, err := codec.ProtoMarshalJSON(simRes, app.interfaceRegistry)
if err != nil {
return sdkerrors.QueryResult(errorsmod.Wrap(err, "failed to JSON encode simulation response"), app.trace)
}
return &abci.ResponseQuery{
Codespace: sdkerrors.RootCodespace,
Height: req.Height,
Value: bz,
}
case "version":
return &abci.ResponseQuery{
Codespace: sdkerrors.RootCodespace,
Height: req.Height,
Value: []byte(app.version),
}
default:
return sdkerrors.QueryResult(errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query: %s", path), app.trace)
}
}
return sdkerrors.QueryResult(
errorsmod.Wrap(
sdkerrors.ErrUnknownRequest,
"expected second parameter to be either 'simulate' or 'version', neither was present",
), app.trace)
}
func handleQueryStore(app *BaseApp, path []string, req abci.RequestQuery) *abci.ResponseQuery {
// "/store" prefix for store queries
queryable, ok := app.cms.(storetypes.Queryable)
if !ok {
return sdkerrors.QueryResult(errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "multi-store does not support queries"), app.trace)
}
req.Path = "/" + strings.Join(path[1:], "/")
if req.Height <= 1 && req.Prove {
return sdkerrors.QueryResult(
errorsmod.Wrap(
sdkerrors.ErrInvalidRequest,
"cannot query with proof when height <= 1; please provide a valid height",
), app.trace)
}
sdkReq := storetypes.RequestQuery(req)
resp, err := queryable.Query(&sdkReq)
if err != nil {
return sdkerrors.QueryResult(err, app.trace)
}
resp.Height = req.Height
abciResp := abci.ResponseQuery(*resp)
return &abciResp
}
func handleQueryP2P(app *BaseApp, path []string) *abci.ResponseQuery {
// "/p2p" prefix for p2p queries
if len(path) < 4 {
return sdkerrors.QueryResult(errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "path should be p2p filter <addr|id> <parameter>"), app.trace)
}
var resp *abci.ResponseQuery
cmd, typ, arg := path[1], path[2], path[3]
switch cmd {
case "filter":
switch typ {
case "addr":
resp = app.FilterPeerByAddrPort(arg)
case "id":
resp = app.FilterPeerByID(arg)
}
default:
resp = sdkerrors.QueryResult(errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "expected second parameter to be 'filter'"), app.trace)
}
return resp
}
// SplitABCIQueryPath splits a string path using the delimiter '/'.
//
// e.g. "this/is/funny" becomes []string{"this", "is", "funny"}
func SplitABCIQueryPath(requestPath string) (path []string) {
path = strings.Split(requestPath, "/")
// first element is empty string
if len(path) > 0 && path[0] == "" {
path = path[1:]
}
return path
}
// FilterPeerByAddrPort filters peers by address/port.
func (app *BaseApp) FilterPeerByAddrPort(info string) *abci.ResponseQuery {
if app.addrPeerFilter != nil {
return app.addrPeerFilter(info)
}
return &abci.ResponseQuery{}
}
// FilterPeerByID filters peers by node ID.
func (app *BaseApp) FilterPeerByID(info string) *abci.ResponseQuery {
if app.idPeerFilter != nil {
return app.idPeerFilter(info)
}
return &abci.ResponseQuery{}
}
// getContextForProposal returns the correct Context for PrepareProposal and
// ProcessProposal. We use finalizeBlockState on the first block to be able to
// access any state changes made in InitChain.
func (app *BaseApp) getContextForProposal(ctx sdk.Context, height int64) sdk.Context {
if height == app.initialHeight {
ctx, _ = app.finalizeBlockState.Context().CacheContext()
// clear all context data set during InitChain to avoid inconsistent behavior
ctx = ctx.WithBlockHeader(cmtproto.Header{}).WithHeaderInfo(coreheader.Info{})
return ctx
}
return ctx
}
func (app *BaseApp) handleQueryGRPC(handler GRPCQueryHandler, req *abci.RequestQuery) *abci.ResponseQuery {
ctx, err := app.CreateQueryContext(req.Height, req.Prove)
if err != nil {
return sdkerrors.QueryResult(err, app.trace)
}
resp, err := handler(ctx, req)
if err != nil {
resp = sdkerrors.QueryResult(gRPCErrorToSDKError(err), app.trace)
resp.Height = req.Height
return resp
}
return resp
}
func gRPCErrorToSDKError(err error) error {
status, ok := grpcstatus.FromError(err)
if !ok {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error())
}
if len(status.Details()) > 0 {
err = errorsmod.Wrapf(err, "%v", status.Details())
}
switch status.Code() {
case codes.NotFound:
return errorsmod.Wrap(sdkerrors.ErrKeyNotFound, err.Error())
case codes.InvalidArgument:
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error())
case codes.FailedPrecondition:
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error())
case codes.Unauthenticated:
return errorsmod.Wrap(sdkerrors.ErrUnauthorized, err.Error())
default:
return errorsmod.Wrap(sdkerrors.ErrUnknownRequest, err.Error())
}
}
func checkNegativeHeight(height int64) error {
if height < 0 {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "cannot query with height < 0; please provide a valid height")
}
return nil
}
// createQueryContext creates a new sdk.Context for a query, taking as args
// the block height and whether the query needs a proof or not.
func (app *BaseApp) CreateQueryContext(height int64, prove bool) (sdk.Context, error) {
if err := checkNegativeHeight(height); err != nil {
return sdk.Context{}, err
}
// use custom query multi-store if provided
qms := app.qms
if qms == nil {
qms = app.cms.(storetypes.MultiStore)
}
lastBlockHeight := qms.LatestVersion()
if lastBlockHeight == 0 {
return sdk.Context{}, errorsmod.Wrapf(sdkerrors.ErrInvalidHeight, "%s is not ready; please wait for first block", app.Name())
}
if height > lastBlockHeight {
return sdk.Context{},
errorsmod.Wrap(
sdkerrors.ErrInvalidHeight,
"cannot query with height in the future; please provide a valid height",
)
}
// when a client did not provide a query height, manually inject the latest
if height == 0 {
height = lastBlockHeight
}
if height <= 1 && prove {
return sdk.Context{},
errorsmod.Wrap(
sdkerrors.ErrInvalidRequest,
"cannot query with proof when height <= 1; please provide a valid height",
)
}
cacheMS, err := qms.CacheMultiStoreWithVersion(height)
if err != nil {
return sdk.Context{},
errorsmod.Wrapf(
sdkerrors.ErrInvalidRequest,
"failed to load state at height %d; %s (latest height: %d)", height, err, lastBlockHeight,
)
}
// branch the commit multi-store for safety
header := app.checkState.Context().BlockHeader()
ctx := sdk.NewContext(cacheMS, header, true, app.logger).
WithMinGasPrices(app.minGasPrices).
WithGasMeter(storetypes.NewGasMeter(app.queryGasLimit)).
WithBlockHeader(header).
WithBlockHeight(height)
if height != lastBlockHeight {
rms, ok := app.cms.(*rootmulti.Store)
if ok {
cInfo, err := rms.GetCommitInfo(height)
if cInfo != nil && err == nil {
ctx = ctx.WithBlockTime(cInfo.Timestamp)
}
}
}
return ctx, nil
}
// GetBlockRetentionHeight returns the height for which all blocks below this height
// are pruned from CometBFT. Given a commitment height and a non-zero local
// minRetainBlocks configuration, the retentionHeight is the smallest height that
// satisfies:
//
// - Unbonding (safety threshold) time: The block interval in which validators
// can be economically punished for misbehavior. Blocks in this interval must be
// auditable e.g. by the light client.
//
// - Logical store snapshot interval: The block interval at which the underlying
// logical store database is persisted to disk, e.g. every 10000 heights. Blocks
// since the last IAVL snapshot must be available for replay on application restart.
//
// - State sync snapshots: Blocks since the oldest available snapshot must be
// available for state sync nodes to catch up (oldest because a node may be
// restoring an old snapshot while a new snapshot was taken).
//
// - Local (minRetainBlocks) config: Archive nodes may want to retain more or
// all blocks, e.g. via a local config option min-retain-blocks. There may also
// be a need to vary retention for other nodes, e.g. sentry nodes which do not
// need historical blocks.
func (app *BaseApp) GetBlockRetentionHeight(commitHeight int64) int64 {
// pruning is disabled if minRetainBlocks is zero
if app.minRetainBlocks == 0 {
return 0
}
minNonZero := func(x, y int64) int64 {
switch {
case x == 0:
return y
case y == 0:
return x
case x < y:
return x
default:
return y
}
}
// Define retentionHeight as the minimum value that satisfies all non-zero
// constraints. All blocks below (commitHeight-retentionHeight) are pruned
// from CometBFT.
var retentionHeight int64
// Define the number of blocks needed to protect against misbehaving validators
// which allows light clients to operate safely. Note, we piggy back of the
// evidence parameters instead of computing an estimated number of blocks based
// on the unbonding period and block commitment time as the two should be
// equivalent.
cp := app.GetConsensusParams(app.finalizeBlockState.Context())
if cp.Evidence != nil && cp.Evidence.MaxAgeNumBlocks > 0 {
retentionHeight = commitHeight - cp.Evidence.MaxAgeNumBlocks
}
if app.snapshotManager != nil {
snapshotRetentionHeights := app.snapshotManager.GetSnapshotBlockRetentionHeights()
if snapshotRetentionHeights > 0 {
retentionHeight = minNonZero(retentionHeight, commitHeight-snapshotRetentionHeights)
}
}
v := commitHeight - int64(app.minRetainBlocks)
retentionHeight = minNonZero(retentionHeight, v)
if retentionHeight <= 0 {
// prune nothing in the case of a non-positive height
return 0
}
return retentionHeight
}
// toVoteInfo converts the new ExtendedVoteInfo to VoteInfo.
func toVoteInfo(votes []abci.ExtendedVoteInfo) []abci.VoteInfo {
legacyVotes := make([]abci.VoteInfo, len(votes))
for i, vote := range votes {
legacyVotes[i] = abci.VoteInfo{
Validator: abci.Validator{
Address: vote.Validator.Address,
Power: vote.Validator.Power,
},
BlockIdFlag: vote.BlockIdFlag,
}
}
return legacyVotes
}
package baseapp
import (
"context"
"fmt"
"math"
"sort"
"strconv"
"github.com/InjectiveLabs/metrics"
"github.com/cockroachdb/errors"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/crypto/tmhash"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/gogoproto/proto"
"golang.org/x/exp/maps"
protov2 "google.golang.org/protobuf/proto"
"cosmossdk.io/core/header"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
"cosmossdk.io/store"
storemetrics "cosmossdk.io/store/metrics"
"cosmossdk.io/store/snapshots"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/baseapp/oe"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/mempool"
)
type (
execMode uint8
// StoreLoader defines a customizable function to control how we load the
// CommitMultiStore from disk. This is useful for state migration, when
// loading a datastore written with an older version of the software. In
// particular, if a module changed the substore key name (or removed a substore)
// between two versions of the software.
StoreLoader func(ms storetypes.CommitMultiStore) error
contextKeyT string
)
const (
execModeCheck execMode = iota // Check a transaction
execModeReCheck // Recheck a (pending) transaction after a commit
execModeSimulate // Simulate a transaction
execModePrepareProposal // Prepare a block proposal
execModeProcessProposal // Process a block proposal
execModeVoteExtension // Extend or verify a pre-commit vote
execModeVerifyVoteExtension // Verify a vote extension
execModeFinalize // Finalize a block proposal
DoNotFailFastSendContextKey contextKeyT = "DoNotFailFast"
)
var _ servertypes.ABCI = (*BaseApp)(nil)
// BaseApp reflects the ABCI application implementation.
type BaseApp struct {
// initialized on creation
logger log.Logger
name string // application name from abci.BlockInfo
db dbm.DB // common DB backend
cms storetypes.CommitMultiStore // Main (uncached) state
qms storetypes.MultiStore // Optional alternative multistore for querying only.
storeLoader StoreLoader // function to handle store loading, may be overridden with SetStoreLoader()
grpcQueryRouter *GRPCQueryRouter // router for redirecting gRPC query calls
msgServiceRouter *MsgServiceRouter // router for redirecting Msg service messages
interfaceRegistry codectypes.InterfaceRegistry
txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx
txEncoder sdk.TxEncoder // marshal sdk.Tx into []byte
mempool mempool.Mempool // application side mempool
anteHandler sdk.AnteHandler // ante handler for fee and auth
postHandler sdk.PostHandler // post handler, optional
initChainer sdk.InitChainer // ABCI InitChain handler
preBlocker sdk.PreBlocker // logic to run before BeginBlocker
beginBlocker sdk.BeginBlocker // (legacy ABCI) BeginBlock handler
endBlocker sdk.EndBlocker // (legacy ABCI) EndBlock handler
processProposal sdk.ProcessProposalHandler // ABCI ProcessProposal handler
prepareProposal sdk.PrepareProposalHandler // ABCI PrepareProposal
extendVote sdk.ExtendVoteHandler // ABCI ExtendVote handler
verifyVoteExt sdk.VerifyVoteExtensionHandler // ABCI VerifyVoteExtension handler
prepareCheckStater sdk.PrepareCheckStater // logic to run during commit using the checkState
precommiter sdk.Precommiter // logic to run during commit using the deliverState
addrPeerFilter sdk.PeerFilter // filter peers by address and port
idPeerFilter sdk.PeerFilter // filter peers by node ID
fauxMerkleMode bool // if true, IAVL MountStores uses MountStoresDB for simulation speed.
sigverifyTx bool // in the simulation test, since the account does not have a private key, we have to ignore the tx sigverify.
// manages snapshots, i.e. dumps of app state at certain intervals
snapshotManager *snapshots.Manager
// volatile states:
//
// - checkState is set on InitChain and reset on Commit
// - finalizeBlockState is set on InitChain and FinalizeBlock and set to nil
// on Commit.
//
// - checkState: Used for CheckTx, which is set based on the previous block's
// state. This state is never committed.
//
// - prepareProposalState: Used for PrepareProposal, which is set based on the
// previous block's state. This state is never committed. In case of multiple
// consensus rounds, the state is always reset to the previous block's state.
//
// - processProposalState: Used for ProcessProposal, which is set based on the
// the previous block's state. This state is never committed. In case of
// multiple rounds, the state is always reset to the previous block's state.
//
// - finalizeBlockState: Used for FinalizeBlock, which is set based on the
// previous block's state. This state is committed.
checkState *state
prepareProposalState *state
processProposalState *state
finalizeBlockState *state
// An inter-block write-through cache provided to the context during the ABCI
// FinalizeBlock call.
interBlockCache storetypes.MultiStorePersistentCache
// paramStore is used to query for ABCI consensus parameters from an
// application parameter store.
paramStore ParamStore
// queryGasLimit defines the maximum gas for queries; unbounded if 0.
queryGasLimit uint64
// The minimum gas prices a validator is willing to accept for processing a
// transaction. This is mainly used for DoS and spam prevention.
minGasPrices sdk.DecCoins
// initialHeight is the initial height at which we start the BaseApp
initialHeight int64
// flag for sealing options and parameters to a BaseApp
sealed bool
// block height at which to halt the chain and gracefully shutdown
haltHeight uint64
// minimum block time (in Unix seconds) at which to halt the chain and gracefully shutdown
haltTime uint64
// minRetainBlocks defines the minimum block height offset from the current
// block being committed, such that all blocks past this offset are pruned
// from CometBFT. It is used as part of the process of determining the
// ResponseCommit.RetainHeight value during ABCI Commit. A value of 0 indicates
// that no blocks should be pruned.
//
// Note: CometBFT block pruning is dependant on this parameter in conjunction
// with the unbonding (safety threshold) period, state pruning and state sync
// snapshot parameters to determine the correct minimum value of
// ResponseCommit.RetainHeight.
minRetainBlocks uint64
// application's version string
version string
// application's protocol version that increments on every upgrade
// if BaseApp is passed to the upgrade keeper's NewKeeper method.
appVersion uint64
// recovery handler for app.runTx method
runTxRecoveryMiddleware recoveryMiddleware
// trace set will return full stack traces for errors in ABCI Log field
trace bool
// indexEvents defines the set of events in the form {eventType}.{attributeKey},
// which informs CometBFT what to index. If empty, all events will be indexed.
indexEvents map[string]struct{}
// streamingManager for managing instances and configuration of ABCIListener services
streamingManager storetypes.StreamingManager
chainID string
cdc codec.Codec
// optimisticExec contains the context required for Optimistic Execution,
// including the goroutine handling.This is experimental and must be enabled
// by developers.
optimisticExec *oe.OptimisticExecution
// disableBlockGasMeter will disable the block gas meter if true, block gas meter is tricky to support
// when executing transactions in parallel.
// when disabled, the block gas meter in context is a noop one.
//
// SAFETY: it's safe to do if validators validate the total gas wanted in the `ProcessProposal`, which is the case in the default handler.
disableBlockGasMeter bool
// StreamEvents
EnableStreamer bool
StreamEvents chan StreamEvents
traceFlightRecorder *metrics.TraceRecorder
}
// NewBaseApp returns a reference to an initialized BaseApp. It accepts a
// variadic number of option functions, which act on the BaseApp to set
// configuration choices.
func NewBaseApp(
name string, logger log.Logger, db dbm.DB, txDecoder sdk.TxDecoder, options ...func(*BaseApp),
) *BaseApp {
app := &BaseApp{
logger: logger,
name: name,
db: db,
cms: store.NewCommitMultiStore(db, logger, storemetrics.NewNoOpMetrics()), // by default we use a no-op metric gather in store
storeLoader: DefaultStoreLoader,
grpcQueryRouter: NewGRPCQueryRouter(),
msgServiceRouter: NewMsgServiceRouter(),
txDecoder: txDecoder,
fauxMerkleMode: false,
sigverifyTx: true,
queryGasLimit: math.MaxUint64,
StreamEvents: make(chan StreamEvents),
}
for _, option := range options {
option(app)
}
if app.mempool == nil {
app.SetMempool(mempool.NoOpMempool{})
}
abciProposalHandler := NewDefaultProposalHandler(app.mempool, app)
if app.prepareProposal == nil {
app.SetPrepareProposal(abciProposalHandler.PrepareProposalHandler())
}
if app.processProposal == nil {
app.SetProcessProposal(abciProposalHandler.ProcessProposalHandler())
}
if app.extendVote == nil {
app.SetExtendVoteHandler(NoOpExtendVote())
}
if app.verifyVoteExt == nil {
app.SetVerifyVoteExtensionHandler(NoOpVerifyVoteExtensionHandler())
}
if app.interBlockCache != nil {
app.cms.SetInterBlockCache(app.interBlockCache)
}
app.runTxRecoveryMiddleware = newDefaultRecoveryMiddleware()
// Initialize with an empty interface registry to avoid nil pointer dereference.
// Unless SetInterfaceRegistry is called with an interface registry with proper address codecs baseapp will panic.
app.cdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
return app
}
// Name returns the name of the BaseApp.
func (app *BaseApp) Name() string {
return app.name
}
// AppVersion returns the application's protocol version.
func (app *BaseApp) AppVersion() uint64 {
return app.appVersion
}
// Version returns the application's version string.
func (app *BaseApp) Version() string {
return app.version
}
// Logger returns the logger of the BaseApp.
func (app *BaseApp) Logger() log.Logger {
return app.logger
}
// Trace returns the boolean value for logging error stack traces.
func (app *BaseApp) Trace() bool {
return app.trace
}
// MsgServiceRouter returns the MsgServiceRouter of a BaseApp.
func (app *BaseApp) MsgServiceRouter() *MsgServiceRouter { return app.msgServiceRouter }
// GRPCQueryRouter returns the GRPCQueryRouter of a BaseApp.
func (app *BaseApp) GRPCQueryRouter() *GRPCQueryRouter { return app.grpcQueryRouter }
// MountStores mounts all IAVL or DB stores to the provided keys in the BaseApp
// multistore.
func (app *BaseApp) MountStores(keys ...storetypes.StoreKey) {
for _, key := range keys {
switch key.(type) {
case *storetypes.KVStoreKey:
if !app.fauxMerkleMode {
app.MountStore(key, storetypes.StoreTypeIAVL)
} else {
// StoreTypeDB doesn't do anything upon commit, and it doesn't
// retain history, but it's useful for faster simulation.
app.MountStore(key, storetypes.StoreTypeDB)
}
case *storetypes.TransientStoreKey:
app.MountStore(key, storetypes.StoreTypeTransient)
case *storetypes.MemoryStoreKey:
app.MountStore(key, storetypes.StoreTypeMemory)
default:
panic(fmt.Sprintf("Unrecognized store key type :%T", key))
}
}
}
// MountKVStores mounts all IAVL or DB stores to the provided keys in the
// BaseApp multistore.
func (app *BaseApp) MountKVStores(keys map[string]*storetypes.KVStoreKey) {
for _, key := range keys {
if !app.fauxMerkleMode {
app.MountStore(key, storetypes.StoreTypeIAVL)
} else {
// StoreTypeDB doesn't do anything upon commit, and it doesn't
// retain history, but it's useful for faster simulation.
app.MountStore(key, storetypes.StoreTypeDB)
}
}
}
// MountTransientStores mounts all transient stores to the provided keys in
// the BaseApp multistore.
func (app *BaseApp) MountTransientStores(keys map[string]*storetypes.TransientStoreKey) {
for _, key := range keys {
app.MountStore(key, storetypes.StoreTypeTransient)
}
}
// MountMemoryStores mounts all in-memory KVStores with the BaseApp's internal
// commit multi-store.
func (app *BaseApp) MountMemoryStores(keys map[string]*storetypes.MemoryStoreKey) {
skeys := maps.Keys(keys)
sort.Strings(skeys)
for _, key := range skeys {
memKey := keys[key]
app.MountStore(memKey, storetypes.StoreTypeMemory)
}
}
// MountStore mounts a store to the provided key in the BaseApp multistore,
// using the default DB.
func (app *BaseApp) MountStore(key storetypes.StoreKey, typ storetypes.StoreType) {
app.cms.MountStoreWithDB(key, typ, nil)
}
// LoadLatestVersion loads the latest application version. It will panic if
// called more than once on a running BaseApp.
func (app *BaseApp) LoadLatestVersion() error {
err := app.storeLoader(app.cms)
if err != nil {
return fmt.Errorf("failed to load latest version: %w", err)
}
return app.Init()
}
// DefaultStoreLoader will be used by default and loads the latest version
func DefaultStoreLoader(ms storetypes.CommitMultiStore) error {
return ms.LoadLatestVersion()
}
// CommitMultiStore returns the root multi-store.
// App constructor can use this to access the `cms`.
// UNSAFE: must not be used during the abci life cycle.
func (app *BaseApp) CommitMultiStore() storetypes.CommitMultiStore {
return app.cms
}
// SnapshotManager returns the snapshot manager.
// application use this to register extra extension snapshotters.
func (app *BaseApp) SnapshotManager() *snapshots.Manager {
return app.snapshotManager
}
// LoadVersion loads the BaseApp application version. It will panic if called
// more than once on a running baseapp.
func (app *BaseApp) LoadVersion(version int64) error {
app.logger.Info("NOTICE: this could take a long time to migrate IAVL store to fastnode if you enable Fast Node.\n")
err := app.cms.LoadVersion(version)
if err != nil {
return fmt.Errorf("failed to load version %d: %w", version, err)
}
return app.Init()
}
// LastCommitID returns the last CommitID of the multistore.
func (app *BaseApp) LastCommitID() storetypes.CommitID {
return app.cms.LastCommitID()
}
// LastBlockHeight returns the last committed block height.
func (app *BaseApp) LastBlockHeight() int64 {
return app.cms.LastCommitID().Version
}
// ChainID returns the chainID of the app.
func (app *BaseApp) ChainID() string {
return app.chainID
}
// AnteHandler returns the AnteHandler of the app.
func (app *BaseApp) AnteHandler() sdk.AnteHandler {
return app.anteHandler
}
// Mempool returns the Mempool of the app.
func (app *BaseApp) Mempool() mempool.Mempool {
return app.mempool
}
// Init initializes the app. It seals the app, preventing any
// further modifications. In addition, it validates the app against
// the earlier provided settings. Returns an error if validation fails.
// nil otherwise. Panics if the app is already sealed.
func (app *BaseApp) Init() error {
if app.sealed {
panic("cannot call initFromMainStore: baseapp already sealed")
}
emptyHeader := cmtproto.Header{ChainID: app.chainID}
// needed for the export command which inits from store but never calls initchain
app.setState(execModeCheck, emptyHeader)
app.Seal()
if app.cms == nil {
return errors.New("commit multi-store must not be nil")
}
return app.cms.GetPruning().Validate()
}
func (app *BaseApp) setMinGasPrices(gasPrices sdk.DecCoins) {
app.minGasPrices = gasPrices
}
func (app *BaseApp) setHaltHeight(haltHeight uint64) {
app.haltHeight = haltHeight
}
func (app *BaseApp) setHaltTime(haltTime uint64) {
app.haltTime = haltTime
}
func (app *BaseApp) setMinRetainBlocks(minRetainBlocks uint64) {
app.minRetainBlocks = minRetainBlocks
}
func (app *BaseApp) setInterBlockCache(cache storetypes.MultiStorePersistentCache) {
app.interBlockCache = cache
}
func (app *BaseApp) setTrace(trace bool) {
app.trace = trace
}
func (app *BaseApp) setIndexEvents(ie []string) {
app.indexEvents = make(map[string]struct{})
for _, e := range ie {
app.indexEvents[e] = struct{}{}
}
}
// Seal seals a BaseApp. It prohibits any further modifications to a BaseApp.
func (app *BaseApp) Seal() { app.sealed = true }
// IsSealed returns true if the BaseApp is sealed and false otherwise.
func (app *BaseApp) IsSealed() bool { return app.sealed }
// setState sets the BaseApp's state for the corresponding mode with a branched
// multi-store (i.e. a CacheMultiStore) and a new Context with the same
// multi-store branch, and provided header.
func (app *BaseApp) setState(mode execMode, h cmtproto.Header) {
ms := app.cms.CacheMultiStore()
headerInfo := header.Info{
Height: h.Height,
Time: h.Time,
ChainID: h.ChainID,
AppHash: h.AppHash,
}
baseState := &state{
ms: ms,
ctx: sdk.NewContext(ms, h, false, app.logger).
WithStreamingManager(app.streamingManager).
WithHeaderInfo(headerInfo),
}
switch mode {
case execModeCheck:
baseState.SetContext(baseState.Context().WithIsCheckTx(true).WithMinGasPrices(app.minGasPrices))
app.checkState = baseState
case execModePrepareProposal:
app.prepareProposalState = baseState
case execModeProcessProposal:
app.processProposalState = baseState
case execModeFinalize:
app.finalizeBlockState = baseState
default:
panic(fmt.Sprintf("invalid runTxMode for setState: %d", mode))
}
}
// SetCircuitBreaker sets the circuit breaker for the BaseApp.
// The circuit breaker is checked on every message execution to verify if a transaction should be executed or not.
func (app *BaseApp) SetCircuitBreaker(cb CircuitBreaker) {
if app.msgServiceRouter == nil {
panic("cannot set circuit breaker with no msg service router set")
}
app.msgServiceRouter.SetCircuit(cb)
}
// GetConsensusParams returns the current consensus parameters from the BaseApp's
// ParamStore. If the BaseApp has no ParamStore defined, nil is returned.
func (app *BaseApp) GetConsensusParams(ctx sdk.Context) cmtproto.ConsensusParams {
if app.paramStore == nil {
return cmtproto.ConsensusParams{}
}
cp, err := app.paramStore.Get(ctx)
if err != nil {
// This could happen while migrating from v0.45/v0.46 to v0.50, we should
// allow it to happen so during preblock the upgrade plan can be executed
// and the consensus params set for the first time in the new format.
app.logger.Error("failed to get consensus params", "err", err)
return cmtproto.ConsensusParams{}
}
return cp
}
// StoreConsensusParams sets the consensus parameters to the BaseApp's param
// store.
//
// NOTE: We're explicitly not storing the CometBFT app_version in the param store.
// It's stored instead in the x/upgrade store, with its own bump logic.
func (app *BaseApp) StoreConsensusParams(ctx sdk.Context, cp cmtproto.ConsensusParams) error {
if app.paramStore == nil {
return errors.New("cannot store consensus params with no params store set")
}
return app.paramStore.Set(ctx, cp)
}
// AddRunTxRecoveryHandler adds custom app.runTx method panic handlers.
func (app *BaseApp) AddRunTxRecoveryHandler(handlers ...RecoveryHandler) {
for _, h := range handlers {
app.runTxRecoveryMiddleware = newRecoveryMiddleware(h, app.runTxRecoveryMiddleware)
}
}
// GetMaximumBlockGas gets the maximum gas from the consensus params. It panics
// if maximum block gas is less than negative one and returns zero if negative
// one.
func (app *BaseApp) GetMaximumBlockGas(ctx sdk.Context) uint64 {
cp := app.GetConsensusParams(ctx)
if cp.Block == nil {
return 0
}
maxGas := cp.Block.MaxGas
switch {
case maxGas < -1:
panic(fmt.Sprintf("invalid maximum block gas: %d", maxGas))
case maxGas == -1:
return 0
default:
return uint64(maxGas)
}
}
func (app *BaseApp) validateFinalizeBlockHeight(req *abci.RequestFinalizeBlock) error {
if req.Height < 1 {
return fmt.Errorf("invalid height: %d", req.Height)
}
lastBlockHeight := app.LastBlockHeight()
// expectedHeight holds the expected height to validate
var expectedHeight int64
if lastBlockHeight == 0 && app.initialHeight > 1 {
// In this case, we're validating the first block of the chain, i.e no
// previous commit. The height we're expecting is the initial height.
expectedHeight = app.initialHeight
} else {
// This case can mean two things:
//
// - Either there was already a previous commit in the store, in which
// case we increment the version from there.
// - Or there was no previous commit, in which case we start at version 1.
expectedHeight = lastBlockHeight + 1
}
if req.Height != expectedHeight {
return fmt.Errorf("invalid height: %d; expected: %d", req.Height, expectedHeight)
}
return nil
}
// validateBasicTxMsgs executes basic validator calls for messages.
func validateBasicTxMsgs(msgs []sdk.Msg) error {
if len(msgs) == 0 {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "must contain at least one message")
}
for _, msg := range msgs {
m, ok := msg.(sdk.HasValidateBasic)
if !ok {
continue
}
if err := m.ValidateBasic(); err != nil {
return err
}
}
return nil
}
func (app *BaseApp) getState(mode execMode) *state {
switch mode {
case execModeFinalize:
return app.finalizeBlockState
case execModePrepareProposal:
return app.prepareProposalState
case execModeProcessProposal:
return app.processProposalState
default:
return app.checkState
}
}
func (app *BaseApp) getBlockGasMeter(ctx sdk.Context) storetypes.GasMeter {
if app.disableBlockGasMeter {
return noopGasMeter{}
}
if maxGas := app.GetMaximumBlockGas(ctx); maxGas > 0 {
return storetypes.NewGasMeter(maxGas)
}
return storetypes.NewInfiniteGasMeter()
}
// retrieve the context for the tx w/ txBytes and other memoized values.
func (app *BaseApp) getContextForTx(mode execMode, txBytes []byte) sdk.Context {
modeState := app.getState(mode)
if modeState == nil {
panic(fmt.Sprintf("state is nil for mode %v", mode))
}
ctx := modeState.Context().
WithTxBytes(txBytes).
WithGasMeter(storetypes.NewInfiniteGasMeter())
// WithVoteInfos(app.voteInfos) // TODO: identify if this is needed
ctx = ctx.WithIsSigverifyTx(app.sigverifyTx)
ctx = ctx.WithConsensusParams(app.GetConsensusParams(ctx))
if mode == execModeReCheck {
ctx = ctx.WithIsReCheckTx(true)
}
if mode == execModeSimulate {
ctx, _ = ctx.CacheContext()
ctx = ctx.WithExecMode(sdk.ExecMode(execModeSimulate))
}
return ctx
}
// cacheTxContext returns a new context based off of the provided context with
// a branched multi-store.
func (app *BaseApp) cacheTxContext(ctx sdk.Context, txBytes []byte) (sdk.Context, storetypes.CacheMultiStore) {
ms := ctx.MultiStore()
// TODO: https://github.com/cosmos/cosmos-sdk/issues/2824
msCache := ms.CacheMultiStore()
if msCache.TracingEnabled() {
msCache = msCache.SetTracingContext(
storetypes.TraceContext(
map[string]interface{}{
"txHash": fmt.Sprintf("%X", tmhash.Sum(txBytes)),
},
),
).(storetypes.CacheMultiStore)
}
return ctx.WithMultiStore(msCache), msCache
}
func (app *BaseApp) preBlock(req *abci.RequestFinalizeBlock) ([]abci.Event, error) {
var events []abci.Event
if app.preBlocker != nil {
ctx := app.finalizeBlockState.Context().WithValue(DoNotFailFastSendContextKey, struct{}{})
rsp, err := app.preBlocker(ctx, req)
if err != nil {
return nil, err
}
events = rsp.Events
// rsp.ConsensusParamsChanged is true from preBlocker means ConsensusParams in store get changed
// write the consensus parameters in store to context
if rsp.ConsensusParamsChanged {
ctx = ctx.WithConsensusParams(app.GetConsensusParams(ctx))
// GasMeter must be set after we get a context with updated consensus params.
gasMeter := app.getBlockGasMeter(ctx)
ctx = ctx.WithBlockGasMeter(gasMeter)
app.finalizeBlockState.SetContext(ctx)
}
}
return events, nil
}
func (app *BaseApp) beginBlock(_ *abci.RequestFinalizeBlock) (sdk.BeginBlock, error) {
var (
resp sdk.BeginBlock
err error
)
if app.beginBlocker != nil {
ctx := app.finalizeBlockState.Context().WithValue(DoNotFailFastSendContextKey, struct{}{})
resp, err = app.beginBlocker(ctx)
if err != nil {
return resp, err
}
// append BeginBlock attributes to all events in the EndBlock response
for i, event := range resp.Events {
resp.Events[i].Attributes = append(
event.Attributes,
abci.EventAttribute{Key: "mode", Value: "BeginBlock"},
)
}
app.AddStreamEvents(ctx.BlockHeight(), ctx.BlockTime(), resp.Events, false)
resp.Events = sdk.MarkEventsToIndex(resp.Events, app.indexEvents)
}
return resp, nil
}
func (app *BaseApp) deliverTx(tx []byte) *abci.ExecTxResult {
gInfo := sdk.GasInfo{}
resultStr := "successful"
var resp *abci.ExecTxResult
defer func() {
telemetry.IncrCounter(1, "tx", "count")
telemetry.IncrCounter(1, "tx", resultStr)
telemetry.SetGauge(float32(gInfo.GasUsed), "tx", "gas", "used")
telemetry.SetGauge(float32(gInfo.GasWanted), "tx", "gas", "wanted")
}()
gInfo, result, anteEvents, err := app.runTx(execModeFinalize, tx)
if err != nil {
resultStr = "failed"
resp = sdkerrors.ResponseExecTxResultWithEvents(
err,
gInfo.GasWanted,
gInfo.GasUsed,
sdk.MarkEventsToIndex(anteEvents, app.indexEvents),
app.trace,
)
return resp
}
ctx := app.finalizeBlockState.Context()
app.AddStreamEvents(ctx.BlockHeight(), ctx.BlockTime(), result.Events, false)
resp = &abci.ExecTxResult{
GasWanted: int64(gInfo.GasWanted),
GasUsed: int64(gInfo.GasUsed),
Log: result.Log,
Data: result.Data,
Events: sdk.MarkEventsToIndex(result.Events, app.indexEvents),
}
return resp
}
// endBlock is an application-defined function that is called after transactions
// have been processed in FinalizeBlock.
func (app *BaseApp) endBlock(_ context.Context) (sdk.EndBlock, error) {
var endblock sdk.EndBlock
if app.endBlocker != nil {
ctx := app.finalizeBlockState.Context().WithValue(DoNotFailFastSendContextKey, struct{}{})
eb, err := app.endBlocker(ctx)
if err != nil {
return endblock, err
}
// append EndBlock attributes to all events in the EndBlock response
for i, event := range eb.Events {
eb.Events[i].Attributes = append(
event.Attributes,
abci.EventAttribute{Key: "mode", Value: "EndBlock"},
)
}
app.AddStreamEvents(ctx.BlockHeight(), ctx.BlockTime(), eb.Events, true)
eb.Events = sdk.MarkEventsToIndex(eb.Events, app.indexEvents)
endblock = eb
}
return endblock, nil
}
// runTx processes a transaction within a given execution mode, encoded transaction
// bytes, and the decoded transaction itself. All state transitions occur through
// a cached Context depending on the mode provided. State only gets persisted
// if all messages get executed successfully and the execution mode is DeliverTx.
// Note, gas execution info is always returned. A reference to a Result is
// returned if the tx does not run out of gas and if all the messages are valid
// and execute successfully. An error is returned otherwise.
func (app *BaseApp) runTx(mode execMode, txBytes []byte) (gInfo sdk.GasInfo, result *sdk.Result, anteEvents []abci.Event, err error) {
// NOTE: GasWanted should be returned by the AnteHandler. GasUsed is
// determined by the GasMeter. We need access to the context to get the gas
// meter, so we initialize upfront.
var gasWanted uint64
ctx := app.getContextForTx(mode, txBytes)
ms := ctx.MultiStore()
// only run the tx if there is block gas remaining
if mode == execModeFinalize && ctx.BlockGasMeter().IsOutOfGas() {
return gInfo, nil, nil, errorsmod.Wrap(sdkerrors.ErrOutOfGas, "no block gas left to run tx")
}
defer func() {
if r := recover(); r != nil {
recoveryMW := newOutOfGasRecoveryMiddleware(gasWanted, ctx, app.runTxRecoveryMiddleware)
err, result = processRecovery(r, recoveryMW), nil
ctx.Logger().Error("panic recovered in runTx", "err", err)
}
gInfo = sdk.GasInfo{GasWanted: gasWanted, GasUsed: ctx.GasMeter().GasConsumed()}
}()
blockGasConsumed := false
// consumeBlockGas makes sure block gas is consumed at most once. It must
// happen after tx processing, and must be executed even if tx processing
// fails. Hence, it's execution is deferred.
consumeBlockGas := func() {
if !blockGasConsumed {
blockGasConsumed = true
ctx.BlockGasMeter().ConsumeGas(
ctx.GasMeter().GasConsumedToLimit(), "block gas meter",
)
}
}
// If BlockGasMeter() panics it will be caught by the above recover and will
// return an error - in any case BlockGasMeter will consume gas past the limit.
//
// NOTE: consumeBlockGas must exist in a separate defer function from the
// general deferred recovery function to recover from consumeBlockGas as it'll
// be executed first (deferred statements are executed as stack).
if mode == execModeFinalize {
defer consumeBlockGas()
}
tx, err := app.txDecoder(txBytes)
if err != nil {
return sdk.GasInfo{}, nil, nil, err
}
msgs := tx.GetMsgs()
if err := validateBasicTxMsgs(msgs); err != nil {
return sdk.GasInfo{}, nil, nil, err
}
for _, msg := range msgs {
handler := app.msgServiceRouter.Handler(msg)
if handler == nil {
return sdk.GasInfo{}, nil, nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "no message handler found for %T", msg)
}
}
if app.anteHandler != nil {
var (
anteCtx sdk.Context
msCache storetypes.CacheMultiStore
)
// Branch context before AnteHandler call in case it aborts.
// This is required for both CheckTx and DeliverTx.
// Ref: https://github.com/cosmos/cosmos-sdk/issues/2772
//
// NOTE: Alternatively, we could require that AnteHandler ensures that
// writes do not happen if aborted/failed. This may have some
// performance benefits, but it'll be more difficult to get right.
anteCtx, msCache = app.cacheTxContext(ctx, txBytes)
anteCtx = anteCtx.WithEventManager(sdk.NewEventManager())
newCtx, err := app.anteHandler(anteCtx, tx, mode == execModeSimulate)
if !newCtx.IsZero() {
// At this point, newCtx.MultiStore() is a store branch, or something else
// replaced by the AnteHandler. We want the original multistore.
//
// Also, in the case of the tx aborting, we need to track gas consumed via
// the instantiated gas meter in the AnteHandler, so we update the context
// prior to returning.
ctx = newCtx.WithMultiStore(ms)
}
events := ctx.EventManager().Events()
// GasMeter expected to be set in AnteHandler
gasWanted = ctx.GasMeter().Limit()
if err != nil {
if mode == execModeReCheck {
// if the ante handler fails on recheck, we want to remove the tx from the mempool
if mempoolErr := app.mempool.Remove(tx); mempoolErr != nil {
return gInfo, nil, anteEvents, errors.Join(err, mempoolErr)
}
}
return gInfo, nil, nil, err
}
msCache.Write()
anteEvents = events.ToABCIEvents()
}
if mode == execModeCheck {
err = app.mempool.Insert(ctx, tx)
if err != nil {
return gInfo, nil, anteEvents, err
}
} else if mode == execModeFinalize {
err = app.mempool.Remove(tx)
if err != nil && !errors.Is(err, mempool.ErrTxNotFound) {
return gInfo, nil, anteEvents,
fmt.Errorf("failed to remove tx from mempool: %w", err)
}
}
// Create a new Context based off of the existing Context with a MultiStore branch
// in case message processing fails. At this point, the MultiStore
// is a branch of a branch.
runMsgCtx, msCache := app.cacheTxContext(ctx, txBytes)
// Attempt to execute all messages and only update state if all messages pass
// and we're in DeliverTx. Note, runMsgs will never return a reference to a
// Result if any single message fails or does not have a registered Handler.
msgsV2, err := tx.GetMsgsV2()
if err == nil {
result, err = app.runMsgs(runMsgCtx, msgs, msgsV2, mode)
}
// Run optional postHandlers (should run regardless of the execution result).
//
// Note: If the postHandler fails, we also revert the runMsgs state.
if app.postHandler != nil {
// The runMsgCtx context currently contains events emitted by the ante handler.
// We clear this to correctly order events without duplicates.
// Note that the state is still preserved.
postCtx := runMsgCtx.WithEventManager(sdk.NewEventManager())
newCtx, errPostHandler := app.postHandler(postCtx, tx, mode == execModeSimulate, err == nil)
if errPostHandler != nil {
return gInfo, nil, anteEvents, errors.Join(err, errPostHandler)
}
// we don't want runTx to panic if runMsgs has failed earlier
if result == nil {
result = &sdk.Result{}
}
result.Events = append(result.Events, newCtx.EventManager().ABCIEvents()...)
}
if err == nil {
if mode == execModeFinalize {
// When block gas exceeds, it'll panic and won't commit the cached store.
consumeBlockGas()
msCache.Write()
}
if len(anteEvents) > 0 && (mode == execModeFinalize || mode == execModeSimulate) {
// append the events in the order of occurrence
result.Events = append(anteEvents, result.Events...)
}
}
return gInfo, result, anteEvents, err
}
// runMsgs iterates through a list of messages and executes them with the provided
// Context and execution mode. Messages will only be executed during simulation
// and DeliverTx. An error is returned if any single message fails or if a
// Handler does not exist for a given message route. Otherwise, a reference to a
// Result is returned. The caller must not commit state if an error is returned.
func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, msgsV2 []protov2.Message, mode execMode) (*sdk.Result, error) {
events := sdk.EmptyEvents()
var msgResponses []*codectypes.Any
// NOTE: GasWanted is determined by the AnteHandler and GasUsed by the GasMeter.
for i, msg := range msgs {
if mode != execModeFinalize && mode != execModeSimulate {
break
}
handler := app.msgServiceRouter.Handler(msg)
if handler == nil {
return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "no message handler found for %T", msg)
}
// ADR 031 request type routing
msgResult, err := handler(ctx, msg)
if err != nil {
return nil, errorsmod.Wrapf(err, "failed to execute message; message index: %d", i)
}
// create message events
msgEvents, err := createEvents(app.cdc, msgResult.GetEvents(), msg, msgsV2[i])
if err != nil {
return nil, errorsmod.Wrapf(err, "failed to create message events; message index: %d", i)
}
// append message events and data
//
// Note: Each message result's data must be length-prefixed in order to
// separate each result.
for j, event := range msgEvents {
// append message index to all events
msgEvents[j] = event.AppendAttributes(sdk.NewAttribute("msg_index", strconv.Itoa(i)))
}
events = events.AppendEvents(msgEvents)
// Each individual sdk.Result that went through the MsgServiceRouter
// (which should represent 99% of the Msgs now, since everyone should
// be using protobuf Msgs) has exactly one Msg response, set inside
// `WrapServiceResult`. We take that Msg response, and aggregate it
// into an array.
if len(msgResult.MsgResponses) > 0 {
msgResponse := msgResult.MsgResponses[0]
if msgResponse == nil {
return nil, sdkerrors.ErrLogic.Wrapf("got nil Msg response at index %d for msg %s", i, sdk.MsgTypeURL(msg))
}
msgResponses = append(msgResponses, msgResponse)
}
}
data, err := makeABCIData(msgResponses)
if err != nil {
return nil, errorsmod.Wrap(err, "failed to marshal tx data")
}
return &sdk.Result{
Data: data,
Events: events.ToABCIEvents(),
MsgResponses: msgResponses,
}, nil
}
// makeABCIData generates the Data field to be sent to ABCI Check/DeliverTx.
func makeABCIData(msgResponses []*codectypes.Any) ([]byte, error) {
return proto.Marshal(&sdk.TxMsgData{MsgResponses: msgResponses})
}
func createEvents(cdc codec.Codec, events sdk.Events, msg sdk.Msg, msgV2 protov2.Message) (sdk.Events, error) {
eventMsgName := sdk.MsgTypeURL(msg)
msgEvent := sdk.NewEvent(sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyAction, eventMsgName))
// we set the signer attribute as the sender
signers, err := cdc.GetMsgV2Signers(msgV2)
if err != nil {
return nil, err
}
if len(signers) > 0 && signers[0] != nil {
addrStr, err := cdc.InterfaceRegistry().SigningContext().AddressCodec().BytesToString(signers[0])
if err != nil {
return nil, err
}
msgEvent = msgEvent.AppendAttributes(sdk.NewAttribute(sdk.AttributeKeySender, addrStr))
}
// verify that events have no module attribute set
if _, found := events.GetAttributes(sdk.AttributeKeyModule); !found {
if moduleName := sdk.GetModuleNameFromTypeURL(eventMsgName); moduleName != "" {
msgEvent = msgEvent.AppendAttributes(sdk.NewAttribute(sdk.AttributeKeyModule, moduleName))
}
}
return sdk.Events{msgEvent}.AppendEvents(events), nil
}
// PrepareProposalVerifyTx performs transaction verification when a proposer is
// creating a block proposal during PrepareProposal. Any state committed to the
// PrepareProposal state internally will be discarded. <nil, err> will be
// returned if the transaction cannot be encoded. <bz, nil> will be returned if
// the transaction is valid, otherwise <bz, err> will be returned.
func (app *BaseApp) PrepareProposalVerifyTx(tx sdk.Tx) ([]byte, error) {
bz, err := app.txEncoder(tx)
if err != nil {
return nil, err
}
_, _, _, err = app.runTx(execModePrepareProposal, bz)
if err != nil {
return nil, err
}
return bz, nil
}
// ProcessProposalVerifyTx performs transaction verification when receiving a
// block proposal during ProcessProposal. Any state committed to the
// ProcessProposal state internally will be discarded. <nil, err> will be
// returned if the transaction cannot be decoded. <Tx, nil> will be returned if
// the transaction is valid, otherwise <Tx, err> will be returned.
func (app *BaseApp) ProcessProposalVerifyTx(txBz []byte) (sdk.Tx, error) {
tx, err := app.txDecoder(txBz)
if err != nil {
return nil, err
}
_, _, _, err = app.runTx(execModeProcessProposal, txBz)
if err != nil {
return nil, err
}
return tx, nil
}
func (app *BaseApp) TxDecode(txBytes []byte) (sdk.Tx, error) {
return app.txDecoder(txBytes)
}
func (app *BaseApp) TxEncode(tx sdk.Tx) ([]byte, error) {
return app.txEncoder(tx)
}
// Close is called in start cmd to gracefully cleanup resources.
func (app *BaseApp) Close() error {
var errs []error
// Close app.db (opened by cosmos-sdk/server/start.go call to openDB)
if app.db != nil {
app.logger.Info("Closing application.db")
if err := app.db.Close(); err != nil {
errs = append(errs, err)
}
}
// Close app.snapshotManager
// - opened when app chains use cosmos-sdk/server/util.go/DefaultBaseappOptions (boilerplate)
// - which calls cosmos-sdk/server/util.go/GetSnapshotStore
// - which is passed to baseapp/options.go/SetSnapshot
// - to set app.snapshotManager = snapshots.NewManager
if app.snapshotManager != nil {
app.logger.Info("Closing snapshots/metadata.db")
if err := app.snapshotManager.Close(); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
package baseapp
import (
"context"
"fmt"
abci "github.com/cometbft/cometbft/abci/types"
gogogrpc "github.com/cosmos/gogoproto/grpc"
"google.golang.org/grpc"
"google.golang.org/grpc/encoding"
"google.golang.org/protobuf/runtime/protoiface"
"github.com/cosmos/cosmos-sdk/baseapp/internal/protocompat"
"github.com/cosmos/cosmos-sdk/client/grpc/reflection"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// GRPCQueryRouter routes ABCI Query requests to GRPC handlers
type GRPCQueryRouter struct {
// routes maps query handlers used in ABCIQuery.
routes map[string]GRPCQueryHandler
// hybridHandlers maps the request name to the handler. It is a hybrid handler which seamlessly
// handles both gogo and protov2 messages.
hybridHandlers map[string][]func(ctx context.Context, req, resp protoiface.MessageV1) error
// binaryCodec is used to encode/decode binary protobuf messages.
binaryCodec codec.BinaryCodec
// cdc is the gRPC codec used by the router to correctly unmarshal messages.
cdc encoding.Codec
// serviceData contains the gRPC services and their handlers.
serviceData []serviceData
}
// serviceData represents a gRPC service, along with its handler.
type serviceData struct {
serviceDesc *grpc.ServiceDesc
handler interface{}
}
var _ gogogrpc.Server = &GRPCQueryRouter{}
// NewGRPCQueryRouter creates a new GRPCQueryRouter
func NewGRPCQueryRouter() *GRPCQueryRouter {
return &GRPCQueryRouter{
routes: map[string]GRPCQueryHandler{},
hybridHandlers: map[string][]func(ctx context.Context, req, resp protoiface.MessageV1) error{},
}
}
// GRPCQueryHandler defines a function type which handles ABCI Query requests
// using gRPC
type GRPCQueryHandler = func(ctx sdk.Context, req *abci.RequestQuery) (*abci.ResponseQuery, error)
// Route returns the GRPCQueryHandler for a given query route path or nil
// if not found
func (qrt *GRPCQueryRouter) Route(path string) GRPCQueryHandler {
handler, found := qrt.routes[path]
if !found {
return nil
}
return handler
}
// RegisterService implements the gRPC Server.RegisterService method. sd is a gRPC
// service description, handler is an object which implements that gRPC service/
//
// This functions PANICS:
// - if a protobuf service is registered twice.
func (qrt *GRPCQueryRouter) RegisterService(sd *grpc.ServiceDesc, handler interface{}) {
// adds a top-level query handler based on the gRPC service name
for _, method := range sd.Methods {
err := qrt.registerABCIQueryHandler(sd, method, handler)
if err != nil {
panic(err)
}
err = qrt.registerHybridHandler(sd, method, handler)
if err != nil {
panic(err)
}
}
qrt.serviceData = append(qrt.serviceData, serviceData{
serviceDesc: sd,
handler: handler,
})
}
func (qrt *GRPCQueryRouter) registerABCIQueryHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) error {
fqName := fmt.Sprintf("/%s/%s", sd.ServiceName, method.MethodName)
methodHandler := method.Handler
// Check that each service is only registered once. If a service is
// registered more than once, then we should error. Since we can't
// return an error (`Server.RegisterService` interface restriction) we
// panic (at startup).
_, found := qrt.routes[fqName]
if found {
return fmt.Errorf(
"gRPC query service %s has already been registered. Please make sure to only register each service once. "+
"This usually means that there are conflicting modules registering the same gRPC query service",
fqName,
)
}
qrt.routes[fqName] = func(ctx sdk.Context, req *abci.RequestQuery) (*abci.ResponseQuery, error) {
// call the method handler from the service description with the handler object,
// a wrapped sdk.Context with proto-unmarshaled data from the ABCI request data
res, err := methodHandler(handler, ctx, func(i interface{}) error {
return qrt.cdc.Unmarshal(req.Data, i)
}, nil)
if err != nil {
return nil, err
}
// proto marshal the result bytes
var resBytes []byte
resBytes, err = qrt.cdc.Marshal(res)
if err != nil {
return nil, err
}
// return the result bytes as the response value
return &abci.ResponseQuery{
Height: req.Height,
Value: resBytes,
}, nil
}
return nil
}
func (qrt *GRPCQueryRouter) HybridHandlerByRequestName(name string) []func(ctx context.Context, req, resp protoiface.MessageV1) error {
return qrt.hybridHandlers[name]
}
func (qrt *GRPCQueryRouter) registerHybridHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) error {
// extract message name from method descriptor
inputName, err := protocompat.RequestFullNameFromMethodDesc(sd, method)
if err != nil {
return err
}
methodHandler, err := protocompat.MakeHybridHandler(qrt.binaryCodec, sd, method, handler)
if err != nil {
return err
}
qrt.hybridHandlers[string(inputName)] = append(qrt.hybridHandlers[string(inputName)], methodHandler)
return nil
}
// SetInterfaceRegistry sets the interface registry for the router. This will
// also register the interface reflection gRPC service.
func (qrt *GRPCQueryRouter) SetInterfaceRegistry(interfaceRegistry codectypes.InterfaceRegistry) {
// instantiate the codec
qrt.cdc = codec.NewProtoCodec(interfaceRegistry).GRPCCodec()
qrt.binaryCodec = codec.NewProtoCodec(interfaceRegistry)
// Once we have an interface registry, we can register the interface
// registry reflection gRPC service.
reflection.RegisterReflectionServiceServer(qrt, reflection.NewReflectionServiceServer(interfaceRegistry))
}
package baseapp
import (
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
// SimCheck defines a CheckTx helper function that used in tests and simulations.
func (app *BaseApp) SimCheck(txEncoder sdk.TxEncoder, tx sdk.Tx) (sdk.GasInfo, *sdk.Result, error) {
// runTx expects tx bytes as argument, so we encode the tx argument into
// bytes. Note that runTx will actually decode those bytes again. But since
// this helper is only used in tests/simulation, it's fine.
bz, err := txEncoder(tx)
if err != nil {
return sdk.GasInfo{}, nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "%s", err)
}
gasInfo, result, _, err := app.runTx(execModeCheck, bz)
return gasInfo, result, err
}
// Simulate executes a tx in simulate mode to get result and gas info.
func (app *BaseApp) Simulate(txBytes []byte) (sdk.GasInfo, *sdk.Result, error) {
gasInfo, result, _, err := app.runTx(execModeSimulate, txBytes)
return gasInfo, result, err
}
func (app *BaseApp) SimDeliver(txEncoder sdk.TxEncoder, tx sdk.Tx) (sdk.GasInfo, *sdk.Result, error) {
// See comment for Check().
bz, err := txEncoder(tx)
if err != nil {
return sdk.GasInfo{}, nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "%s", err)
}
gasInfo, result, _, err := app.runTx(execModeFinalize, bz)
return gasInfo, result, err
}
func (app *BaseApp) SimTxFinalizeBlock(txEncoder sdk.TxEncoder, tx sdk.Tx) (sdk.GasInfo, *sdk.Result, error) {
// See comment for Check().
bz, err := txEncoder(tx)
if err != nil {
return sdk.GasInfo{}, nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "%s", err)
}
gasInfo, result, _, err := app.runTx(execModeFinalize, bz)
return gasInfo, result, err
}
// NewContextLegacy returns a new sdk.Context with the provided header
func (app *BaseApp) NewContextLegacy(isCheckTx bool, header cmtproto.Header) sdk.Context {
if isCheckTx {
return sdk.NewContext(app.checkState.ms, header, true, app.logger).
WithMinGasPrices(app.minGasPrices)
}
return sdk.NewContext(app.finalizeBlockState.ms, header, false, app.logger)
}
// NewContext returns a new sdk.Context with a empty header
func (app *BaseApp) NewContext(isCheckTx bool) sdk.Context {
return app.NewContextLegacy(isCheckTx, cmtproto.Header{})
}
func (app *BaseApp) NewUncachedContext(isCheckTx bool, header cmtproto.Header) sdk.Context {
return sdk.NewContext(app.cms, header, isCheckTx, app.logger)
}
func (app *BaseApp) GetContextForFinalizeBlock(txBytes []byte) sdk.Context {
return app.getContextForTx(execModeFinalize, txBytes)
}
func (app *BaseApp) GetContextForCheckTx(txBytes []byte) sdk.Context {
return app.getContextForTx(execModeCheck, txBytes)
}
package codec
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
cmttypes "github.com/cometbft/cometbft/types"
amino "github.com/tendermint/go-amino"
"github.com/cosmos/cosmos-sdk/codec/types"
)
// LegacyAmino defines a wrapper for an Amino codec that properly
// handles protobuf types with Any's. Deprecated.
type LegacyAmino struct {
Amino *amino.Codec
}
func (cdc *LegacyAmino) Seal() {
cdc.Amino.Seal()
}
func NewLegacyAmino() *LegacyAmino {
return &LegacyAmino{amino.NewCodec()}
}
// RegisterEvidences registers CometBFT evidence types with the provided Amino
// codec.
func RegisterEvidences(cdc *LegacyAmino) {
cdc.Amino.RegisterInterface((*cmttypes.Evidence)(nil), nil)
cdc.Amino.RegisterConcrete(&cmttypes.DuplicateVoteEvidence{}, "tendermint/DuplicateVoteEvidence", nil)
}
// MarshalJSONIndent provides a utility for indented JSON encoding of an object
// via an Amino codec. It returns an error if it cannot serialize or indent as
// JSON.
func MarshalJSONIndent(cdc *LegacyAmino, obj interface{}) ([]byte, error) {
bz, err := cdc.MarshalJSON(obj)
if err != nil {
return nil, err
}
var out bytes.Buffer
if err = json.Indent(&out, bz, "", " "); err != nil {
return nil, err
}
return out.Bytes(), nil
}
// MustMarshalJSONIndent executes MarshalJSONIndent except it panics upon failure.
func MustMarshalJSONIndent(cdc *LegacyAmino, obj interface{}) []byte {
bz, err := MarshalJSONIndent(cdc, obj)
if err != nil {
panic(fmt.Sprintf("failed to marshal JSON: %s", err))
}
return bz
}
func (cdc *LegacyAmino) marshalAnys(o interface{}) error {
return types.UnpackInterfaces(o, types.AminoPacker{Cdc: cdc.Amino})
}
func (cdc *LegacyAmino) unmarshalAnys(o interface{}) error {
return types.UnpackInterfaces(o, types.AminoUnpacker{Cdc: cdc.Amino})
}
func (cdc *LegacyAmino) jsonMarshalAnys(o interface{}) error {
return types.UnpackInterfaces(o, types.AminoJSONPacker{Cdc: cdc.Amino})
}
func (cdc *LegacyAmino) jsonUnmarshalAnys(o interface{}) error {
return types.UnpackInterfaces(o, types.AminoJSONUnpacker{Cdc: cdc.Amino})
}
func (cdc *LegacyAmino) Marshal(o interface{}) ([]byte, error) {
err := cdc.marshalAnys(o)
if err != nil {
return nil, err
}
return cdc.Amino.MarshalBinaryBare(o)
}
func (cdc *LegacyAmino) MustMarshal(o interface{}) []byte {
bz, err := cdc.Marshal(o)
if err != nil {
panic(err)
}
return bz
}
func (cdc *LegacyAmino) MarshalLengthPrefixed(o interface{}) ([]byte, error) {
err := cdc.marshalAnys(o)
if err != nil {
return nil, err
}
return cdc.Amino.MarshalBinaryLengthPrefixed(o)
}
func (cdc *LegacyAmino) MustMarshalLengthPrefixed(o interface{}) []byte {
bz, err := cdc.MarshalLengthPrefixed(o)
if err != nil {
panic(err)
}
return bz
}
func (cdc *LegacyAmino) Unmarshal(bz []byte, ptr interface{}) error {
err := cdc.Amino.UnmarshalBinaryBare(bz, ptr)
if err != nil {
return err
}
return cdc.unmarshalAnys(ptr)
}
func (cdc *LegacyAmino) MustUnmarshal(bz []byte, ptr interface{}) {
err := cdc.Unmarshal(bz, ptr)
if err != nil {
panic(err)
}
}
func (cdc *LegacyAmino) UnmarshalLengthPrefixed(bz []byte, ptr interface{}) error {
err := cdc.Amino.UnmarshalBinaryLengthPrefixed(bz, ptr)
if err != nil {
return err
}
return cdc.unmarshalAnys(ptr)
}
func (cdc *LegacyAmino) MustUnmarshalLengthPrefixed(bz []byte, ptr interface{}) {
err := cdc.UnmarshalLengthPrefixed(bz, ptr)
if err != nil {
panic(err)
}
}
// MarshalJSON implements codec.Codec interface
func (cdc *LegacyAmino) MarshalJSON(o interface{}) ([]byte, error) {
err := cdc.jsonMarshalAnys(o)
if err != nil {
return nil, err
}
return cdc.Amino.MarshalJSON(o)
}
func (cdc *LegacyAmino) MustMarshalJSON(o interface{}) []byte {
bz, err := cdc.MarshalJSON(o)
if err != nil {
panic(err)
}
return bz
}
// UnmarshalJSON implements codec.Codec interface
func (cdc *LegacyAmino) UnmarshalJSON(bz []byte, ptr interface{}) error {
err := cdc.Amino.UnmarshalJSON(bz, ptr)
if err != nil {
return err
}
return cdc.jsonUnmarshalAnys(ptr)
}
func (cdc *LegacyAmino) MustUnmarshalJSON(bz []byte, ptr interface{}) {
err := cdc.UnmarshalJSON(bz, ptr)
if err != nil {
panic(err)
}
}
func (*LegacyAmino) UnpackAny(*types.Any, interface{}) error {
return errors.New("AminoCodec can't handle unpack protobuf Any's")
}
func (cdc *LegacyAmino) RegisterInterface(ptr interface{}, iopts *amino.InterfaceOptions) {
cdc.Amino.RegisterInterface(ptr, iopts)
}
func (cdc *LegacyAmino) RegisterConcrete(o interface{}, name string, copts *amino.ConcreteOptions) {
cdc.Amino.RegisterConcrete(o, name, copts)
}
func (cdc *LegacyAmino) MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
err := cdc.jsonMarshalAnys(o)
if err != nil {
panic(err)
}
return cdc.Amino.MarshalJSONIndent(o, prefix, indent)
}
func (cdc *LegacyAmino) PrintTypes(out io.Writer) error {
return cdc.Amino.PrintTypes(out)
}
package codec
import (
"encoding/binary"
"errors"
"fmt"
"strings"
"github.com/cosmos/cosmos-proto/anyutil"
"github.com/cosmos/gogoproto/jsonpb"
gogoproto "github.com/cosmos/gogoproto/proto"
"google.golang.org/grpc/encoding"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/dynamicpb"
"google.golang.org/protobuf/types/known/anypb"
"cosmossdk.io/x/tx/signing/aminojson"
"github.com/cosmos/cosmos-sdk/codec/types"
)
// ProtoCodecMarshaler defines an interface for codecs that utilize Protobuf for both
// binary and JSON encoding.
// Deprecated: Use Codec instead.
type ProtoCodecMarshaler interface {
Codec
}
// ProtoCodec defines a codec that utilizes Protobuf for both binary and JSON
// encoding.
type ProtoCodec struct {
interfaceRegistry types.InterfaceRegistry
}
var _ Codec = (*ProtoCodec)(nil)
// NewProtoCodec returns a reference to a new ProtoCodec
func NewProtoCodec(interfaceRegistry types.InterfaceRegistry) *ProtoCodec {
return &ProtoCodec{
interfaceRegistry: interfaceRegistry,
}
}
// Marshal implements BinaryMarshaler.Marshal method.
// NOTE: this function must be used with a concrete type which
// implements proto.Message. For interface please use the codec.MarshalInterface
func (pc *ProtoCodec) Marshal(o gogoproto.Message) ([]byte, error) {
// Size() check can catch the typed nil value.
if o == nil || gogoproto.Size(o) == 0 {
// return empty bytes instead of nil, because nil has special meaning in places like store.Set
return []byte{}, nil
}
return gogoproto.Marshal(o)
}
// MustMarshal implements BinaryMarshaler.MustMarshal method.
// NOTE: this function must be used with a concrete type which
// implements proto.Message. For interface please use the codec.MarshalInterface
func (pc *ProtoCodec) MustMarshal(o gogoproto.Message) []byte {
bz, err := pc.Marshal(o)
if err != nil {
panic(err)
}
return bz
}
// MarshalLengthPrefixed implements BinaryMarshaler.MarshalLengthPrefixed method.
func (pc *ProtoCodec) MarshalLengthPrefixed(o gogoproto.Message) ([]byte, error) {
bz, err := pc.Marshal(o)
if err != nil {
return nil, err
}
var sizeBuf [binary.MaxVarintLen64]byte
n := binary.PutUvarint(sizeBuf[:], uint64(len(bz)))
return append(sizeBuf[:n], bz...), nil
}
// MustMarshalLengthPrefixed implements BinaryMarshaler.MustMarshalLengthPrefixed method.
func (pc *ProtoCodec) MustMarshalLengthPrefixed(o gogoproto.Message) []byte {
bz, err := pc.MarshalLengthPrefixed(o)
if err != nil {
panic(err)
}
return bz
}
// Unmarshal implements BinaryMarshaler.Unmarshal method.
// NOTE: this function must be used with a concrete type which
// implements proto.Message. For interface please use the codec.UnmarshalInterface
func (pc *ProtoCodec) Unmarshal(bz []byte, ptr gogoproto.Message) error {
err := gogoproto.Unmarshal(bz, ptr)
if err != nil {
return err
}
err = types.UnpackInterfaces(ptr, pc.interfaceRegistry)
if err != nil {
return err
}
return nil
}
// MustUnmarshal implements BinaryMarshaler.MustUnmarshal method.
// NOTE: this function must be used with a concrete type which
// implements proto.Message. For interface please use the codec.UnmarshalInterface
func (pc *ProtoCodec) MustUnmarshal(bz []byte, ptr gogoproto.Message) {
if err := pc.Unmarshal(bz, ptr); err != nil {
panic(err)
}
}
// UnmarshalLengthPrefixed implements BinaryMarshaler.UnmarshalLengthPrefixed method.
func (pc *ProtoCodec) UnmarshalLengthPrefixed(bz []byte, ptr gogoproto.Message) error {
size, n := binary.Uvarint(bz)
if n < 0 {
return fmt.Errorf("invalid number of bytes read from length-prefixed encoding: %d", n)
}
if size > uint64(len(bz)-n) {
return fmt.Errorf("not enough bytes to read; want: %v, got: %v", size, len(bz)-n)
} else if size < uint64(len(bz)-n) {
return fmt.Errorf("too many bytes to read; want: %v, got: %v", size, len(bz)-n)
}
bz = bz[n:]
return pc.Unmarshal(bz, ptr)
}
// MustUnmarshalLengthPrefixed implements BinaryMarshaler.MustUnmarshalLengthPrefixed method.
func (pc *ProtoCodec) MustUnmarshalLengthPrefixed(bz []byte, ptr gogoproto.Message) {
if err := pc.UnmarshalLengthPrefixed(bz, ptr); err != nil {
panic(err)
}
}
// MarshalJSON implements JSONCodec.MarshalJSON method,
// it marshals to JSON using proto codec.
// NOTE: this function must be used with a concrete type which
// implements proto.Message. For interface please use the codec.MarshalInterfaceJSON
func (pc *ProtoCodec) MarshalJSON(o gogoproto.Message) ([]byte, error) { //nolint:stdmethods // we don't want to implement Marshaler interface
if o == nil {
return nil, fmt.Errorf("cannot protobuf JSON encode nil")
}
return ProtoMarshalJSON(o, pc.interfaceRegistry)
}
// MustMarshalJSON implements JSONCodec.MustMarshalJSON method,
// it executes MarshalJSON except it panics upon failure.
// NOTE: this function must be used with a concrete type which
// implements proto.Message. For interface please use the codec.MarshalInterfaceJSON
func (pc *ProtoCodec) MustMarshalJSON(o gogoproto.Message) []byte {
bz, err := pc.MarshalJSON(o)
if err != nil {
panic(err)
}
return bz
}
// MarshalAminoJSON provides aminojson.Encoder compatibility for gogoproto messages.
// x/tx/signing/aminojson cannot marshal gogoproto messages directly since this type does not implement
// the standard library google.golang.org/protobuf/proto.Message.
// We convert gogo types to dynamicpb messages and then marshal that directly to amino JSON.
func (pc *ProtoCodec) MarshalAminoJSON(msg gogoproto.Message) ([]byte, error) {
encoder := aminojson.NewEncoder(aminojson.EncoderOptions{FileResolver: pc.interfaceRegistry})
gogoBytes, err := gogoproto.Marshal(msg)
if err != nil {
return nil, err
}
var protoMsg protoreflect.ProtoMessage
typ, err := protoregistry.GlobalTypes.FindMessageByURL(fmt.Sprintf("/%s", gogoproto.MessageName(msg)))
if typ != nil && err != nil {
protoMsg = typ.New().Interface()
} else {
desc, err := pc.interfaceRegistry.FindDescriptorByName(protoreflect.FullName(gogoproto.MessageName(msg)))
if err != nil {
return nil, err
}
dynamicMsgType := dynamicpb.NewMessageType(desc.(protoreflect.MessageDescriptor))
protoMsg = dynamicMsgType.New().Interface()
}
err = proto.Unmarshal(gogoBytes, protoMsg)
if err != nil {
return nil, err
}
return encoder.Marshal(protoMsg)
}
// UnmarshalJSON implements JSONCodec.UnmarshalJSON method,
// it unmarshals from JSON using proto codec.
// NOTE: this function must be used with a concrete type which
// implements proto.Message. For interface please use the codec.UnmarshalInterfaceJSON
func (pc *ProtoCodec) UnmarshalJSON(bz []byte, ptr gogoproto.Message) error {
if ptr == nil {
return fmt.Errorf("cannot protobuf JSON decode unsupported type: %T", ptr)
}
unmarshaler := jsonpb.Unmarshaler{AnyResolver: pc.interfaceRegistry}
err := unmarshaler.Unmarshal(strings.NewReader(string(bz)), ptr)
if err != nil {
return err
}
return types.UnpackInterfaces(ptr, pc.interfaceRegistry)
}
// MustUnmarshalJSON implements JSONCodec.MustUnmarshalJSON method,
// it executes UnmarshalJSON except it panics upon failure.
// NOTE: this function must be used with a concrete type which
// implements proto.Message. For interface please use the codec.UnmarshalInterfaceJSON
func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr gogoproto.Message) {
if err := pc.UnmarshalJSON(bz, ptr); err != nil {
panic(err)
}
}
// MarshalInterface is a convenience function for proto marshaling interfaces. It packs
// the provided value, which must be an interface, in an Any and then marshals it to bytes.
// NOTE: to marshal a concrete type, you should use Marshal instead
func (pc *ProtoCodec) MarshalInterface(i gogoproto.Message) ([]byte, error) {
if err := assertNotNil(i); err != nil {
return nil, err
}
any, err := types.NewAnyWithValue(i)
if err != nil {
return nil, err
}
err = pc.interfaceRegistry.EnsureRegistered(i)
if err != nil {
return nil, err
}
return pc.Marshal(any)
}
// UnmarshalInterface is a convenience function for proto unmarshaling interfaces. It
// unmarshals an Any from bz bytes and then unpacks it to the `ptr`, which must
// be a pointer to a non empty interface with registered implementations.
// NOTE: to unmarshal a concrete type, you should use Unmarshal instead
//
// Example:
//
// var x MyInterface
// err := cdc.UnmarshalInterface(bz, &x)
func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error {
any := &types.Any{}
err := pc.Unmarshal(bz, any)
if err != nil {
return err
}
return pc.UnpackAny(any, ptr)
}
// MarshalInterfaceJSON is a convenience function for proto marshaling interfaces. It
// packs the provided value in an Any and then marshals it to bytes.
// NOTE: to marshal a concrete type, you should use MarshalJSON instead
func (pc *ProtoCodec) MarshalInterfaceJSON(x gogoproto.Message) ([]byte, error) {
any, err := types.NewAnyWithValue(x)
if err != nil {
return nil, err
}
return pc.MarshalJSON(any)
}
// UnmarshalInterfaceJSON is a convenience function for proto unmarshaling interfaces.
// It unmarshals an Any from bz bytes and then unpacks it to the `iface`, which must
// be a pointer to a non empty interface, implementing proto.Message with registered implementations.
// NOTE: to unmarshal a concrete type, you should use UnmarshalJSON instead
//
// Example:
//
// var x MyInterface // must implement proto.Message
// err := cdc.UnmarshalInterfaceJSON(&x, bz)
func (pc *ProtoCodec) UnmarshalInterfaceJSON(bz []byte, iface interface{}) error {
any := &types.Any{}
err := pc.UnmarshalJSON(bz, any)
if err != nil {
return err
}
return pc.UnpackAny(any, iface)
}
// UnpackAny implements AnyUnpacker.UnpackAny method,
// it unpacks the value in any to the interface pointer passed in as
// iface.
func (pc *ProtoCodec) UnpackAny(any *types.Any, iface interface{}) error {
return pc.interfaceRegistry.UnpackAny(any, iface)
}
// InterfaceRegistry returns InterfaceRegistry
func (pc *ProtoCodec) InterfaceRegistry() types.InterfaceRegistry {
return pc.interfaceRegistry
}
func (pc ProtoCodec) GetMsgAnySigners(msg *types.Any) ([][]byte, proto.Message, error) {
msgv2, err := anyutil.Unpack(&anypb.Any{
TypeUrl: msg.TypeUrl,
Value: msg.Value,
}, pc.interfaceRegistry, nil)
if err != nil {
return nil, nil, err
}
signers, err := pc.interfaceRegistry.SigningContext().GetSigners(msgv2)
return signers, msgv2, err
}
func (pc *ProtoCodec) GetMsgV2Signers(msg proto.Message) ([][]byte, error) {
return pc.interfaceRegistry.SigningContext().GetSigners(msg)
}
func (pc *ProtoCodec) GetMsgV1Signers(msg gogoproto.Message) ([][]byte, proto.Message, error) {
if msgV2, ok := msg.(proto.Message); ok {
signers, err := pc.interfaceRegistry.SigningContext().GetSigners(msgV2)
return signers, msgV2, err
}
a, err := types.NewAnyWithValue(msg)
if err != nil {
return nil, nil, err
}
return pc.GetMsgAnySigners(a)
}
// GRPCCodec returns the gRPC Codec for this specific ProtoCodec
func (pc *ProtoCodec) GRPCCodec() encoding.Codec {
return &grpcProtoCodec{cdc: pc}
}
func (pc *ProtoCodec) mustEmbedCodec() {}
var errUnknownProtoType = errors.New("codec: unknown proto type") // sentinel error
// grpcProtoCodec is the implementation of the gRPC proto codec.
type grpcProtoCodec struct {
cdc *ProtoCodec
}
func (g grpcProtoCodec) Marshal(v interface{}) ([]byte, error) {
switch m := v.(type) {
case proto.Message:
protov2MarshalOpts := proto.MarshalOptions{Deterministic: true}
return protov2MarshalOpts.Marshal(m)
case gogoproto.Message:
return g.cdc.Marshal(m)
default:
return nil, fmt.Errorf("%w: cannot marshal type %T", errUnknownProtoType, v)
}
}
func (g grpcProtoCodec) Unmarshal(data []byte, v interface{}) error {
switch m := v.(type) {
case proto.Message:
return proto.Unmarshal(data, m)
case gogoproto.Message:
return g.cdc.Unmarshal(data, m)
default:
return fmt.Errorf("%w: cannot unmarshal type %T", errUnknownProtoType, v)
}
}
func (g grpcProtoCodec) Name() string {
return "cosmos-sdk-grpc-codec"
}
func assertNotNil(i interface{}) error {
if i == nil {
return errors.New("can't marshal <nil> value")
}
return nil
}
package unknownproto
import (
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"reflect"
"strings"
"sync"
"github.com/cosmos/gogoproto/jsonpb"
"github.com/cosmos/gogoproto/proto"
"google.golang.org/protobuf/encoding/protowire"
protov2 "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"github.com/cosmos/cosmos-sdk/codec/types"
)
const bit11NonCritical = 1 << 10
type descriptorIface interface {
Descriptor() ([]byte, []int)
}
// RejectUnknownFieldsStrict rejects any bytes bz with an error that has unknown fields for the provided proto.Message type.
// This function traverses inside of messages nested via google.protobuf.Any. It does not do any deserialization of the proto.Message.
// An AnyResolver must be provided for traversing inside google.protobuf.Any's.
func RejectUnknownFieldsStrict(bz []byte, msg proto.Message, resolver jsonpb.AnyResolver) error {
_, err := RejectUnknownFields(bz, msg, false, resolver)
return err
}
// RejectUnknownFields rejects any bytes bz with an error that has unknown fields for the provided proto.Message type with an
// option to allow non-critical fields (specified as those fields with bit 11) to pass through. In either case, the
// hasUnknownNonCriticals will be set to true if non-critical fields were encountered during traversal. This flag can be
// used to treat a message with non-critical field different in different security contexts (such as transaction signing).
// This function traverses inside of messages nested via google.protobuf.Any. It does not do any deserialization of the proto.Message.
// An AnyResolver must be provided for traversing inside google.protobuf.Any's.
func RejectUnknownFields(bz []byte, msg proto.Message, allowUnknownNonCriticals bool, resolver jsonpb.AnyResolver) (hasUnknownNonCriticals bool, err error) {
if len(bz) == 0 {
return hasUnknownNonCriticals, nil
}
desc, ok := msg.(descriptorIface)
if !ok {
return hasUnknownNonCriticals, fmt.Errorf("%T does not have a Descriptor() method", msg)
}
fieldDescProtoFromTagNum, _, err := getDescriptorInfo(desc, msg)
if err != nil {
return hasUnknownNonCriticals, err
}
for len(bz) > 0 {
tagNum, wireType, m := protowire.ConsumeTag(bz)
if m < 0 {
return hasUnknownNonCriticals, errors.New("invalid length")
}
fieldDescProto, ok := fieldDescProtoFromTagNum[int32(tagNum)]
switch {
case ok:
// Assert that the wireTypes match.
if !canEncodeType(wireType, fieldDescProto.GetType()) {
return hasUnknownNonCriticals, &errMismatchedWireType{
Type: reflect.ValueOf(msg).Type().String(),
TagNum: tagNum,
GotWireType: wireType,
WantWireType: toProtowireType(fieldDescProto.GetType()),
}
}
default:
isCriticalField := tagNum&bit11NonCritical == 0
if !isCriticalField {
hasUnknownNonCriticals = true
}
if isCriticalField || !allowUnknownNonCriticals {
// The tag is critical, so report it.
return hasUnknownNonCriticals, &errUnknownField{
Type: reflect.ValueOf(msg).Type().String(),
TagNum: tagNum,
WireType: wireType,
}
}
}
// Skip over the bytes that store fieldNumber and wireType bytes.
bz = bz[m:]
n := protowire.ConsumeFieldValue(tagNum, wireType, bz)
if n < 0 {
err = fmt.Errorf("could not consume field value for tagNum: %d, wireType: %q; %w",
tagNum, wireTypeToString(wireType), protowire.ParseError(n))
return hasUnknownNonCriticals, err
}
fieldBytes := bz[:n]
bz = bz[n:]
// An unknown but non-critical field or just a scalar type (aka *INT and BYTES like).
if fieldDescProto == nil || isScalar(fieldDescProto) {
continue
}
protoMessageName := fieldDescProto.GetTypeName()
if protoMessageName == "" {
switch typ := fieldDescProto.GetType(); typ {
case descriptorpb.FieldDescriptorProto_TYPE_STRING, descriptorpb.FieldDescriptorProto_TYPE_BYTES:
// At this point only TYPE_STRING is expected to be unregistered, since FieldDescriptorProto.IsScalar() returns false for
// TYPE_BYTES and TYPE_STRING as per
// https://github.com/cosmos/gogoproto/blob/5628607bb4c51c3157aacc3a50f0ab707582b805/protoc-gen-gogo/descriptor/descriptor.go#L95-L118
default:
return hasUnknownNonCriticals, fmt.Errorf("failed to get typename for message of type %v, can only be TYPE_STRING or TYPE_BYTES", typ)
}
continue
}
// Let's recursively traverse and typecheck the field.
// consume length prefix of nested message
_, o := protowire.ConsumeVarint(fieldBytes)
fieldBytes = fieldBytes[o:]
var msg proto.Message
var err error
if protoMessageName == ".google.protobuf.Any" {
// Firstly typecheck types.Any to ensure nothing snuck in.
hasUnknownNonCriticalsChild, err := RejectUnknownFields(fieldBytes, (*types.Any)(nil), allowUnknownNonCriticals, resolver)
hasUnknownNonCriticals = hasUnknownNonCriticals || hasUnknownNonCriticalsChild
if err != nil {
return hasUnknownNonCriticals, err
}
// And finally we can extract the TypeURL containing the protoMessageName.
any := new(types.Any)
if err := proto.Unmarshal(fieldBytes, any); err != nil {
return hasUnknownNonCriticals, err
}
protoMessageName = any.TypeUrl
fieldBytes = any.Value
msg, err = resolver.Resolve(protoMessageName)
if err != nil {
return hasUnknownNonCriticals, err
}
} else {
msg, err = protoMessageForTypeName(protoMessageName[1:])
if err != nil {
return hasUnknownNonCriticals, err
}
}
hasUnknownNonCriticalsChild, err := RejectUnknownFields(fieldBytes, msg, allowUnknownNonCriticals, resolver)
hasUnknownNonCriticals = hasUnknownNonCriticals || hasUnknownNonCriticalsChild
if err != nil {
return hasUnknownNonCriticals, err
}
}
return hasUnknownNonCriticals, nil
}
var (
protoMessageForTypeNameMu sync.RWMutex
protoMessageForTypeNameCache = make(map[string]proto.Message)
)
// protoMessageForTypeName takes in a fully qualified name e.g. testdata.TestVersionFD1
// and returns a corresponding empty protobuf message that serves the prototype for typechecking.
func protoMessageForTypeName(protoMessageName string) (proto.Message, error) {
protoMessageForTypeNameMu.RLock()
msg, ok := protoMessageForTypeNameCache[protoMessageName]
protoMessageForTypeNameMu.RUnlock()
if ok {
return msg, nil
}
concreteGoType := proto.MessageType(protoMessageName)
if concreteGoType == nil {
return nil, fmt.Errorf("failed to retrieve the message of type %q", protoMessageName)
}
value := reflect.New(concreteGoType).Elem()
msg, ok = value.Interface().(proto.Message)
if !ok {
return nil, fmt.Errorf("%q does not implement proto.Message", protoMessageName)
}
// Now cache it.
protoMessageForTypeNameMu.Lock()
protoMessageForTypeNameCache[protoMessageName] = msg
protoMessageForTypeNameMu.Unlock()
return msg, nil
}
// checks is a mapping of protowire.Type to supported descriptor.FieldDescriptorProto_Type.
// it is implemented this way so as to have constant time lookups and avoid the overhead
// from O(n) walking of switch. The change to using this mapping boosts throughput by about 200%.
var checks = [...]map[descriptorpb.FieldDescriptorProto_Type]bool{
// "0 Varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum"
0: {
descriptorpb.FieldDescriptorProto_TYPE_INT32: true,
descriptorpb.FieldDescriptorProto_TYPE_INT64: true,
descriptorpb.FieldDescriptorProto_TYPE_UINT32: true,
descriptorpb.FieldDescriptorProto_TYPE_UINT64: true,
descriptorpb.FieldDescriptorProto_TYPE_SINT32: true,
descriptorpb.FieldDescriptorProto_TYPE_SINT64: true,
descriptorpb.FieldDescriptorProto_TYPE_BOOL: true,
descriptorpb.FieldDescriptorProto_TYPE_ENUM: true,
},
// "1 64-bit: fixed64, sfixed64, double"
1: {
descriptorpb.FieldDescriptorProto_TYPE_FIXED64: true,
descriptorpb.FieldDescriptorProto_TYPE_SFIXED64: true,
descriptorpb.FieldDescriptorProto_TYPE_DOUBLE: true,
},
// "2 Length-delimited: string, bytes, embedded messages, packed repeated fields"
2: {
descriptorpb.FieldDescriptorProto_TYPE_STRING: true,
descriptorpb.FieldDescriptorProto_TYPE_BYTES: true,
descriptorpb.FieldDescriptorProto_TYPE_MESSAGE: true,
// The following types can be packed repeated.
// ref: "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire types) can be declared "packed"."
// ref: https://developers.google.com/protocol-buffers/docs/encoding#packed
descriptorpb.FieldDescriptorProto_TYPE_INT32: true,
descriptorpb.FieldDescriptorProto_TYPE_INT64: true,
descriptorpb.FieldDescriptorProto_TYPE_UINT32: true,
descriptorpb.FieldDescriptorProto_TYPE_UINT64: true,
descriptorpb.FieldDescriptorProto_TYPE_SINT32: true,
descriptorpb.FieldDescriptorProto_TYPE_SINT64: true,
descriptorpb.FieldDescriptorProto_TYPE_BOOL: true,
descriptorpb.FieldDescriptorProto_TYPE_ENUM: true,
descriptorpb.FieldDescriptorProto_TYPE_FIXED64: true,
descriptorpb.FieldDescriptorProto_TYPE_SFIXED64: true,
descriptorpb.FieldDescriptorProto_TYPE_DOUBLE: true,
},
// "3 Start group: groups (deprecated)"
3: {
descriptorpb.FieldDescriptorProto_TYPE_GROUP: true,
},
// "4 End group: groups (deprecated)"
4: {
descriptorpb.FieldDescriptorProto_TYPE_GROUP: true,
},
// "5 32-bit: fixed32, sfixed32, float"
5: {
descriptorpb.FieldDescriptorProto_TYPE_FIXED32: true,
descriptorpb.FieldDescriptorProto_TYPE_SFIXED32: true,
descriptorpb.FieldDescriptorProto_TYPE_FLOAT: true,
},
}
// canEncodeType returns true if the wireType is suitable for encoding the descriptor type.
// See https://developers.google.com/protocol-buffers/docs/encoding#structure.
func canEncodeType(wireType protowire.Type, descType descriptorpb.FieldDescriptorProto_Type) bool {
if iwt := int(wireType); iwt < 0 || iwt >= len(checks) {
return false
}
return checks[wireType][descType]
}
// errMismatchedWireType describes a mismatch between
// expected and got wireTypes for a specific tag number.
type errMismatchedWireType struct {
Type string
GotWireType protowire.Type
WantWireType protowire.Type
TagNum protowire.Number
}
// String implements fmt.Stringer.
func (mwt *errMismatchedWireType) String() string {
return fmt.Sprintf("Mismatched %q: {TagNum: %d, GotWireType: %q != WantWireType: %q}",
mwt.Type, mwt.TagNum, wireTypeToString(mwt.GotWireType), wireTypeToString(mwt.WantWireType))
}
// Error implements the error interface.
func (mwt *errMismatchedWireType) Error() string {
return mwt.String()
}
var _ error = (*errMismatchedWireType)(nil)
func wireTypeToString(wt protowire.Type) string {
switch wt {
case 0:
return "varint"
case 1:
return "fixed64"
case 2:
return "bytes"
case 3:
return "start_group"
case 4:
return "end_group"
case 5:
return "fixed32"
default:
return fmt.Sprintf("unknown type: %d", wt)
}
}
// errUnknownField represents an error indicating that we encountered
// a field that isn't available in the target proto.Message.
type errUnknownField struct {
Type string
TagNum protowire.Number
WireType protowire.Type
}
// String implements fmt.Stringer.
func (twt *errUnknownField) String() string {
return fmt.Sprintf("errUnknownField %q: {TagNum: %d, WireType:%q}",
twt.Type, twt.TagNum, wireTypeToString(twt.WireType))
}
// Error implements the error interface.
func (twt *errUnknownField) Error() string {
return twt.String()
}
var _ error = (*errUnknownField)(nil)
var (
protoFileToDesc = make(map[string]*descriptorpb.FileDescriptorProto)
protoFileToDescMu sync.RWMutex
)
func unnestDesc(mdescs []*descriptorpb.DescriptorProto, indices []int) *descriptorpb.DescriptorProto {
mdesc := mdescs[indices[0]]
for _, index := range indices[1:] {
mdesc = mdesc.NestedType[index]
}
return mdesc
}
// Invoking descriptorpb.ForMessage(proto.Message.(Descriptor).Descriptor()) is incredibly slow
// for every single message, thus the need for a hand-rolled custom version that's performant and cacheable.
func extractFileDescMessageDesc(desc descriptorIface) (*descriptorpb.FileDescriptorProto, *descriptorpb.DescriptorProto, error) {
gzippedPb, indices := desc.Descriptor()
protoFileToDescMu.RLock()
cached, ok := protoFileToDesc[string(gzippedPb)]
protoFileToDescMu.RUnlock()
if ok {
return cached, unnestDesc(cached.MessageType, indices), nil
}
// Time to gunzip the content of the FileDescriptor and then proto unmarshal them.
gzr, err := gzip.NewReader(bytes.NewReader(gzippedPb))
if err != nil {
return nil, nil, err
}
protoBlob, err := io.ReadAll(gzr)
if err != nil {
return nil, nil, err
}
fdesc := new(descriptorpb.FileDescriptorProto)
if err := protov2.Unmarshal(protoBlob, fdesc); err != nil {
return nil, nil, err
}
// Now cache the FileDescriptor.
protoFileToDescMu.Lock()
protoFileToDesc[string(gzippedPb)] = fdesc
protoFileToDescMu.Unlock()
// Unnest the type if necessary.
return fdesc, unnestDesc(fdesc.MessageType, indices), nil
}
type descriptorMatch struct {
cache map[int32]*descriptorpb.FieldDescriptorProto
desc *descriptorpb.DescriptorProto
}
var (
descprotoCacheMu sync.RWMutex
descprotoCache = make(map[reflect.Type]*descriptorMatch)
)
// getDescriptorInfo retrieves the mapping of field numbers to their respective field descriptors.
func getDescriptorInfo(desc descriptorIface, msg proto.Message) (map[int32]*descriptorpb.FieldDescriptorProto, *descriptorpb.DescriptorProto, error) {
key := reflect.ValueOf(msg).Type()
descprotoCacheMu.RLock()
got, ok := descprotoCache[key]
descprotoCacheMu.RUnlock()
if ok {
return got.cache, got.desc, nil
}
// Now compute and cache the index.
_, md, err := extractFileDescMessageDesc(desc)
if err != nil {
return nil, nil, err
}
tagNumToTypeIndex := make(map[int32]*descriptorpb.FieldDescriptorProto)
for _, field := range md.Field {
tagNumToTypeIndex[field.GetNumber()] = field
}
descprotoCacheMu.Lock()
descprotoCache[key] = &descriptorMatch{
cache: tagNumToTypeIndex,
desc: md,
}
descprotoCacheMu.Unlock()
return tagNumToTypeIndex, md, nil
}
// DefaultAnyResolver is a default implementation of AnyResolver which uses
// the default encoding of type URLs as specified by the protobuf specification.
type DefaultAnyResolver struct{}
var _ jsonpb.AnyResolver = DefaultAnyResolver{}
// Resolve is the AnyResolver.Resolve method.
func (d DefaultAnyResolver) Resolve(typeURL string) (proto.Message, error) {
// Only the part of typeURL after the last slash is relevant.
mname := typeURL
if slash := strings.LastIndex(mname, "/"); slash >= 0 {
mname = mname[slash+1:]
}
mt := proto.MessageType(mname)
if mt == nil {
return nil, fmt.Errorf("unknown message type %q", mname)
}
return reflect.New(mt.Elem()).Interface().(proto.Message), nil
}
// toProtowireType converts a descriptorpb.FieldDescriptorProto_Type to a protowire.Type.
func toProtowireType(fieldType descriptorpb.FieldDescriptorProto_Type) protowire.Type {
switch fieldType {
// varint encoded
case descriptorpb.FieldDescriptorProto_TYPE_INT64,
descriptorpb.FieldDescriptorProto_TYPE_UINT64,
descriptorpb.FieldDescriptorProto_TYPE_INT32,
descriptorpb.FieldDescriptorProto_TYPE_UINT32,
descriptorpb.FieldDescriptorProto_TYPE_BOOL,
descriptorpb.FieldDescriptorProto_TYPE_ENUM,
descriptorpb.FieldDescriptorProto_TYPE_SINT32,
descriptorpb.FieldDescriptorProto_TYPE_SINT64:
return protowire.VarintType
// fixed64 encoded
case descriptorpb.FieldDescriptorProto_TYPE_DOUBLE,
descriptorpb.FieldDescriptorProto_TYPE_FIXED64,
descriptorpb.FieldDescriptorProto_TYPE_SFIXED64:
return protowire.Fixed64Type
// fixed32 encoded
case descriptorpb.FieldDescriptorProto_TYPE_FLOAT,
descriptorpb.FieldDescriptorProto_TYPE_FIXED32,
descriptorpb.FieldDescriptorProto_TYPE_SFIXED32:
return protowire.Fixed32Type
// bytes encoded
case descriptorpb.FieldDescriptorProto_TYPE_STRING,
descriptorpb.FieldDescriptorProto_TYPE_BYTES,
descriptorpb.FieldDescriptorProto_TYPE_MESSAGE,
descriptorpb.FieldDescriptorProto_TYPE_GROUP:
return protowire.BytesType
default:
panic(fmt.Sprintf("unknown field type %s", fieldType))
}
}
// isScalar defines whether a field is a scalar type.
// Copied from gogo/protobuf/protoc-gen-gogo
// https://github.com/gogo/protobuf/blob/b03c65ea87cdc3521ede29f62fe3ce239267c1bc/protoc-gen-gogo/descriptor/descriptor.go#L95
func isScalar(field *descriptorpb.FieldDescriptorProto) bool {
if field.Type == nil {
return false
}
switch *field.Type {
case descriptorpb.FieldDescriptorProto_TYPE_DOUBLE,
descriptorpb.FieldDescriptorProto_TYPE_FLOAT,
descriptorpb.FieldDescriptorProto_TYPE_INT64,
descriptorpb.FieldDescriptorProto_TYPE_UINT64,
descriptorpb.FieldDescriptorProto_TYPE_INT32,
descriptorpb.FieldDescriptorProto_TYPE_FIXED64,
descriptorpb.FieldDescriptorProto_TYPE_FIXED32,
descriptorpb.FieldDescriptorProto_TYPE_BOOL,
descriptorpb.FieldDescriptorProto_TYPE_UINT32,
descriptorpb.FieldDescriptorProto_TYPE_ENUM,
descriptorpb.FieldDescriptorProto_TYPE_SFIXED32,
descriptorpb.FieldDescriptorProto_TYPE_SFIXED64,
descriptorpb.FieldDescriptorProto_TYPE_SINT32,
descriptorpb.FieldDescriptorProto_TYPE_SINT64:
return true
default:
return false
}
}
package secp256k1
import (
"bytes"
"crypto/sha256"
"crypto/subtle"
"fmt"
"io"
"math/big"
"github.com/cometbft/cometbft/crypto"
secp256k1 "github.com/decred/dcrd/dcrec/secp256k1/v4"
"golang.org/x/crypto/ripemd160" //nolint: staticcheck // keep around for backwards compatibility
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/types/errors"
)
var (
_ cryptotypes.PrivKey = &PrivKey{}
_ codec.AminoMarshaler = &PrivKey{}
)
const (
PrivKeySize = 32
keyType = "secp256k1"
PrivKeyName = "tendermint/PrivKeySecp256k1"
PubKeyName = "tendermint/PubKeySecp256k1"
)
// Bytes returns the byte representation of the Private Key.
func (privKey *PrivKey) Bytes() []byte {
return privKey.Key
}
// PubKey performs the point-scalar multiplication from the privKey on the
// generator point to get the pubkey.
func (privKey *PrivKey) PubKey() cryptotypes.PubKey {
pubkeyObject := secp256k1.PrivKeyFromBytes(privKey.Key).PubKey()
pk := pubkeyObject.SerializeCompressed()
return &PubKey{Key: pk}
}
// Equals - you probably don't need to use this.
// Runs in constant time based on length of the
func (privKey *PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool {
return privKey.Type() == other.Type() && subtle.ConstantTimeCompare(privKey.Bytes(), other.Bytes()) == 1
}
func (privKey *PrivKey) Type() string {
return keyType
}
// MarshalAmino overrides Amino binary marshaling.
func (privKey PrivKey) MarshalAmino() ([]byte, error) {
return privKey.Key, nil
}
// UnmarshalAmino overrides Amino binary marshaling.
func (privKey *PrivKey) UnmarshalAmino(bz []byte) error {
if len(bz) != PrivKeySize {
return fmt.Errorf("invalid privkey size")
}
privKey.Key = bz
return nil
}
// MarshalAminoJSON overrides Amino JSON marshaling.
func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) {
// When we marshal to Amino JSON, we don't marshal the "key" field itself,
// just its contents (i.e. the key bytes).
return privKey.MarshalAmino()
}
// UnmarshalAminoJSON overrides Amino JSON marshaling.
func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error {
return privKey.UnmarshalAmino(bz)
}
// GenPrivKey generates a new ECDSA private key on curve secp256k1 private key.
// It uses OS randomness to generate the private key.
func GenPrivKey() *PrivKey {
return &PrivKey{Key: genPrivKey(crypto.CReader())}
}
// genPrivKey generates a new secp256k1 private key using the provided reader.
func genPrivKey(rand io.Reader) []byte {
var privKeyBytes [PrivKeySize]byte
d := new(big.Int)
for {
privKeyBytes = [PrivKeySize]byte{}
_, err := io.ReadFull(rand, privKeyBytes[:])
if err != nil {
panic(err)
}
d.SetBytes(privKeyBytes[:])
// break if we found a valid point (i.e. > 0 and < N == curverOrder)
isValidFieldElement := 0 < d.Sign() && d.Cmp(secp256k1.S256().N) < 0
if isValidFieldElement {
break
}
}
return privKeyBytes[:]
}
var one = new(big.Int).SetInt64(1)
// GenPrivKeyFromSecret hashes the secret with SHA2, and uses
// that 32 byte output to create the private key.
//
// It makes sure the private key is a valid field element by setting:
//
// c = sha256(secret)
// k = (c mod (n − 1)) + 1, where n = curve order.
//
// NOTE: secret should be the output of a KDF like bcrypt,
// if it's derived from user input.
func GenPrivKeyFromSecret(secret []byte) *PrivKey {
secHash := sha256.Sum256(secret)
// to guarantee that we have a valid field element, we use the approach of:
// "Suite B Implementer’s Guide to FIPS 186-3", A.2.1
// https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm
// see also https://github.com/golang/go/blob/0380c9ad38843d523d9c9804fe300cb7edd7cd3c/src/crypto/ecdsa/ecdsa.go#L89-L101
fe := new(big.Int).SetBytes(secHash[:])
n := new(big.Int).Sub(secp256k1.S256().N, one)
fe.Mod(fe, n)
fe.Add(fe, one)
feB := fe.Bytes()
privKey32 := make([]byte, PrivKeySize)
// copy feB over to fixed 32 byte privKey32 and pad (if necessary)
copy(privKey32[32-len(feB):32], feB)
return &PrivKey{Key: privKey32}
}
//-------------------------------------
var (
_ cryptotypes.PubKey = &PubKey{}
_ codec.AminoMarshaler = &PubKey{}
)
// PubKeySize is comprised of 32 bytes for one field element
// (the x-coordinate), plus one byte for the parity of the y-coordinate.
const PubKeySize = 33
// Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey))
func (pubKey *PubKey) Address() crypto.Address {
if len(pubKey.Key) != PubKeySize {
panic("length of pubkey is incorrect")
}
sha := sha256.Sum256(pubKey.Key)
hasherRIPEMD160 := ripemd160.New()
hasherRIPEMD160.Write(sha[:]) // does not error
return crypto.Address(hasherRIPEMD160.Sum(nil))
}
// Bytes returns the pubkey byte format.
func (pubKey *PubKey) Bytes() []byte {
return pubKey.Key
}
func (pubKey *PubKey) String() string {
return fmt.Sprintf("PubKeySecp256k1{%X}", pubKey.Key)
}
func (pubKey *PubKey) Type() string {
return keyType
}
func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool {
return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes())
}
// MarshalAmino overrides Amino binary marshaling.
func (pubKey PubKey) MarshalAmino() ([]byte, error) {
return pubKey.Key, nil
}
// UnmarshalAmino overrides Amino binary marshaling.
func (pubKey *PubKey) UnmarshalAmino(bz []byte) error {
if len(bz) != PubKeySize {
return errorsmod.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size")
}
pubKey.Key = bz
return nil
}
// MarshalAminoJSON overrides Amino JSON marshaling.
func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) {
// When we marshal to Amino JSON, we don't marshal the "key" field itself,
// just its contents (i.e. the key bytes).
return pubKey.MarshalAmino()
}
// UnmarshalAminoJSON overrides Amino JSON marshaling.
func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error {
return pubKey.UnmarshalAmino(bz)
}
package server
import (
"context"
abci "github.com/cometbft/cometbft/abci/types"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
)
type cometABCIWrapper struct {
app servertypes.ABCI
}
func NewCometABCIWrapper(app servertypes.ABCI) abci.Application {
return cometABCIWrapper{app: app}
}
func (w cometABCIWrapper) Info(_ context.Context, req *abci.RequestInfo) (*abci.ResponseInfo, error) {
return w.app.Info(req)
}
func (w cometABCIWrapper) Query(ctx context.Context, req *abci.RequestQuery) (*abci.ResponseQuery, error) {
return w.app.Query(ctx, req)
}
func (w cometABCIWrapper) CheckTx(_ context.Context, req *abci.RequestCheckTx) (*abci.ResponseCheckTx, error) {
return w.app.CheckTx(req)
}
func (w cometABCIWrapper) InitChain(_ context.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) {
return w.app.InitChain(req)
}
func (w cometABCIWrapper) PrepareProposal(_ context.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) {
return w.app.PrepareProposal(req)
}
func (w cometABCIWrapper) ProcessProposal(_ context.Context, req *abci.RequestProcessProposal) (*abci.ResponseProcessProposal, error) {
return w.app.ProcessProposal(req)
}
func (w cometABCIWrapper) FinalizeBlock(_ context.Context, req *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) {
return w.app.FinalizeBlock(req)
}
func (w cometABCIWrapper) ExtendVote(ctx context.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) {
return w.app.ExtendVote(ctx, req)
}
func (w cometABCIWrapper) VerifyVoteExtension(_ context.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) {
return w.app.VerifyVoteExtension(req)
}
func (w cometABCIWrapper) Commit(_ context.Context, _ *abci.RequestCommit) (*abci.ResponseCommit, error) {
return w.app.Commit()
}
func (w cometABCIWrapper) ListSnapshots(_ context.Context, req *abci.RequestListSnapshots) (*abci.ResponseListSnapshots, error) {
return w.app.ListSnapshots(req)
}
func (w cometABCIWrapper) OfferSnapshot(_ context.Context, req *abci.RequestOfferSnapshot) (*abci.ResponseOfferSnapshot, error) {
return w.app.OfferSnapshot(req)
}
func (w cometABCIWrapper) LoadSnapshotChunk(_ context.Context, req *abci.RequestLoadSnapshotChunk) (*abci.ResponseLoadSnapshotChunk, error) {
return w.app.LoadSnapshotChunk(req)
}
func (w cometABCIWrapper) ApplySnapshotChunk(_ context.Context, req *abci.RequestApplySnapshotChunk) (*abci.ResponseApplySnapshotChunk, error) {
return w.app.ApplySnapshotChunk(req)
}
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/base/abci/v1beta1/abci.proto
package types
import (
fmt "fmt"
types1 "github.com/cometbft/cometbft/abci/types"
types2 "github.com/cometbft/cometbft/proto/tendermint/types"
types "github.com/cosmos/cosmos-sdk/codec/types"
_ "github.com/cosmos/gogoproto/gogoproto"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
reflect "reflect"
strings "strings"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// TxResponse defines a structure containing relevant tx data and metadata. The
// tags are stringified and the log is JSON decoded.
type TxResponse struct {
// The block height
Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"`
// The transaction hash.
TxHash string `protobuf:"bytes,2,opt,name=txhash,proto3" json:"txhash,omitempty"`
// Namespace for the Code
Codespace string `protobuf:"bytes,3,opt,name=codespace,proto3" json:"codespace,omitempty"`
// Response code.
Code uint32 `protobuf:"varint,4,opt,name=code,proto3" json:"code,omitempty"`
// Result bytes, if any.
Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"`
// The output of the application's logger (raw string). May be
// non-deterministic.
RawLog string `protobuf:"bytes,6,opt,name=raw_log,json=rawLog,proto3" json:"raw_log,omitempty"`
// The output of the application's logger (typed). May be non-deterministic.
Logs ABCIMessageLogs `protobuf:"bytes,7,rep,name=logs,proto3,castrepeated=ABCIMessageLogs" json:"logs"`
// Additional information. May be non-deterministic.
Info string `protobuf:"bytes,8,opt,name=info,proto3" json:"info,omitempty"`
// Amount of gas requested for transaction.
GasWanted int64 `protobuf:"varint,9,opt,name=gas_wanted,json=gasWanted,proto3" json:"gas_wanted,omitempty"`
// Amount of gas consumed by transaction.
GasUsed int64 `protobuf:"varint,10,opt,name=gas_used,json=gasUsed,proto3" json:"gas_used,omitempty"`
// The request transaction bytes.
Tx *types.Any `protobuf:"bytes,11,opt,name=tx,proto3" json:"tx,omitempty"`
// Time of the previous block. For heights > 1, it's the weighted median of
// the timestamps of the valid votes in the block.LastCommit. For height == 1,
// it's genesis time.
Timestamp string `protobuf:"bytes,12,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
// Events defines all the events emitted by processing a transaction. Note,
// these events include those emitted by processing all the messages and those
// emitted from the ante. Whereas Logs contains the events, with
// additional metadata, emitted only by processing the messages.
//
// Since: cosmos-sdk 0.42.11, 0.44.5, 0.45
Events []types1.Event `protobuf:"bytes,13,rep,name=events,proto3" json:"events"`
}
func (m *TxResponse) Reset() { *m = TxResponse{} }
func (*TxResponse) ProtoMessage() {}
func (*TxResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{0}
}
func (m *TxResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxResponse.Merge(m, src)
}
func (m *TxResponse) XXX_Size() int {
return m.Size()
}
func (m *TxResponse) XXX_DiscardUnknown() {
xxx_messageInfo_TxResponse.DiscardUnknown(m)
}
var xxx_messageInfo_TxResponse proto.InternalMessageInfo
// ABCIMessageLog defines a structure containing an indexed tx ABCI message log.
type ABCIMessageLog struct {
MsgIndex uint32 `protobuf:"varint,1,opt,name=msg_index,json=msgIndex,proto3" json:"msg_index"`
Log string `protobuf:"bytes,2,opt,name=log,proto3" json:"log,omitempty"`
// Events contains a slice of Event objects that were emitted during some
// execution.
Events StringEvents `protobuf:"bytes,3,rep,name=events,proto3,castrepeated=StringEvents" json:"events"`
}
func (m *ABCIMessageLog) Reset() { *m = ABCIMessageLog{} }
func (*ABCIMessageLog) ProtoMessage() {}
func (*ABCIMessageLog) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{1}
}
func (m *ABCIMessageLog) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ABCIMessageLog) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ABCIMessageLog.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ABCIMessageLog) XXX_Merge(src proto.Message) {
xxx_messageInfo_ABCIMessageLog.Merge(m, src)
}
func (m *ABCIMessageLog) XXX_Size() int {
return m.Size()
}
func (m *ABCIMessageLog) XXX_DiscardUnknown() {
xxx_messageInfo_ABCIMessageLog.DiscardUnknown(m)
}
var xxx_messageInfo_ABCIMessageLog proto.InternalMessageInfo
func (m *ABCIMessageLog) GetMsgIndex() uint32 {
if m != nil {
return m.MsgIndex
}
return 0
}
func (m *ABCIMessageLog) GetLog() string {
if m != nil {
return m.Log
}
return ""
}
func (m *ABCIMessageLog) GetEvents() StringEvents {
if m != nil {
return m.Events
}
return nil
}
// StringEvent defines en Event object wrapper where all the attributes
// contain key/value pairs that are strings instead of raw bytes.
type StringEvent struct {
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
Attributes []Attribute `protobuf:"bytes,2,rep,name=attributes,proto3" json:"attributes"`
}
func (m *StringEvent) Reset() { *m = StringEvent{} }
func (*StringEvent) ProtoMessage() {}
func (*StringEvent) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{2}
}
func (m *StringEvent) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *StringEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_StringEvent.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *StringEvent) XXX_Merge(src proto.Message) {
xxx_messageInfo_StringEvent.Merge(m, src)
}
func (m *StringEvent) XXX_Size() int {
return m.Size()
}
func (m *StringEvent) XXX_DiscardUnknown() {
xxx_messageInfo_StringEvent.DiscardUnknown(m)
}
var xxx_messageInfo_StringEvent proto.InternalMessageInfo
func (m *StringEvent) GetType() string {
if m != nil {
return m.Type
}
return ""
}
func (m *StringEvent) GetAttributes() []Attribute {
if m != nil {
return m.Attributes
}
return nil
}
// Attribute defines an attribute wrapper where the key and value are
// strings instead of raw bytes.
type Attribute struct {
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
}
func (m *Attribute) Reset() { *m = Attribute{} }
func (*Attribute) ProtoMessage() {}
func (*Attribute) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{3}
}
func (m *Attribute) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Attribute) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Attribute.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Attribute) XXX_Merge(src proto.Message) {
xxx_messageInfo_Attribute.Merge(m, src)
}
func (m *Attribute) XXX_Size() int {
return m.Size()
}
func (m *Attribute) XXX_DiscardUnknown() {
xxx_messageInfo_Attribute.DiscardUnknown(m)
}
var xxx_messageInfo_Attribute proto.InternalMessageInfo
func (m *Attribute) GetKey() string {
if m != nil {
return m.Key
}
return ""
}
func (m *Attribute) GetValue() string {
if m != nil {
return m.Value
}
return ""
}
// GasInfo defines tx execution gas context.
type GasInfo struct {
// GasWanted is the maximum units of work we allow this tx to perform.
GasWanted uint64 `protobuf:"varint,1,opt,name=gas_wanted,json=gasWanted,proto3" json:"gas_wanted,omitempty"`
// GasUsed is the amount of gas actually consumed.
GasUsed uint64 `protobuf:"varint,2,opt,name=gas_used,json=gasUsed,proto3" json:"gas_used,omitempty"`
}
func (m *GasInfo) Reset() { *m = GasInfo{} }
func (*GasInfo) ProtoMessage() {}
func (*GasInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{4}
}
func (m *GasInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GasInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GasInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GasInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_GasInfo.Merge(m, src)
}
func (m *GasInfo) XXX_Size() int {
return m.Size()
}
func (m *GasInfo) XXX_DiscardUnknown() {
xxx_messageInfo_GasInfo.DiscardUnknown(m)
}
var xxx_messageInfo_GasInfo proto.InternalMessageInfo
func (m *GasInfo) GetGasWanted() uint64 {
if m != nil {
return m.GasWanted
}
return 0
}
func (m *GasInfo) GetGasUsed() uint64 {
if m != nil {
return m.GasUsed
}
return 0
}
// Result is the union of ResponseFormat and ResponseCheckTx.
type Result struct {
// Data is any data returned from message or handler execution. It MUST be
// length prefixed in order to separate data from multiple message executions.
// Deprecated. This field is still populated, but prefer msg_response instead
// because it also contains the Msg response typeURL.
Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` // Deprecated: Do not use.
// Log contains the log information from message or handler execution.
Log string `protobuf:"bytes,2,opt,name=log,proto3" json:"log,omitempty"`
// Events contains a slice of Event objects that were emitted during message
// or handler execution.
Events []types1.Event `protobuf:"bytes,3,rep,name=events,proto3" json:"events"`
// msg_responses contains the Msg handler responses type packed in Anys.
//
// Since: cosmos-sdk 0.46
MsgResponses []*types.Any `protobuf:"bytes,4,rep,name=msg_responses,json=msgResponses,proto3" json:"msg_responses,omitempty"`
}
func (m *Result) Reset() { *m = Result{} }
func (*Result) ProtoMessage() {}
func (*Result) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{5}
}
func (m *Result) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Result) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Result.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Result) XXX_Merge(src proto.Message) {
xxx_messageInfo_Result.Merge(m, src)
}
func (m *Result) XXX_Size() int {
return m.Size()
}
func (m *Result) XXX_DiscardUnknown() {
xxx_messageInfo_Result.DiscardUnknown(m)
}
var xxx_messageInfo_Result proto.InternalMessageInfo
// SimulationResponse defines the response generated when a transaction is
// successfully simulated.
type SimulationResponse struct {
GasInfo `protobuf:"bytes,1,opt,name=gas_info,json=gasInfo,proto3,embedded=gas_info" json:"gas_info"`
Result *Result `protobuf:"bytes,2,opt,name=result,proto3" json:"result,omitempty"`
}
func (m *SimulationResponse) Reset() { *m = SimulationResponse{} }
func (*SimulationResponse) ProtoMessage() {}
func (*SimulationResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{6}
}
func (m *SimulationResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SimulationResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SimulationResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SimulationResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_SimulationResponse.Merge(m, src)
}
func (m *SimulationResponse) XXX_Size() int {
return m.Size()
}
func (m *SimulationResponse) XXX_DiscardUnknown() {
xxx_messageInfo_SimulationResponse.DiscardUnknown(m)
}
var xxx_messageInfo_SimulationResponse proto.InternalMessageInfo
func (m *SimulationResponse) GetResult() *Result {
if m != nil {
return m.Result
}
return nil
}
// MsgData defines the data returned in a Result object during message
// execution.
//
// Deprecated: Do not use.
type MsgData struct {
MsgType string `protobuf:"bytes,1,opt,name=msg_type,json=msgType,proto3" json:"msg_type,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
}
func (m *MsgData) Reset() { *m = MsgData{} }
func (*MsgData) ProtoMessage() {}
func (*MsgData) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{7}
}
func (m *MsgData) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *MsgData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_MsgData.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *MsgData) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgData.Merge(m, src)
}
func (m *MsgData) XXX_Size() int {
return m.Size()
}
func (m *MsgData) XXX_DiscardUnknown() {
xxx_messageInfo_MsgData.DiscardUnknown(m)
}
var xxx_messageInfo_MsgData proto.InternalMessageInfo
func (m *MsgData) GetMsgType() string {
if m != nil {
return m.MsgType
}
return ""
}
func (m *MsgData) GetData() []byte {
if m != nil {
return m.Data
}
return nil
}
// TxMsgData defines a list of MsgData. A transaction will have a MsgData object
// for each message.
type TxMsgData struct {
// data field is deprecated and not populated.
Data []*MsgData `protobuf:"bytes,1,rep,name=data,proto3" json:"data,omitempty"` // Deprecated: Do not use.
// msg_responses contains the Msg handler responses packed into Anys.
//
// Since: cosmos-sdk 0.46
MsgResponses []*types.Any `protobuf:"bytes,2,rep,name=msg_responses,json=msgResponses,proto3" json:"msg_responses,omitempty"`
}
func (m *TxMsgData) Reset() { *m = TxMsgData{} }
func (*TxMsgData) ProtoMessage() {}
func (*TxMsgData) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{8}
}
func (m *TxMsgData) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxMsgData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxMsgData.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxMsgData) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxMsgData.Merge(m, src)
}
func (m *TxMsgData) XXX_Size() int {
return m.Size()
}
func (m *TxMsgData) XXX_DiscardUnknown() {
xxx_messageInfo_TxMsgData.DiscardUnknown(m)
}
var xxx_messageInfo_TxMsgData proto.InternalMessageInfo
// Deprecated: Do not use.
func (m *TxMsgData) GetData() []*MsgData {
if m != nil {
return m.Data
}
return nil
}
func (m *TxMsgData) GetMsgResponses() []*types.Any {
if m != nil {
return m.MsgResponses
}
return nil
}
// SearchTxsResult defines a structure for querying txs pageable
type SearchTxsResult struct {
// Count of all txs
TotalCount uint64 `protobuf:"varint,1,opt,name=total_count,json=totalCount,proto3" json:"total_count,omitempty"`
// Count of txs in current page
Count uint64 `protobuf:"varint,2,opt,name=count,proto3" json:"count,omitempty"`
// Index of current page, start from 1
PageNumber uint64 `protobuf:"varint,3,opt,name=page_number,json=pageNumber,proto3" json:"page_number,omitempty"`
// Count of total pages
PageTotal uint64 `protobuf:"varint,4,opt,name=page_total,json=pageTotal,proto3" json:"page_total,omitempty"`
// Max count txs per page
Limit uint64 `protobuf:"varint,5,opt,name=limit,proto3" json:"limit,omitempty"`
// List of txs in current page
Txs []*TxResponse `protobuf:"bytes,6,rep,name=txs,proto3" json:"txs,omitempty"`
}
func (m *SearchTxsResult) Reset() { *m = SearchTxsResult{} }
func (*SearchTxsResult) ProtoMessage() {}
func (*SearchTxsResult) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{9}
}
func (m *SearchTxsResult) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SearchTxsResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SearchTxsResult.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SearchTxsResult) XXX_Merge(src proto.Message) {
xxx_messageInfo_SearchTxsResult.Merge(m, src)
}
func (m *SearchTxsResult) XXX_Size() int {
return m.Size()
}
func (m *SearchTxsResult) XXX_DiscardUnknown() {
xxx_messageInfo_SearchTxsResult.DiscardUnknown(m)
}
var xxx_messageInfo_SearchTxsResult proto.InternalMessageInfo
func (m *SearchTxsResult) GetTotalCount() uint64 {
if m != nil {
return m.TotalCount
}
return 0
}
func (m *SearchTxsResult) GetCount() uint64 {
if m != nil {
return m.Count
}
return 0
}
func (m *SearchTxsResult) GetPageNumber() uint64 {
if m != nil {
return m.PageNumber
}
return 0
}
func (m *SearchTxsResult) GetPageTotal() uint64 {
if m != nil {
return m.PageTotal
}
return 0
}
func (m *SearchTxsResult) GetLimit() uint64 {
if m != nil {
return m.Limit
}
return 0
}
func (m *SearchTxsResult) GetTxs() []*TxResponse {
if m != nil {
return m.Txs
}
return nil
}
// SearchBlocksResult defines a structure for querying blocks pageable
type SearchBlocksResult struct {
// Count of all blocks
TotalCount int64 `protobuf:"varint,1,opt,name=total_count,json=totalCount,proto3" json:"total_count,omitempty"`
// Count of blocks in current page
Count int64 `protobuf:"varint,2,opt,name=count,proto3" json:"count,omitempty"`
// Index of current page, start from 1
PageNumber int64 `protobuf:"varint,3,opt,name=page_number,json=pageNumber,proto3" json:"page_number,omitempty"`
// Count of total pages
PageTotal int64 `protobuf:"varint,4,opt,name=page_total,json=pageTotal,proto3" json:"page_total,omitempty"`
// Max count blocks per page
Limit int64 `protobuf:"varint,5,opt,name=limit,proto3" json:"limit,omitempty"`
// List of blocks in current page
Blocks []*types2.Block `protobuf:"bytes,6,rep,name=blocks,proto3" json:"blocks,omitempty"`
}
func (m *SearchBlocksResult) Reset() { *m = SearchBlocksResult{} }
func (*SearchBlocksResult) ProtoMessage() {}
func (*SearchBlocksResult) Descriptor() ([]byte, []int) {
return fileDescriptor_4e37629bc7eb0df8, []int{10}
}
func (m *SearchBlocksResult) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SearchBlocksResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SearchBlocksResult.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SearchBlocksResult) XXX_Merge(src proto.Message) {
xxx_messageInfo_SearchBlocksResult.Merge(m, src)
}
func (m *SearchBlocksResult) XXX_Size() int {
return m.Size()
}
func (m *SearchBlocksResult) XXX_DiscardUnknown() {
xxx_messageInfo_SearchBlocksResult.DiscardUnknown(m)
}
var xxx_messageInfo_SearchBlocksResult proto.InternalMessageInfo
func (m *SearchBlocksResult) GetTotalCount() int64 {
if m != nil {
return m.TotalCount
}
return 0
}
func (m *SearchBlocksResult) GetCount() int64 {
if m != nil {
return m.Count
}
return 0
}
func (m *SearchBlocksResult) GetPageNumber() int64 {
if m != nil {
return m.PageNumber
}
return 0
}
func (m *SearchBlocksResult) GetPageTotal() int64 {
if m != nil {
return m.PageTotal
}
return 0
}
func (m *SearchBlocksResult) GetLimit() int64 {
if m != nil {
return m.Limit
}
return 0
}
func (m *SearchBlocksResult) GetBlocks() []*types2.Block {
if m != nil {
return m.Blocks
}
return nil
}
func init() {
proto.RegisterType((*TxResponse)(nil), "cosmos.base.abci.v1beta1.TxResponse")
proto.RegisterType((*ABCIMessageLog)(nil), "cosmos.base.abci.v1beta1.ABCIMessageLog")
proto.RegisterType((*StringEvent)(nil), "cosmos.base.abci.v1beta1.StringEvent")
proto.RegisterType((*Attribute)(nil), "cosmos.base.abci.v1beta1.Attribute")
proto.RegisterType((*GasInfo)(nil), "cosmos.base.abci.v1beta1.GasInfo")
proto.RegisterType((*Result)(nil), "cosmos.base.abci.v1beta1.Result")
proto.RegisterType((*SimulationResponse)(nil), "cosmos.base.abci.v1beta1.SimulationResponse")
proto.RegisterType((*MsgData)(nil), "cosmos.base.abci.v1beta1.MsgData")
proto.RegisterType((*TxMsgData)(nil), "cosmos.base.abci.v1beta1.TxMsgData")
proto.RegisterType((*SearchTxsResult)(nil), "cosmos.base.abci.v1beta1.SearchTxsResult")
proto.RegisterType((*SearchBlocksResult)(nil), "cosmos.base.abci.v1beta1.SearchBlocksResult")
}
func init() {
proto.RegisterFile("cosmos/base/abci/v1beta1/abci.proto", fileDescriptor_4e37629bc7eb0df8)
}
var fileDescriptor_4e37629bc7eb0df8 = []byte{
// 968 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x56, 0x4f, 0x6f, 0x1b, 0xb7,
0x13, 0xd5, 0x6a, 0x37, 0x2b, 0x8b, 0xb2, 0x7e, 0xf9, 0x81, 0x30, 0x6c, 0x3a, 0x4d, 0x25, 0x55,
0x49, 0x01, 0xa1, 0x40, 0x57, 0x88, 0x13, 0x14, 0x4d, 0x4e, 0x89, 0xdc, 0x7f, 0x06, 0x92, 0x1e,
0xd6, 0x0a, 0x0a, 0xf4, 0x22, 0x50, 0x12, 0x43, 0x2d, 0xac, 0x5d, 0x0a, 0x4b, 0xca, 0x96, 0x6f,
0xbd, 0xb5, 0xc7, 0x9e, 0x7a, 0xee, 0xb5, 0xfd, 0x24, 0x39, 0xf4, 0xe0, 0xa3, 0x0f, 0x81, 0xdb,
0xda, 0xb7, 0x7e, 0x8a, 0x62, 0x86, 0xd4, 0x9f, 0xd4, 0x95, 0x9b, 0x93, 0x87, 0x6f, 0x86, 0xd4,
0xbc, 0x37, 0x6f, 0x49, 0x93, 0x7b, 0x03, 0xa5, 0x53, 0xa5, 0xdb, 0x7d, 0xae, 0x45, 0x9b, 0xf7,
0x07, 0x49, 0xfb, 0xf8, 0x41, 0x5f, 0x18, 0xfe, 0x00, 0x17, 0xd1, 0x24, 0x57, 0x46, 0x51, 0x66,
0x8b, 0x22, 0x28, 0x8a, 0x10, 0x77, 0x45, 0x77, 0xb6, 0xa4, 0x92, 0x0a, 0x8b, 0xda, 0x10, 0xd9,
0xfa, 0x3b, 0xef, 0x19, 0x91, 0x0d, 0x45, 0x9e, 0x26, 0x99, 0xb1, 0x67, 0x9a, 0xd3, 0x89, 0xd0,
0x2e, 0x79, 0x77, 0x25, 0x89, 0x78, 0xbb, 0x3f, 0x56, 0x83, 0x23, 0x97, 0xdd, 0x95, 0x4a, 0xc9,
0xb1, 0x68, 0xe3, 0xaa, 0x3f, 0x7d, 0xd5, 0xe6, 0xd9, 0xa9, 0x4d, 0x35, 0x7f, 0xf3, 0x09, 0xe9,
0xce, 0x62, 0xa1, 0x27, 0x2a, 0xd3, 0x82, 0x6e, 0x93, 0x70, 0x24, 0x12, 0x39, 0x32, 0xcc, 0x6b,
0x78, 0x2d, 0x3f, 0x76, 0x2b, 0xda, 0x24, 0xa1, 0x99, 0x8d, 0xb8, 0x1e, 0xb1, 0x62, 0xc3, 0x6b,
0x95, 0x3b, 0xe4, 0xf2, 0xa2, 0x1e, 0x76, 0x67, 0x5f, 0x71, 0x3d, 0x8a, 0x5d, 0x86, 0xde, 0x25,
0xe5, 0x81, 0x1a, 0x0a, 0x3d, 0xe1, 0x03, 0xc1, 0x7c, 0x28, 0x8b, 0x97, 0x00, 0xa5, 0x24, 0x80,
0x05, 0x0b, 0x1a, 0x5e, 0xab, 0x1a, 0x63, 0x0c, 0xd8, 0x90, 0x1b, 0xce, 0x6e, 0x61, 0x31, 0xc6,
0x74, 0x87, 0x94, 0x72, 0x7e, 0xd2, 0x1b, 0x2b, 0xc9, 0x42, 0x84, 0xc3, 0x9c, 0x9f, 0x3c, 0x57,
0x92, 0xbe, 0x24, 0xc1, 0x58, 0x49, 0xcd, 0x4a, 0x0d, 0xbf, 0x55, 0xd9, 0x6b, 0x45, 0xeb, 0xe4,
0x8b, 0x9e, 0x75, 0xf6, 0x0f, 0x5e, 0x08, 0xad, 0xb9, 0x14, 0xcf, 0x95, 0xec, 0xec, 0xbc, 0xbe,
0xa8, 0x17, 0x7e, 0xfd, 0xbd, 0x7e, 0xfb, 0x6d, 0x5c, 0xc7, 0x78, 0x1c, 0xf4, 0x90, 0x64, 0xaf,
0x14, 0xdb, 0xb0, 0x3d, 0x40, 0x4c, 0xdf, 0x27, 0x44, 0x72, 0xdd, 0x3b, 0xe1, 0x99, 0x11, 0x43,
0x56, 0x46, 0x25, 0xca, 0x92, 0xeb, 0x6f, 0x10, 0xa0, 0xbb, 0x64, 0x03, 0xd2, 0x53, 0x2d, 0x86,
0x8c, 0x60, 0xb2, 0x24, 0xb9, 0x7e, 0xa9, 0xc5, 0x90, 0xde, 0x27, 0x45, 0x33, 0x63, 0x95, 0x86,
0xd7, 0xaa, 0xec, 0x6d, 0x45, 0x56, 0xf6, 0x68, 0x2e, 0x7b, 0xf4, 0x2c, 0x3b, 0x8d, 0x8b, 0x66,
0x06, 0x4a, 0x99, 0x24, 0x15, 0xda, 0xf0, 0x74, 0xc2, 0x36, 0xad, 0x52, 0x0b, 0x80, 0x3e, 0x22,
0xa1, 0x38, 0x16, 0x99, 0xd1, 0xac, 0x8a, 0x54, 0xb7, 0xa3, 0xe5, 0x70, 0x2d, 0xd3, 0xcf, 0x21,
0xdd, 0x09, 0x80, 0x58, 0xec, 0x6a, 0x9f, 0x04, 0x3f, 0xfc, 0x5c, 0x2f, 0x34, 0x7f, 0xf1, 0xc8,
0xff, 0xde, 0xe6, 0x49, 0x3f, 0x22, 0xe5, 0x54, 0xcb, 0x5e, 0x92, 0x0d, 0xc5, 0x0c, 0xa7, 0x5a,
0xed, 0x54, 0xff, 0xba, 0xa8, 0x2f, 0xc1, 0x78, 0x23, 0xd5, 0xf2, 0x00, 0x22, 0xfa, 0x7f, 0xe2,
0x83, 0xf0, 0x38, 0xe3, 0x18, 0x42, 0x7a, 0xb8, 0x68, 0xc6, 0xc7, 0x66, 0x3e, 0x5c, 0xaf, 0xfb,
0xa1, 0xc9, 0x93, 0x4c, 0xda, 0xde, 0xb6, 0x9c, 0xe8, 0x9b, 0x2b, 0xa0, 0x5e, 0xf6, 0xfa, 0xdd,
0x9b, 0x86, 0xd7, 0xcc, 0x49, 0x65, 0x25, 0x0b, 0x83, 0x00, 0xe7, 0x62, 0x8b, 0xe5, 0x18, 0x63,
0x7a, 0x40, 0x08, 0x37, 0x26, 0x4f, 0xfa, 0x53, 0x23, 0x34, 0x2b, 0x62, 0x07, 0xf7, 0x6e, 0x98,
0xfc, 0xbc, 0xd6, 0x69, 0xb3, 0xb2, 0xd9, 0xfd, 0xe6, 0x43, 0x52, 0x5e, 0x14, 0x01, 0xdb, 0x23,
0x71, 0xea, 0x7e, 0x10, 0x42, 0xba, 0x45, 0x6e, 0x1d, 0xf3, 0xf1, 0x54, 0x38, 0x05, 0xec, 0xa2,
0xb9, 0x4f, 0x4a, 0x5f, 0x72, 0x7d, 0x70, 0xdd, 0x19, 0xb0, 0x33, 0x58, 0xe7, 0x8c, 0x22, 0x26,
0xe7, 0xce, 0x80, 0xc9, 0x84, 0xb1, 0xd0, 0xd3, 0xb1, 0xa1, 0xdb, 0xce, 0xf6, 0xb0, 0x7d, 0xb3,
0x53, 0x64, 0x9e, 0xb3, 0xfe, 0x75, 0xf5, 0x1f, 0xfd, 0x43, 0xfd, 0x77, 0xb2, 0x02, 0x7d, 0x4c,
0xaa, 0x30, 0xdc, 0xdc, 0x7d, 0xd4, 0x9a, 0x05, 0xb8, 0xf9, 0xdf, 0xfd, 0xb8, 0x99, 0x6a, 0x39,
0xff, 0xfc, 0xe7, 0x2e, 0xfa, 0xc9, 0x23, 0xf4, 0x30, 0x49, 0xa7, 0x63, 0x6e, 0x12, 0x95, 0x2d,
0x2e, 0x87, 0x2f, 0x2c, 0x3b, 0xfc, 0x5c, 0x3c, 0xb4, 0xf8, 0x07, 0xeb, 0x67, 0xe1, 0x14, 0xeb,
0x6c, 0x40, 0x6b, 0x67, 0x17, 0x75, 0x0f, 0xa5, 0x40, 0x11, 0x3f, 0x25, 0x61, 0x8e, 0x4a, 0x20,
0xd5, 0xca, 0x5e, 0x63, 0xfd, 0x29, 0x56, 0xb1, 0xd8, 0xd5, 0x37, 0x9f, 0x92, 0xd2, 0x0b, 0x2d,
0x3f, 0x03, 0xb1, 0x76, 0x09, 0xd8, 0xb6, 0xb7, 0x62, 0x99, 0x52, 0xaa, 0x65, 0x17, 0x5c, 0x33,
0xbf, 0x56, 0xe0, 0xf4, 0x4d, 0xab, 0xed, 0x93, 0x10, 0xc6, 0xcf, 0xbc, 0xe6, 0xf7, 0x1e, 0x29,
0x77, 0x67, 0xf3, 0x43, 0x1e, 0x2f, 0x26, 0xe1, 0xdf, 0xcc, 0xc6, 0x6d, 0x58, 0x19, 0xd6, 0x35,
0x91, 0x8b, 0xef, 0x2e, 0x32, 0x5a, 0xf1, 0x8d, 0x47, 0x6e, 0x1f, 0x0a, 0x9e, 0x0f, 0x46, 0xdd,
0x99, 0x76, 0xce, 0xa8, 0x93, 0x8a, 0x51, 0x86, 0x8f, 0x7b, 0x03, 0x35, 0xcd, 0x8c, 0xf3, 0x17,
0x41, 0x68, 0x1f, 0x10, 0x30, 0xa8, 0x4d, 0x59, 0x77, 0xd9, 0x05, 0x6c, 0x9b, 0x70, 0x29, 0x7a,
0xd9, 0x34, 0xed, 0x8b, 0x1c, 0xef, 0xde, 0x20, 0x26, 0x00, 0x7d, 0x8d, 0x08, 0xd8, 0x16, 0x0b,
0xf0, 0x24, 0xbc, 0x82, 0x83, 0xb8, 0x0c, 0x48, 0x17, 0x00, 0x38, 0x75, 0x9c, 0xa4, 0x89, 0xc1,
0x8b, 0x38, 0x88, 0xed, 0x82, 0x7e, 0x42, 0x7c, 0x33, 0xd3, 0x2c, 0x44, 0x5e, 0xf7, 0xd7, 0x6b,
0xb3, 0x7c, 0x3e, 0x62, 0xd8, 0xe0, 0xe8, 0x9d, 0x83, 0x87, 0x90, 0x5e, 0x07, 0x5e, 0xa2, 0x1b,
0x18, 0xfa, 0xeb, 0x19, 0xfa, 0x37, 0x30, 0xf4, 0xff, 0x83, 0xa1, 0xbf, 0x96, 0xa1, 0x3f, 0x67,
0xd8, 0x26, 0x21, 0x3e, 0x93, 0x73, 0x92, 0x3b, 0xab, 0x9f, 0x97, 0x7d, 0x5e, 0xb1, 0xf9, 0xd8,
0x95, 0x59, 0x6a, 0x9d, 0xa7, 0xe7, 0x7f, 0xd6, 0x0a, 0xaf, 0x2f, 0x6b, 0xde, 0xd9, 0x65, 0xcd,
0xfb, 0xe3, 0xb2, 0xe6, 0xfd, 0x78, 0x55, 0x2b, 0x9c, 0x5d, 0xd5, 0x0a, 0xe7, 0x57, 0xb5, 0xc2,
0xb7, 0x4d, 0x99, 0x98, 0xd1, 0xb4, 0x1f, 0x0d, 0x54, 0xda, 0x76, 0xff, 0x07, 0xd8, 0x3f, 0x1f,
0xeb, 0xe1, 0x91, 0x7d, 0x9c, 0xfb, 0x21, 0xba, 0xe3, 0xe1, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff,
0x4d, 0x51, 0x55, 0xd9, 0x29, 0x08, 0x00, 0x00,
}
func (m *TxResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Events) > 0 {
for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x6a
}
}
if len(m.Timestamp) > 0 {
i -= len(m.Timestamp)
copy(dAtA[i:], m.Timestamp)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Timestamp)))
i--
dAtA[i] = 0x62
}
if m.Tx != nil {
{
size, err := m.Tx.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x5a
}
if m.GasUsed != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.GasUsed))
i--
dAtA[i] = 0x50
}
if m.GasWanted != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.GasWanted))
i--
dAtA[i] = 0x48
}
if len(m.Info) > 0 {
i -= len(m.Info)
copy(dAtA[i:], m.Info)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Info)))
i--
dAtA[i] = 0x42
}
if len(m.Logs) > 0 {
for iNdEx := len(m.Logs) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Logs[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x3a
}
}
if len(m.RawLog) > 0 {
i -= len(m.RawLog)
copy(dAtA[i:], m.RawLog)
i = encodeVarintAbci(dAtA, i, uint64(len(m.RawLog)))
i--
dAtA[i] = 0x32
}
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0x2a
}
if m.Code != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.Code))
i--
dAtA[i] = 0x20
}
if len(m.Codespace) > 0 {
i -= len(m.Codespace)
copy(dAtA[i:], m.Codespace)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Codespace)))
i--
dAtA[i] = 0x1a
}
if len(m.TxHash) > 0 {
i -= len(m.TxHash)
copy(dAtA[i:], m.TxHash)
i = encodeVarintAbci(dAtA, i, uint64(len(m.TxHash)))
i--
dAtA[i] = 0x12
}
if m.Height != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ABCIMessageLog) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ABCIMessageLog) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ABCIMessageLog) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Events) > 0 {
for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
if len(m.Log) > 0 {
i -= len(m.Log)
copy(dAtA[i:], m.Log)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Log)))
i--
dAtA[i] = 0x12
}
if m.MsgIndex != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.MsgIndex))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *StringEvent) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *StringEvent) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StringEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Attributes) > 0 {
for iNdEx := len(m.Attributes) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Attributes[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if len(m.Type) > 0 {
i -= len(m.Type)
copy(dAtA[i:], m.Type)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Type)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *Attribute) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Attribute) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Attribute) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *GasInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GasInfo) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GasInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.GasUsed != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.GasUsed))
i--
dAtA[i] = 0x10
}
if m.GasWanted != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.GasWanted))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Result) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Result) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Result) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.MsgResponses) > 0 {
for iNdEx := len(m.MsgResponses) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.MsgResponses[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
}
if len(m.Events) > 0 {
for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
if len(m.Log) > 0 {
i -= len(m.Log)
copy(dAtA[i:], m.Log)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Log)))
i--
dAtA[i] = 0x12
}
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *SimulationResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SimulationResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SimulationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Result != nil {
{
size, err := m.Result.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
{
size, err := m.GasInfo.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *MsgData) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *MsgData) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *MsgData) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Data) > 0 {
i -= len(m.Data)
copy(dAtA[i:], m.Data)
i = encodeVarintAbci(dAtA, i, uint64(len(m.Data)))
i--
dAtA[i] = 0x12
}
if len(m.MsgType) > 0 {
i -= len(m.MsgType)
copy(dAtA[i:], m.MsgType)
i = encodeVarintAbci(dAtA, i, uint64(len(m.MsgType)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *TxMsgData) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxMsgData) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxMsgData) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.MsgResponses) > 0 {
for iNdEx := len(m.MsgResponses) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.MsgResponses[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if len(m.Data) > 0 {
for iNdEx := len(m.Data) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Data[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *SearchTxsResult) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SearchTxsResult) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SearchTxsResult) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Txs[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x32
}
}
if m.Limit != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.Limit))
i--
dAtA[i] = 0x28
}
if m.PageTotal != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.PageTotal))
i--
dAtA[i] = 0x20
}
if m.PageNumber != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.PageNumber))
i--
dAtA[i] = 0x18
}
if m.Count != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.Count))
i--
dAtA[i] = 0x10
}
if m.TotalCount != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.TotalCount))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *SearchBlocksResult) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SearchBlocksResult) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SearchBlocksResult) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Blocks) > 0 {
for iNdEx := len(m.Blocks) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Blocks[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAbci(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x32
}
}
if m.Limit != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.Limit))
i--
dAtA[i] = 0x28
}
if m.PageTotal != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.PageTotal))
i--
dAtA[i] = 0x20
}
if m.PageNumber != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.PageNumber))
i--
dAtA[i] = 0x18
}
if m.Count != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.Count))
i--
dAtA[i] = 0x10
}
if m.TotalCount != 0 {
i = encodeVarintAbci(dAtA, i, uint64(m.TotalCount))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func encodeVarintAbci(dAtA []byte, offset int, v uint64) int {
offset -= sovAbci(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *TxResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Height != 0 {
n += 1 + sovAbci(uint64(m.Height))
}
l = len(m.TxHash)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
l = len(m.Codespace)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
if m.Code != 0 {
n += 1 + sovAbci(uint64(m.Code))
}
l = len(m.Data)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
l = len(m.RawLog)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
if len(m.Logs) > 0 {
for _, e := range m.Logs {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
l = len(m.Info)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
if m.GasWanted != 0 {
n += 1 + sovAbci(uint64(m.GasWanted))
}
if m.GasUsed != 0 {
n += 1 + sovAbci(uint64(m.GasUsed))
}
if m.Tx != nil {
l = m.Tx.Size()
n += 1 + l + sovAbci(uint64(l))
}
l = len(m.Timestamp)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
if len(m.Events) > 0 {
for _, e := range m.Events {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
return n
}
func (m *ABCIMessageLog) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.MsgIndex != 0 {
n += 1 + sovAbci(uint64(m.MsgIndex))
}
l = len(m.Log)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
if len(m.Events) > 0 {
for _, e := range m.Events {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
return n
}
func (m *StringEvent) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Type)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
if len(m.Attributes) > 0 {
for _, e := range m.Attributes {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
return n
}
func (m *Attribute) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Key)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
return n
}
func (m *GasInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.GasWanted != 0 {
n += 1 + sovAbci(uint64(m.GasWanted))
}
if m.GasUsed != 0 {
n += 1 + sovAbci(uint64(m.GasUsed))
}
return n
}
func (m *Result) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Data)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
l = len(m.Log)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
if len(m.Events) > 0 {
for _, e := range m.Events {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
if len(m.MsgResponses) > 0 {
for _, e := range m.MsgResponses {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
return n
}
func (m *SimulationResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.GasInfo.Size()
n += 1 + l + sovAbci(uint64(l))
if m.Result != nil {
l = m.Result.Size()
n += 1 + l + sovAbci(uint64(l))
}
return n
}
func (m *MsgData) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.MsgType)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
l = len(m.Data)
if l > 0 {
n += 1 + l + sovAbci(uint64(l))
}
return n
}
func (m *TxMsgData) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Data) > 0 {
for _, e := range m.Data {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
if len(m.MsgResponses) > 0 {
for _, e := range m.MsgResponses {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
return n
}
func (m *SearchTxsResult) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.TotalCount != 0 {
n += 1 + sovAbci(uint64(m.TotalCount))
}
if m.Count != 0 {
n += 1 + sovAbci(uint64(m.Count))
}
if m.PageNumber != 0 {
n += 1 + sovAbci(uint64(m.PageNumber))
}
if m.PageTotal != 0 {
n += 1 + sovAbci(uint64(m.PageTotal))
}
if m.Limit != 0 {
n += 1 + sovAbci(uint64(m.Limit))
}
if len(m.Txs) > 0 {
for _, e := range m.Txs {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
return n
}
func (m *SearchBlocksResult) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.TotalCount != 0 {
n += 1 + sovAbci(uint64(m.TotalCount))
}
if m.Count != 0 {
n += 1 + sovAbci(uint64(m.Count))
}
if m.PageNumber != 0 {
n += 1 + sovAbci(uint64(m.PageNumber))
}
if m.PageTotal != 0 {
n += 1 + sovAbci(uint64(m.PageTotal))
}
if m.Limit != 0 {
n += 1 + sovAbci(uint64(m.Limit))
}
if len(m.Blocks) > 0 {
for _, e := range m.Blocks {
l = e.Size()
n += 1 + l + sovAbci(uint64(l))
}
}
return n
}
func sovAbci(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozAbci(x uint64) (n int) {
return sovAbci(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *ABCIMessageLog) String() string {
if this == nil {
return "nil"
}
repeatedStringForEvents := "[]StringEvent{"
for _, f := range this.Events {
repeatedStringForEvents += strings.Replace(strings.Replace(f.String(), "StringEvent", "StringEvent", 1), `&`, ``, 1) + ","
}
repeatedStringForEvents += "}"
s := strings.Join([]string{`&ABCIMessageLog{`,
`MsgIndex:` + fmt.Sprintf("%v", this.MsgIndex) + `,`,
`Log:` + fmt.Sprintf("%v", this.Log) + `,`,
`Events:` + repeatedStringForEvents + `,`,
`}`,
}, "")
return s
}
func (this *StringEvent) String() string {
if this == nil {
return "nil"
}
repeatedStringForAttributes := "[]Attribute{"
for _, f := range this.Attributes {
repeatedStringForAttributes += fmt.Sprintf("%v", f) + ","
}
repeatedStringForAttributes += "}"
s := strings.Join([]string{`&StringEvent{`,
`Type:` + fmt.Sprintf("%v", this.Type) + `,`,
`Attributes:` + repeatedStringForAttributes + `,`,
`}`,
}, "")
return s
}
func (this *MsgData) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&MsgData{`,
`MsgType:` + fmt.Sprintf("%v", this.MsgType) + `,`,
`Data:` + fmt.Sprintf("%v", this.Data) + `,`,
`}`,
}, "")
return s
}
func (this *TxMsgData) String() string {
if this == nil {
return "nil"
}
repeatedStringForData := "[]*MsgData{"
for _, f := range this.Data {
repeatedStringForData += strings.Replace(f.String(), "MsgData", "MsgData", 1) + ","
}
repeatedStringForData += "}"
repeatedStringForMsgResponses := "[]*Any{"
for _, f := range this.MsgResponses {
repeatedStringForMsgResponses += strings.Replace(fmt.Sprintf("%v", f), "Any", "types.Any", 1) + ","
}
repeatedStringForMsgResponses += "}"
s := strings.Join([]string{`&TxMsgData{`,
`Data:` + repeatedStringForData + `,`,
`MsgResponses:` + repeatedStringForMsgResponses + `,`,
`}`,
}, "")
return s
}
func (this *SearchTxsResult) String() string {
if this == nil {
return "nil"
}
repeatedStringForTxs := "[]*TxResponse{"
for _, f := range this.Txs {
repeatedStringForTxs += strings.Replace(fmt.Sprintf("%v", f), "TxResponse", "TxResponse", 1) + ","
}
repeatedStringForTxs += "}"
s := strings.Join([]string{`&SearchTxsResult{`,
`TotalCount:` + fmt.Sprintf("%v", this.TotalCount) + `,`,
`Count:` + fmt.Sprintf("%v", this.Count) + `,`,
`PageNumber:` + fmt.Sprintf("%v", this.PageNumber) + `,`,
`PageTotal:` + fmt.Sprintf("%v", this.PageTotal) + `,`,
`Limit:` + fmt.Sprintf("%v", this.Limit) + `,`,
`Txs:` + repeatedStringForTxs + `,`,
`}`,
}, "")
return s
}
func (this *SearchBlocksResult) String() string {
if this == nil {
return "nil"
}
repeatedStringForBlocks := "[]*Block{"
for _, f := range this.Blocks {
repeatedStringForBlocks += strings.Replace(fmt.Sprintf("%v", f), "Block", "types2.Block", 1) + ","
}
repeatedStringForBlocks += "}"
s := strings.Join([]string{`&SearchBlocksResult{`,
`TotalCount:` + fmt.Sprintf("%v", this.TotalCount) + `,`,
`Count:` + fmt.Sprintf("%v", this.Count) + `,`,
`PageNumber:` + fmt.Sprintf("%v", this.PageNumber) + `,`,
`PageTotal:` + fmt.Sprintf("%v", this.PageTotal) + `,`,
`Limit:` + fmt.Sprintf("%v", this.Limit) + `,`,
`Blocks:` + repeatedStringForBlocks + `,`,
`}`,
}, "")
return s
}
func valueToStringAbci(v interface{}) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func (m *TxResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxHash", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TxHash = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Codespace", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Codespace = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType)
}
m.Code = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Code |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field RawLog", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.RawLog = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Logs", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Logs = append(m.Logs, ABCIMessageLog{})
if err := m.Logs[len(m.Logs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Info = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 9:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType)
}
m.GasWanted = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.GasWanted |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 10:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType)
}
m.GasUsed = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.GasUsed |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 11:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Tx == nil {
m.Tx = &types.Any{}
}
if err := m.Tx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 12:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Timestamp = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 13:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Events = append(m.Events, types1.Event{})
if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ABCIMessageLog) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ABCIMessageLog: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ABCIMessageLog: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MsgIndex", wireType)
}
m.MsgIndex = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.MsgIndex |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Log = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Events = append(m.Events, StringEvent{})
if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *StringEvent) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StringEvent: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StringEvent: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Type = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Attributes = append(m.Attributes, Attribute{})
if err := m.Attributes[len(m.Attributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Attribute) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Attribute: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Attribute: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GasInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GasInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GasInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType)
}
m.GasWanted = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.GasWanted |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType)
}
m.GasUsed = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.GasUsed |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Result) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Result: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Result: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Log = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Events = append(m.Events, types1.Event{})
if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field MsgResponses", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.MsgResponses = append(m.MsgResponses, &types.Any{})
if err := m.MsgResponses[len(m.MsgResponses)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SimulationResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SimulationResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SimulationResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field GasInfo", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.GasInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Result == nil {
m.Result = &Result{}
}
if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *MsgData) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MsgData: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MsgData: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field MsgType", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.MsgType = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxMsgData) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxMsgData: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxMsgData: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data, &MsgData{})
if err := m.Data[len(m.Data)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field MsgResponses", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.MsgResponses = append(m.MsgResponses, &types.Any{})
if err := m.MsgResponses[len(m.MsgResponses)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SearchTxsResult) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SearchTxsResult: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SearchTxsResult: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field TotalCount", wireType)
}
m.TotalCount = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.TotalCount |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType)
}
m.Count = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Count |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field PageNumber", wireType)
}
m.PageNumber = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.PageNumber |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field PageTotal", wireType)
}
m.PageTotal = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.PageTotal |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
}
m.Limit = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Limit |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, &TxResponse{})
if err := m.Txs[len(m.Txs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SearchBlocksResult) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SearchBlocksResult: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SearchBlocksResult: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field TotalCount", wireType)
}
m.TotalCount = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.TotalCount |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType)
}
m.Count = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Count |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field PageNumber", wireType)
}
m.PageNumber = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.PageNumber |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field PageTotal", wireType)
}
m.PageTotal = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.PageTotal |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
}
m.Limit = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Limit |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Blocks", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAbci
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAbci
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAbci
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Blocks = append(m.Blocks, &types2.Block{})
if err := m.Blocks[len(m.Blocks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAbci(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAbci
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipAbci(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAbci
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAbci
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAbci
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthAbci
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupAbci
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthAbci
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthAbci = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowAbci = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupAbci = fmt.Errorf("proto: unexpected end of group")
)
package query
import (
"fmt"
proto "github.com/cosmos/gogoproto/proto"
"cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
)
// FilteredPaginate does pagination of all the results in the PrefixStore based on the
// provided PageRequest. onResult should be used to do actual unmarshaling and filter the results.
// If key is provided, the pagination uses the optimized querying.
// If offset is used, the pagination uses lazy filtering i.e., searches through all the records.
// The accumulate parameter represents if the response is valid based on the offset given.
// It will be false for the results (filtered) < offset and true for `offset > accumulate <= end`.
// When accumulate is set to true the current result should be appended to the result set returned
// to the client.
func FilteredPaginate(
prefixStore types.KVStore,
pageRequest *PageRequest,
onResult func(key, value []byte, accumulate bool) (bool, error),
) (*PageResponse, error) {
pageRequest = initPageRequestDefaults(pageRequest)
if pageRequest.Offset > 0 && pageRequest.Key != nil {
return nil, fmt.Errorf("invalid request, either offset or key is expected, got both")
}
var (
numHits uint64
nextKey []byte
err error
)
iterator := getIterator(prefixStore, pageRequest.Key, pageRequest.Reverse)
defer iterator.Close()
if len(pageRequest.Key) != 0 {
accumulateFn := func(_ uint64) bool { return true }
for ; iterator.Valid(); iterator.Next() {
if numHits == pageRequest.Limit {
nextKey = iterator.Key()
break
}
numHits, err = processResult(iterator, numHits, onResult, accumulateFn)
if err != nil {
return nil, err
}
}
return &PageResponse{
NextKey: nextKey,
}, nil
}
end := pageRequest.Offset + pageRequest.Limit
accumulateFn := func(numHits uint64) bool { return numHits >= pageRequest.Offset && numHits < end }
for ; iterator.Valid(); iterator.Next() {
numHits, err = processResult(iterator, numHits, onResult, accumulateFn)
if err != nil {
return nil, err
}
if numHits == end+1 {
if nextKey == nil {
nextKey = iterator.Key()
}
if !pageRequest.CountTotal {
break
}
}
}
res := &PageResponse{NextKey: nextKey}
if pageRequest.CountTotal {
res.Total = numHits
}
return res, nil
}
func processResult(iterator types.Iterator, numHits uint64, onResult func(key, value []byte, accumulate bool) (bool, error), accumulateFn func(numHits uint64) bool) (uint64, error) {
if iterator.Error() != nil {
return numHits, iterator.Error()
}
accumulate := accumulateFn(numHits)
hit, err := onResult(iterator.Key(), iterator.Value(), accumulate)
if err != nil {
return numHits, err
}
if hit {
numHits++
}
return numHits, nil
}
func genericProcessResult[T, F proto.Message](iterator types.Iterator, numHits uint64, onResult func(key []byte, value T) (F, error), accumulateFn func(numHits uint64) bool,
constructor func() T, cdc codec.BinaryCodec, results []F,
) ([]F, uint64, error) {
if iterator.Error() != nil {
return results, numHits, iterator.Error()
}
protoMsg := constructor()
err := cdc.Unmarshal(iterator.Value(), protoMsg)
if err != nil {
return results, numHits, err
}
val, err := onResult(iterator.Key(), protoMsg)
if err != nil {
return results, numHits, err
}
if proto.Size(val) != 0 {
// Previously this was the "accumulate" flag
if accumulateFn(numHits) {
results = append(results, val)
}
numHits++
}
return results, numHits, nil
}
// GenericFilteredPaginate does pagination of all the results in the PrefixStore based on the
// provided PageRequest. `onResult` should be used to filter or transform the results.
// `c` is a constructor function that needs to return a new instance of the type T (this is to
// workaround some generic pitfalls in which we can't instantiate a T struct inside the function).
// If key is provided, the pagination uses the optimized querying.
// If offset is used, the pagination uses lazy filtering i.e., searches through all the records.
// The resulting slice (of type F) can be of a different type than the one being iterated through
// (type T), so it's possible to do any necessary transformation inside the onResult function.
func GenericFilteredPaginate[T, F proto.Message](
cdc codec.BinaryCodec,
prefixStore types.KVStore,
pageRequest *PageRequest,
onResult func(key []byte, value T) (F, error),
constructor func() T,
) ([]F, *PageResponse, error) {
pageRequest = initPageRequestDefaults(pageRequest)
results := []F{}
if pageRequest.Offset > 0 && pageRequest.Key != nil {
return results, nil, fmt.Errorf("invalid request, either offset or key is expected, got both")
}
var (
numHits uint64
nextKey []byte
err error
)
iterator := getIterator(prefixStore, pageRequest.Key, pageRequest.Reverse)
defer iterator.Close()
if len(pageRequest.Key) != 0 {
accumulateFn := func(_ uint64) bool { return true }
for ; iterator.Valid(); iterator.Next() {
if numHits == pageRequest.Limit {
nextKey = iterator.Key()
break
}
results, numHits, err = genericProcessResult(iterator, numHits, onResult, accumulateFn, constructor, cdc, results)
if err != nil {
return nil, nil, err
}
}
return results, &PageResponse{
NextKey: nextKey,
}, nil
}
end := pageRequest.Offset + pageRequest.Limit
accumulateFn := func(numHits uint64) bool { return numHits >= pageRequest.Offset && numHits < end }
for ; iterator.Valid(); iterator.Next() {
results, numHits, err = genericProcessResult(iterator, numHits, onResult, accumulateFn, constructor, cdc, results)
if err != nil {
return nil, nil, err
}
if numHits == end+1 {
if nextKey == nil {
nextKey = iterator.Key()
}
if !pageRequest.CountTotal {
break
}
}
}
res := &PageResponse{NextKey: nextKey}
if pageRequest.CountTotal {
res.Total = numHits
}
return results, res, nil
}
package query
import (
"fmt"
"math"
db "github.com/cosmos/cosmos-db"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"cosmossdk.io/store/types"
)
// DefaultPage is the default `page` number for queries.
// If the `page` number is not supplied, `DefaultPage` will be used.
const DefaultPage = 1
// DefaultLimit is the default `limit` for queries
// if the `limit` is not supplied, paginate will use `DefaultLimit`
const DefaultLimit = 100
// PaginationMaxLimit is the maximum limit the paginate function can handle
// which equals the maximum value that can be stored in uint64
var PaginationMaxLimit uint64 = math.MaxUint64
// ParsePagination validate PageRequest and returns page number & limit.
func ParsePagination(pageReq *PageRequest) (page, limit int, err error) {
offset := 0
limit = DefaultLimit
if pageReq != nil {
offset = int(pageReq.Offset)
limit = int(pageReq.Limit)
}
if offset < 0 {
return 1, 0, status.Error(codes.InvalidArgument, "offset must greater than 0")
}
if limit < 0 {
return 1, 0, status.Error(codes.InvalidArgument, "limit must greater than 0")
} else if limit == 0 {
limit = DefaultLimit
}
page = offset/limit + 1
return page, limit, nil
}
// Paginate does pagination of all the results in the PrefixStore based on the
// provided PageRequest. onResult should be used to do actual unmarshaling.
func Paginate(
prefixStore types.KVStore,
pageRequest *PageRequest,
onResult func(key, value []byte) error,
) (*PageResponse, error) {
pageRequest = initPageRequestDefaults(pageRequest)
if pageRequest.Offset > 0 && pageRequest.Key != nil {
return nil, fmt.Errorf("invalid request, either offset or key is expected, got both")
}
iterator := getIterator(prefixStore, pageRequest.Key, pageRequest.Reverse)
defer iterator.Close()
var count uint64
var nextKey []byte
if len(pageRequest.Key) != 0 {
for ; iterator.Valid(); iterator.Next() {
if count == pageRequest.Limit {
nextKey = iterator.Key()
break
}
if iterator.Error() != nil {
return nil, iterator.Error()
}
err := onResult(iterator.Key(), iterator.Value())
if err != nil {
return nil, err
}
count++
}
return &PageResponse{
NextKey: nextKey,
}, nil
}
end := pageRequest.Offset + pageRequest.Limit
for ; iterator.Valid(); iterator.Next() {
count++
if count <= pageRequest.Offset {
continue
}
if count <= end {
err := onResult(iterator.Key(), iterator.Value())
if err != nil {
return nil, err
}
} else if count == end+1 {
nextKey = iterator.Key()
if !pageRequest.CountTotal {
break
}
}
if iterator.Error() != nil {
return nil, iterator.Error()
}
}
res := &PageResponse{NextKey: nextKey}
if pageRequest.CountTotal {
res.Total = count
}
return res, nil
}
func getIterator(prefixStore types.KVStore, start []byte, reverse bool) db.Iterator {
if reverse {
var end []byte
if start != nil {
itr := prefixStore.Iterator(start, nil)
defer itr.Close()
if itr.Valid() {
itr.Next()
end = itr.Key()
}
}
return prefixStore.ReverseIterator(nil, end)
}
return prefixStore.Iterator(start, nil)
}
// initPageRequestDefaults initializes a PageRequest's defaults when those are not set.
func initPageRequestDefaults(pageRequest *PageRequest) *PageRequest {
// if the PageRequest is nil, use default PageRequest
if pageRequest == nil {
pageRequest = &PageRequest{}
}
pageRequestCopy := *pageRequest
if len(pageRequestCopy.Key) == 0 {
pageRequestCopy.Key = nil
}
if pageRequestCopy.Limit == 0 {
pageRequestCopy.Limit = DefaultLimit
// count total results when the limit is zero/not supplied
pageRequestCopy.CountTotal = true
}
return &pageRequestCopy
}
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/base/query/v1beta1/pagination.proto
package query
import (
fmt "fmt"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// PageRequest is to be embedded in gRPC request messages for efficient
// pagination. Ex:
//
// message SomeRequest {
// Foo some_parameter = 1;
// PageRequest pagination = 2;
// }
type PageRequest struct {
// key is a value returned in PageResponse.next_key to begin
// querying the next page most efficiently. Only one of offset or key
// should be set.
Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
// offset is a numeric offset that can be used when key is unavailable.
// It is less efficient than using key. Only one of offset or key should
// be set.
Offset uint64 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"`
// limit is the total number of results to be returned in the result page.
// If left empty it will default to a value to be set by each app.
Limit uint64 `protobuf:"varint,3,opt,name=limit,proto3" json:"limit,omitempty"`
// count_total is set to true to indicate that the result set should include
// a count of the total number of items available for pagination in UIs.
// count_total is only respected when offset is used. It is ignored when key
// is set.
CountTotal bool `protobuf:"varint,4,opt,name=count_total,json=countTotal,proto3" json:"count_total,omitempty"`
// reverse is set to true if results are to be returned in the descending order.
//
// Since: cosmos-sdk 0.43
Reverse bool `protobuf:"varint,5,opt,name=reverse,proto3" json:"reverse,omitempty"`
}
func (m *PageRequest) Reset() { *m = PageRequest{} }
func (m *PageRequest) String() string { return proto.CompactTextString(m) }
func (*PageRequest) ProtoMessage() {}
func (*PageRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_53d6d609fe6828af, []int{0}
}
func (m *PageRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PageRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PageRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PageRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_PageRequest.Merge(m, src)
}
func (m *PageRequest) XXX_Size() int {
return m.Size()
}
func (m *PageRequest) XXX_DiscardUnknown() {
xxx_messageInfo_PageRequest.DiscardUnknown(m)
}
var xxx_messageInfo_PageRequest proto.InternalMessageInfo
func (m *PageRequest) GetKey() []byte {
if m != nil {
return m.Key
}
return nil
}
func (m *PageRequest) GetOffset() uint64 {
if m != nil {
return m.Offset
}
return 0
}
func (m *PageRequest) GetLimit() uint64 {
if m != nil {
return m.Limit
}
return 0
}
func (m *PageRequest) GetCountTotal() bool {
if m != nil {
return m.CountTotal
}
return false
}
func (m *PageRequest) GetReverse() bool {
if m != nil {
return m.Reverse
}
return false
}
// PageResponse is to be embedded in gRPC response messages where the
// corresponding request message has used PageRequest.
//
// message SomeResponse {
// repeated Bar results = 1;
// PageResponse page = 2;
// }
type PageResponse struct {
// next_key is the key to be passed to PageRequest.key to
// query the next page most efficiently. It will be empty if
// there are no more results.
NextKey []byte `protobuf:"bytes,1,opt,name=next_key,json=nextKey,proto3" json:"next_key,omitempty"`
// total is total number of results available if PageRequest.count_total
// was set, its value is undefined otherwise
Total uint64 `protobuf:"varint,2,opt,name=total,proto3" json:"total,omitempty"`
}
func (m *PageResponse) Reset() { *m = PageResponse{} }
func (m *PageResponse) String() string { return proto.CompactTextString(m) }
func (*PageResponse) ProtoMessage() {}
func (*PageResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_53d6d609fe6828af, []int{1}
}
func (m *PageResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PageResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PageResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PageResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_PageResponse.Merge(m, src)
}
func (m *PageResponse) XXX_Size() int {
return m.Size()
}
func (m *PageResponse) XXX_DiscardUnknown() {
xxx_messageInfo_PageResponse.DiscardUnknown(m)
}
var xxx_messageInfo_PageResponse proto.InternalMessageInfo
func (m *PageResponse) GetNextKey() []byte {
if m != nil {
return m.NextKey
}
return nil
}
func (m *PageResponse) GetTotal() uint64 {
if m != nil {
return m.Total
}
return 0
}
func init() {
proto.RegisterType((*PageRequest)(nil), "cosmos.base.query.v1beta1.PageRequest")
proto.RegisterType((*PageResponse)(nil), "cosmos.base.query.v1beta1.PageResponse")
}
func init() {
proto.RegisterFile("cosmos/base/query/v1beta1/pagination.proto", fileDescriptor_53d6d609fe6828af)
}
var fileDescriptor_53d6d609fe6828af = []byte{
// 282 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x90, 0xbd, 0x4e, 0xc3, 0x30,
0x14, 0x85, 0x6b, 0xfa, 0x2b, 0xb7, 0x03, 0xb2, 0x10, 0x72, 0x17, 0x13, 0x75, 0x8a, 0x90, 0x88,
0x55, 0xf1, 0x00, 0x48, 0x5d, 0x59, 0x50, 0xc4, 0xc4, 0x52, 0x39, 0xe1, 0x36, 0x44, 0x6d, 0xe2,
0x34, 0xbe, 0xa9, 0xc8, 0x1b, 0x30, 0xf2, 0x58, 0x8c, 0x1d, 0x19, 0x51, 0xf2, 0x22, 0x28, 0x76,
0x10, 0x93, 0xfd, 0x9d, 0x7b, 0x74, 0xef, 0xd1, 0xa1, 0xb7, 0xb1, 0x36, 0x99, 0x36, 0x32, 0x52,
0x06, 0xe4, 0xb1, 0x82, 0xb2, 0x96, 0xa7, 0x75, 0x04, 0xa8, 0xd6, 0xb2, 0x50, 0x49, 0x9a, 0x2b,
0x4c, 0x75, 0x1e, 0x14, 0xa5, 0x46, 0xcd, 0x96, 0xce, 0x1b, 0x74, 0xde, 0xc0, 0x7a, 0x83, 0xde,
0xbb, 0xfa, 0x20, 0x74, 0xfe, 0xa4, 0x12, 0x08, 0xe1, 0x58, 0x81, 0x41, 0x76, 0x49, 0x87, 0x7b,
0xa8, 0x39, 0xf1, 0x88, 0xbf, 0x08, 0xbb, 0x2f, 0xbb, 0xa6, 0x13, 0xbd, 0xdb, 0x19, 0x40, 0x7e,
0xe1, 0x11, 0x7f, 0x14, 0xf6, 0xc4, 0xae, 0xe8, 0xf8, 0x90, 0x66, 0x29, 0xf2, 0xa1, 0x95, 0x1d,
0xb0, 0x1b, 0x3a, 0x8f, 0x75, 0x95, 0xe3, 0x16, 0x35, 0xaa, 0x03, 0x1f, 0x79, 0xc4, 0x9f, 0x85,
0xd4, 0x4a, 0xcf, 0x9d, 0xc2, 0x38, 0x9d, 0x96, 0x70, 0x82, 0xd2, 0x00, 0x1f, 0xdb, 0xe1, 0x1f,
0xae, 0x1e, 0xe8, 0xc2, 0x25, 0x31, 0x85, 0xce, 0x0d, 0xb0, 0x25, 0x9d, 0xe5, 0xf0, 0x8e, 0xdb,
0xff, 0x3c, 0xd3, 0x8e, 0x1f, 0xa1, 0xee, 0x6e, 0xbb, 0xfd, 0x2e, 0x92, 0x83, 0xcd, 0xe6, 0xab,
0x11, 0xe4, 0xdc, 0x08, 0xf2, 0xd3, 0x08, 0xf2, 0xd9, 0x8a, 0xc1, 0xb9, 0x15, 0x83, 0xef, 0x56,
0x0c, 0x5e, 0xfc, 0x24, 0xc5, 0xb7, 0x2a, 0x0a, 0x62, 0x9d, 0xc9, 0xbe, 0x37, 0xf7, 0xdc, 0x99,
0xd7, 0xbd, 0xc4, 0xba, 0x00, 0xe3, 0x3a, 0x8c, 0x26, 0xb6, 0xb1, 0xfb, 0xdf, 0x00, 0x00, 0x00,
0xff, 0xff, 0x3d, 0x43, 0x85, 0xf7, 0x5f, 0x01, 0x00, 0x00,
}
func (m *PageRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PageRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PageRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Reverse {
i--
if m.Reverse {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x28
}
if m.CountTotal {
i--
if m.CountTotal {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x20
}
if m.Limit != 0 {
i = encodeVarintPagination(dAtA, i, uint64(m.Limit))
i--
dAtA[i] = 0x18
}
if m.Offset != 0 {
i = encodeVarintPagination(dAtA, i, uint64(m.Offset))
i--
dAtA[i] = 0x10
}
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintPagination(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *PageResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PageResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PageResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Total != 0 {
i = encodeVarintPagination(dAtA, i, uint64(m.Total))
i--
dAtA[i] = 0x10
}
if len(m.NextKey) > 0 {
i -= len(m.NextKey)
copy(dAtA[i:], m.NextKey)
i = encodeVarintPagination(dAtA, i, uint64(len(m.NextKey)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintPagination(dAtA []byte, offset int, v uint64) int {
offset -= sovPagination(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *PageRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Key)
if l > 0 {
n += 1 + l + sovPagination(uint64(l))
}
if m.Offset != 0 {
n += 1 + sovPagination(uint64(m.Offset))
}
if m.Limit != 0 {
n += 1 + sovPagination(uint64(m.Limit))
}
if m.CountTotal {
n += 2
}
if m.Reverse {
n += 2
}
return n
}
func (m *PageResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.NextKey)
if l > 0 {
n += 1 + l + sovPagination(uint64(l))
}
if m.Total != 0 {
n += 1 + sovPagination(uint64(m.Total))
}
return n
}
func sovPagination(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozPagination(x uint64) (n int) {
return sovPagination(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *PageRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PageRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PageRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthPagination
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthPagination
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...)
if m.Key == nil {
m.Key = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Offset", wireType)
}
m.Offset = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Offset |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
}
m.Limit = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Limit |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CountTotal", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.CountTotal = bool(v != 0)
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Reverse", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Reverse = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipPagination(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthPagination
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *PageResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PageResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PageResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field NextKey", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthPagination
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthPagination
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.NextKey = append(m.NextKey[:0], dAtA[iNdEx:postIndex]...)
if m.NextKey == nil {
m.NextKey = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType)
}
m.Total = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowPagination
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Total |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipPagination(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthPagination
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipPagination(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowPagination
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowPagination
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowPagination
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthPagination
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupPagination
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthPagination
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthPagination = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowPagination = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupPagination = fmt.Errorf("proto: unexpected end of group")
)
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/tx/v1beta1/service.proto
package tx
import (
context "context"
fmt "fmt"
types1 "github.com/cometbft/cometbft/proto/tendermint/types"
types "github.com/cosmos/cosmos-sdk/types"
query "github.com/cosmos/cosmos-sdk/types/query"
grpc1 "github.com/cosmos/gogoproto/grpc"
proto "github.com/cosmos/gogoproto/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// OrderBy defines the sorting order
type OrderBy int32
const (
// ORDER_BY_UNSPECIFIED specifies an unknown sorting order. OrderBy defaults
// to ASC in this case.
OrderBy_ORDER_BY_UNSPECIFIED OrderBy = 0
// ORDER_BY_ASC defines ascending order
OrderBy_ORDER_BY_ASC OrderBy = 1
// ORDER_BY_DESC defines descending order
OrderBy_ORDER_BY_DESC OrderBy = 2
)
var OrderBy_name = map[int32]string{
0: "ORDER_BY_UNSPECIFIED",
1: "ORDER_BY_ASC",
2: "ORDER_BY_DESC",
}
var OrderBy_value = map[string]int32{
"ORDER_BY_UNSPECIFIED": 0,
"ORDER_BY_ASC": 1,
"ORDER_BY_DESC": 2,
}
func (x OrderBy) String() string {
return proto.EnumName(OrderBy_name, int32(x))
}
func (OrderBy) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{0}
}
// BroadcastMode specifies the broadcast mode for the TxService.Broadcast RPC
// method.
type BroadcastMode int32
const (
// zero-value for mode ordering
BroadcastMode_BROADCAST_MODE_UNSPECIFIED BroadcastMode = 0
// DEPRECATED: use BROADCAST_MODE_SYNC instead,
// BROADCAST_MODE_BLOCK is not supported by the SDK from v0.47.x onwards.
BroadcastMode_BROADCAST_MODE_BLOCK BroadcastMode = 1 // Deprecated: Do not use.
// BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits
// for a CheckTx execution response only.
BroadcastMode_BROADCAST_MODE_SYNC BroadcastMode = 2
// BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client
// returns immediately.
BroadcastMode_BROADCAST_MODE_ASYNC BroadcastMode = 3
)
var BroadcastMode_name = map[int32]string{
0: "BROADCAST_MODE_UNSPECIFIED",
1: "BROADCAST_MODE_BLOCK",
2: "BROADCAST_MODE_SYNC",
3: "BROADCAST_MODE_ASYNC",
}
var BroadcastMode_value = map[string]int32{
"BROADCAST_MODE_UNSPECIFIED": 0,
"BROADCAST_MODE_BLOCK": 1,
"BROADCAST_MODE_SYNC": 2,
"BROADCAST_MODE_ASYNC": 3,
}
func (x BroadcastMode) String() string {
return proto.EnumName(BroadcastMode_name, int32(x))
}
func (BroadcastMode) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{1}
}
// GetTxsEventRequest is the request type for the Service.TxsByEvents
// RPC method.
type GetTxsEventRequest struct {
// events is the list of transaction event type.
// Deprecated post v0.47.x: use query instead, which should contain a valid
// events query.
Events []string `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` // Deprecated: Do not use.
// pagination defines a pagination for the request.
// Deprecated post v0.46.x: use page and limit instead.
Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` // Deprecated: Do not use.
OrderBy OrderBy `protobuf:"varint,3,opt,name=order_by,json=orderBy,proto3,enum=cosmos.tx.v1beta1.OrderBy" json:"order_by,omitempty"`
// page is the page number to query, starts at 1. If not provided, will
// default to first page.
Page uint64 `protobuf:"varint,4,opt,name=page,proto3" json:"page,omitempty"`
// limit is the total number of results to be returned in the result page.
// If left empty it will default to a value to be set by each app.
Limit uint64 `protobuf:"varint,5,opt,name=limit,proto3" json:"limit,omitempty"`
// query defines the transaction event query that is proxied to Tendermint's
// TxSearch RPC method. The query must be valid.
//
// Since cosmos-sdk 0.50
Query string `protobuf:"bytes,6,opt,name=query,proto3" json:"query,omitempty"`
}
func (m *GetTxsEventRequest) Reset() { *m = GetTxsEventRequest{} }
func (m *GetTxsEventRequest) String() string { return proto.CompactTextString(m) }
func (*GetTxsEventRequest) ProtoMessage() {}
func (*GetTxsEventRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{0}
}
func (m *GetTxsEventRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GetTxsEventRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GetTxsEventRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GetTxsEventRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetTxsEventRequest.Merge(m, src)
}
func (m *GetTxsEventRequest) XXX_Size() int {
return m.Size()
}
func (m *GetTxsEventRequest) XXX_DiscardUnknown() {
xxx_messageInfo_GetTxsEventRequest.DiscardUnknown(m)
}
var xxx_messageInfo_GetTxsEventRequest proto.InternalMessageInfo
// Deprecated: Do not use.
func (m *GetTxsEventRequest) GetEvents() []string {
if m != nil {
return m.Events
}
return nil
}
// Deprecated: Do not use.
func (m *GetTxsEventRequest) GetPagination() *query.PageRequest {
if m != nil {
return m.Pagination
}
return nil
}
func (m *GetTxsEventRequest) GetOrderBy() OrderBy {
if m != nil {
return m.OrderBy
}
return OrderBy_ORDER_BY_UNSPECIFIED
}
func (m *GetTxsEventRequest) GetPage() uint64 {
if m != nil {
return m.Page
}
return 0
}
func (m *GetTxsEventRequest) GetLimit() uint64 {
if m != nil {
return m.Limit
}
return 0
}
func (m *GetTxsEventRequest) GetQuery() string {
if m != nil {
return m.Query
}
return ""
}
// GetTxsEventResponse is the response type for the Service.TxsByEvents
// RPC method.
type GetTxsEventResponse struct {
// txs is the list of queried transactions.
Txs []*Tx `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"`
// tx_responses is the list of queried TxResponses.
TxResponses []*types.TxResponse `protobuf:"bytes,2,rep,name=tx_responses,json=txResponses,proto3" json:"tx_responses,omitempty"`
// pagination defines a pagination for the response.
// Deprecated post v0.46.x: use total instead.
Pagination *query.PageResponse `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` // Deprecated: Do not use.
// total is total number of results available
Total uint64 `protobuf:"varint,4,opt,name=total,proto3" json:"total,omitempty"`
}
func (m *GetTxsEventResponse) Reset() { *m = GetTxsEventResponse{} }
func (m *GetTxsEventResponse) String() string { return proto.CompactTextString(m) }
func (*GetTxsEventResponse) ProtoMessage() {}
func (*GetTxsEventResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{1}
}
func (m *GetTxsEventResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GetTxsEventResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GetTxsEventResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GetTxsEventResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetTxsEventResponse.Merge(m, src)
}
func (m *GetTxsEventResponse) XXX_Size() int {
return m.Size()
}
func (m *GetTxsEventResponse) XXX_DiscardUnknown() {
xxx_messageInfo_GetTxsEventResponse.DiscardUnknown(m)
}
var xxx_messageInfo_GetTxsEventResponse proto.InternalMessageInfo
func (m *GetTxsEventResponse) GetTxs() []*Tx {
if m != nil {
return m.Txs
}
return nil
}
func (m *GetTxsEventResponse) GetTxResponses() []*types.TxResponse {
if m != nil {
return m.TxResponses
}
return nil
}
// Deprecated: Do not use.
func (m *GetTxsEventResponse) GetPagination() *query.PageResponse {
if m != nil {
return m.Pagination
}
return nil
}
func (m *GetTxsEventResponse) GetTotal() uint64 {
if m != nil {
return m.Total
}
return 0
}
// BroadcastTxRequest is the request type for the Service.BroadcastTxRequest
// RPC method.
type BroadcastTxRequest struct {
// tx_bytes is the raw transaction.
TxBytes []byte `protobuf:"bytes,1,opt,name=tx_bytes,json=txBytes,proto3" json:"tx_bytes,omitempty"`
Mode BroadcastMode `protobuf:"varint,2,opt,name=mode,proto3,enum=cosmos.tx.v1beta1.BroadcastMode" json:"mode,omitempty"`
}
func (m *BroadcastTxRequest) Reset() { *m = BroadcastTxRequest{} }
func (m *BroadcastTxRequest) String() string { return proto.CompactTextString(m) }
func (*BroadcastTxRequest) ProtoMessage() {}
func (*BroadcastTxRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{2}
}
func (m *BroadcastTxRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *BroadcastTxRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_BroadcastTxRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *BroadcastTxRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_BroadcastTxRequest.Merge(m, src)
}
func (m *BroadcastTxRequest) XXX_Size() int {
return m.Size()
}
func (m *BroadcastTxRequest) XXX_DiscardUnknown() {
xxx_messageInfo_BroadcastTxRequest.DiscardUnknown(m)
}
var xxx_messageInfo_BroadcastTxRequest proto.InternalMessageInfo
func (m *BroadcastTxRequest) GetTxBytes() []byte {
if m != nil {
return m.TxBytes
}
return nil
}
func (m *BroadcastTxRequest) GetMode() BroadcastMode {
if m != nil {
return m.Mode
}
return BroadcastMode_BROADCAST_MODE_UNSPECIFIED
}
// BroadcastTxResponse is the response type for the
// Service.BroadcastTx method.
type BroadcastTxResponse struct {
// tx_response is the queried TxResponses.
TxResponse *types.TxResponse `protobuf:"bytes,1,opt,name=tx_response,json=txResponse,proto3" json:"tx_response,omitempty"`
}
func (m *BroadcastTxResponse) Reset() { *m = BroadcastTxResponse{} }
func (m *BroadcastTxResponse) String() string { return proto.CompactTextString(m) }
func (*BroadcastTxResponse) ProtoMessage() {}
func (*BroadcastTxResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{3}
}
func (m *BroadcastTxResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *BroadcastTxResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_BroadcastTxResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *BroadcastTxResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_BroadcastTxResponse.Merge(m, src)
}
func (m *BroadcastTxResponse) XXX_Size() int {
return m.Size()
}
func (m *BroadcastTxResponse) XXX_DiscardUnknown() {
xxx_messageInfo_BroadcastTxResponse.DiscardUnknown(m)
}
var xxx_messageInfo_BroadcastTxResponse proto.InternalMessageInfo
func (m *BroadcastTxResponse) GetTxResponse() *types.TxResponse {
if m != nil {
return m.TxResponse
}
return nil
}
// SimulateRequest is the request type for the Service.Simulate
// RPC method.
type SimulateRequest struct {
// tx is the transaction to simulate.
// Deprecated. Send raw tx bytes instead.
Tx *Tx `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"` // Deprecated: Do not use.
// tx_bytes is the raw transaction.
//
// Since: cosmos-sdk 0.43
TxBytes []byte `protobuf:"bytes,2,opt,name=tx_bytes,json=txBytes,proto3" json:"tx_bytes,omitempty"`
}
func (m *SimulateRequest) Reset() { *m = SimulateRequest{} }
func (m *SimulateRequest) String() string { return proto.CompactTextString(m) }
func (*SimulateRequest) ProtoMessage() {}
func (*SimulateRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{4}
}
func (m *SimulateRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SimulateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SimulateRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SimulateRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_SimulateRequest.Merge(m, src)
}
func (m *SimulateRequest) XXX_Size() int {
return m.Size()
}
func (m *SimulateRequest) XXX_DiscardUnknown() {
xxx_messageInfo_SimulateRequest.DiscardUnknown(m)
}
var xxx_messageInfo_SimulateRequest proto.InternalMessageInfo
// Deprecated: Do not use.
func (m *SimulateRequest) GetTx() *Tx {
if m != nil {
return m.Tx
}
return nil
}
func (m *SimulateRequest) GetTxBytes() []byte {
if m != nil {
return m.TxBytes
}
return nil
}
// SimulateResponse is the response type for the
// Service.SimulateRPC method.
type SimulateResponse struct {
// gas_info is the information about gas used in the simulation.
GasInfo *types.GasInfo `protobuf:"bytes,1,opt,name=gas_info,json=gasInfo,proto3" json:"gas_info,omitempty"`
// result is the result of the simulation.
Result *types.Result `protobuf:"bytes,2,opt,name=result,proto3" json:"result,omitempty"`
}
func (m *SimulateResponse) Reset() { *m = SimulateResponse{} }
func (m *SimulateResponse) String() string { return proto.CompactTextString(m) }
func (*SimulateResponse) ProtoMessage() {}
func (*SimulateResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{5}
}
func (m *SimulateResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SimulateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SimulateResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SimulateResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_SimulateResponse.Merge(m, src)
}
func (m *SimulateResponse) XXX_Size() int {
return m.Size()
}
func (m *SimulateResponse) XXX_DiscardUnknown() {
xxx_messageInfo_SimulateResponse.DiscardUnknown(m)
}
var xxx_messageInfo_SimulateResponse proto.InternalMessageInfo
func (m *SimulateResponse) GetGasInfo() *types.GasInfo {
if m != nil {
return m.GasInfo
}
return nil
}
func (m *SimulateResponse) GetResult() *types.Result {
if m != nil {
return m.Result
}
return nil
}
// GetTxRequest is the request type for the Service.GetTx
// RPC method.
type GetTxRequest struct {
// hash is the tx hash to query, encoded as a hex string.
Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"`
}
func (m *GetTxRequest) Reset() { *m = GetTxRequest{} }
func (m *GetTxRequest) String() string { return proto.CompactTextString(m) }
func (*GetTxRequest) ProtoMessage() {}
func (*GetTxRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{6}
}
func (m *GetTxRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GetTxRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GetTxRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GetTxRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetTxRequest.Merge(m, src)
}
func (m *GetTxRequest) XXX_Size() int {
return m.Size()
}
func (m *GetTxRequest) XXX_DiscardUnknown() {
xxx_messageInfo_GetTxRequest.DiscardUnknown(m)
}
var xxx_messageInfo_GetTxRequest proto.InternalMessageInfo
func (m *GetTxRequest) GetHash() string {
if m != nil {
return m.Hash
}
return ""
}
// GetTxResponse is the response type for the Service.GetTx method.
type GetTxResponse struct {
// tx is the queried transaction.
Tx *Tx `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"`
// tx_response is the queried TxResponses.
TxResponse *types.TxResponse `protobuf:"bytes,2,opt,name=tx_response,json=txResponse,proto3" json:"tx_response,omitempty"`
}
func (m *GetTxResponse) Reset() { *m = GetTxResponse{} }
func (m *GetTxResponse) String() string { return proto.CompactTextString(m) }
func (*GetTxResponse) ProtoMessage() {}
func (*GetTxResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{7}
}
func (m *GetTxResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GetTxResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GetTxResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GetTxResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetTxResponse.Merge(m, src)
}
func (m *GetTxResponse) XXX_Size() int {
return m.Size()
}
func (m *GetTxResponse) XXX_DiscardUnknown() {
xxx_messageInfo_GetTxResponse.DiscardUnknown(m)
}
var xxx_messageInfo_GetTxResponse proto.InternalMessageInfo
func (m *GetTxResponse) GetTx() *Tx {
if m != nil {
return m.Tx
}
return nil
}
func (m *GetTxResponse) GetTxResponse() *types.TxResponse {
if m != nil {
return m.TxResponse
}
return nil
}
// GetBlockWithTxsRequest is the request type for the Service.GetBlockWithTxs
// RPC method.
//
// Since: cosmos-sdk 0.45.2
type GetBlockWithTxsRequest struct {
// height is the height of the block to query.
Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"`
// pagination defines a pagination for the request.
Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *GetBlockWithTxsRequest) Reset() { *m = GetBlockWithTxsRequest{} }
func (m *GetBlockWithTxsRequest) String() string { return proto.CompactTextString(m) }
func (*GetBlockWithTxsRequest) ProtoMessage() {}
func (*GetBlockWithTxsRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{8}
}
func (m *GetBlockWithTxsRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GetBlockWithTxsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GetBlockWithTxsRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GetBlockWithTxsRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetBlockWithTxsRequest.Merge(m, src)
}
func (m *GetBlockWithTxsRequest) XXX_Size() int {
return m.Size()
}
func (m *GetBlockWithTxsRequest) XXX_DiscardUnknown() {
xxx_messageInfo_GetBlockWithTxsRequest.DiscardUnknown(m)
}
var xxx_messageInfo_GetBlockWithTxsRequest proto.InternalMessageInfo
func (m *GetBlockWithTxsRequest) GetHeight() int64 {
if m != nil {
return m.Height
}
return 0
}
func (m *GetBlockWithTxsRequest) GetPagination() *query.PageRequest {
if m != nil {
return m.Pagination
}
return nil
}
// GetBlockWithTxsResponse is the response type for the Service.GetBlockWithTxs
// method.
//
// Since: cosmos-sdk 0.45.2
type GetBlockWithTxsResponse struct {
// txs are the transactions in the block.
Txs []*Tx `protobuf:"bytes,1,rep,name=txs,proto3" json:"txs,omitempty"`
BlockId *types1.BlockID `protobuf:"bytes,2,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"`
Block *types1.Block `protobuf:"bytes,3,opt,name=block,proto3" json:"block,omitempty"`
// pagination defines a pagination for the response.
Pagination *query.PageResponse `protobuf:"bytes,4,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *GetBlockWithTxsResponse) Reset() { *m = GetBlockWithTxsResponse{} }
func (m *GetBlockWithTxsResponse) String() string { return proto.CompactTextString(m) }
func (*GetBlockWithTxsResponse) ProtoMessage() {}
func (*GetBlockWithTxsResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{9}
}
func (m *GetBlockWithTxsResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GetBlockWithTxsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GetBlockWithTxsResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GetBlockWithTxsResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetBlockWithTxsResponse.Merge(m, src)
}
func (m *GetBlockWithTxsResponse) XXX_Size() int {
return m.Size()
}
func (m *GetBlockWithTxsResponse) XXX_DiscardUnknown() {
xxx_messageInfo_GetBlockWithTxsResponse.DiscardUnknown(m)
}
var xxx_messageInfo_GetBlockWithTxsResponse proto.InternalMessageInfo
func (m *GetBlockWithTxsResponse) GetTxs() []*Tx {
if m != nil {
return m.Txs
}
return nil
}
func (m *GetBlockWithTxsResponse) GetBlockId() *types1.BlockID {
if m != nil {
return m.BlockId
}
return nil
}
func (m *GetBlockWithTxsResponse) GetBlock() *types1.Block {
if m != nil {
return m.Block
}
return nil
}
func (m *GetBlockWithTxsResponse) GetPagination() *query.PageResponse {
if m != nil {
return m.Pagination
}
return nil
}
// TxDecodeRequest is the request type for the Service.TxDecode
// RPC method.
//
// Since: cosmos-sdk 0.47
type TxDecodeRequest struct {
// tx_bytes is the raw transaction.
TxBytes []byte `protobuf:"bytes,1,opt,name=tx_bytes,json=txBytes,proto3" json:"tx_bytes,omitempty"`
}
func (m *TxDecodeRequest) Reset() { *m = TxDecodeRequest{} }
func (m *TxDecodeRequest) String() string { return proto.CompactTextString(m) }
func (*TxDecodeRequest) ProtoMessage() {}
func (*TxDecodeRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{10}
}
func (m *TxDecodeRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxDecodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxDecodeRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxDecodeRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxDecodeRequest.Merge(m, src)
}
func (m *TxDecodeRequest) XXX_Size() int {
return m.Size()
}
func (m *TxDecodeRequest) XXX_DiscardUnknown() {
xxx_messageInfo_TxDecodeRequest.DiscardUnknown(m)
}
var xxx_messageInfo_TxDecodeRequest proto.InternalMessageInfo
func (m *TxDecodeRequest) GetTxBytes() []byte {
if m != nil {
return m.TxBytes
}
return nil
}
// TxDecodeResponse is the response type for the
// Service.TxDecode method.
//
// Since: cosmos-sdk 0.47
type TxDecodeResponse struct {
// tx is the decoded transaction.
Tx *Tx `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"`
}
func (m *TxDecodeResponse) Reset() { *m = TxDecodeResponse{} }
func (m *TxDecodeResponse) String() string { return proto.CompactTextString(m) }
func (*TxDecodeResponse) ProtoMessage() {}
func (*TxDecodeResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{11}
}
func (m *TxDecodeResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxDecodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxDecodeResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxDecodeResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxDecodeResponse.Merge(m, src)
}
func (m *TxDecodeResponse) XXX_Size() int {
return m.Size()
}
func (m *TxDecodeResponse) XXX_DiscardUnknown() {
xxx_messageInfo_TxDecodeResponse.DiscardUnknown(m)
}
var xxx_messageInfo_TxDecodeResponse proto.InternalMessageInfo
func (m *TxDecodeResponse) GetTx() *Tx {
if m != nil {
return m.Tx
}
return nil
}
// TxEncodeRequest is the request type for the Service.TxEncode
// RPC method.
//
// Since: cosmos-sdk 0.47
type TxEncodeRequest struct {
// tx is the transaction to encode.
Tx *Tx `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"`
}
func (m *TxEncodeRequest) Reset() { *m = TxEncodeRequest{} }
func (m *TxEncodeRequest) String() string { return proto.CompactTextString(m) }
func (*TxEncodeRequest) ProtoMessage() {}
func (*TxEncodeRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{12}
}
func (m *TxEncodeRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxEncodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxEncodeRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxEncodeRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxEncodeRequest.Merge(m, src)
}
func (m *TxEncodeRequest) XXX_Size() int {
return m.Size()
}
func (m *TxEncodeRequest) XXX_DiscardUnknown() {
xxx_messageInfo_TxEncodeRequest.DiscardUnknown(m)
}
var xxx_messageInfo_TxEncodeRequest proto.InternalMessageInfo
func (m *TxEncodeRequest) GetTx() *Tx {
if m != nil {
return m.Tx
}
return nil
}
// TxEncodeResponse is the response type for the
// Service.TxEncode method.
//
// Since: cosmos-sdk 0.47
type TxEncodeResponse struct {
// tx_bytes is the encoded transaction bytes.
TxBytes []byte `protobuf:"bytes,1,opt,name=tx_bytes,json=txBytes,proto3" json:"tx_bytes,omitempty"`
}
func (m *TxEncodeResponse) Reset() { *m = TxEncodeResponse{} }
func (m *TxEncodeResponse) String() string { return proto.CompactTextString(m) }
func (*TxEncodeResponse) ProtoMessage() {}
func (*TxEncodeResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{13}
}
func (m *TxEncodeResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxEncodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxEncodeResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxEncodeResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxEncodeResponse.Merge(m, src)
}
func (m *TxEncodeResponse) XXX_Size() int {
return m.Size()
}
func (m *TxEncodeResponse) XXX_DiscardUnknown() {
xxx_messageInfo_TxEncodeResponse.DiscardUnknown(m)
}
var xxx_messageInfo_TxEncodeResponse proto.InternalMessageInfo
func (m *TxEncodeResponse) GetTxBytes() []byte {
if m != nil {
return m.TxBytes
}
return nil
}
// TxEncodeAminoRequest is the request type for the Service.TxEncodeAmino
// RPC method.
//
// Since: cosmos-sdk 0.47
type TxEncodeAminoRequest struct {
AminoJson string `protobuf:"bytes,1,opt,name=amino_json,json=aminoJson,proto3" json:"amino_json,omitempty"`
}
func (m *TxEncodeAminoRequest) Reset() { *m = TxEncodeAminoRequest{} }
func (m *TxEncodeAminoRequest) String() string { return proto.CompactTextString(m) }
func (*TxEncodeAminoRequest) ProtoMessage() {}
func (*TxEncodeAminoRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{14}
}
func (m *TxEncodeAminoRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxEncodeAminoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxEncodeAminoRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxEncodeAminoRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxEncodeAminoRequest.Merge(m, src)
}
func (m *TxEncodeAminoRequest) XXX_Size() int {
return m.Size()
}
func (m *TxEncodeAminoRequest) XXX_DiscardUnknown() {
xxx_messageInfo_TxEncodeAminoRequest.DiscardUnknown(m)
}
var xxx_messageInfo_TxEncodeAminoRequest proto.InternalMessageInfo
func (m *TxEncodeAminoRequest) GetAminoJson() string {
if m != nil {
return m.AminoJson
}
return ""
}
// TxEncodeAminoResponse is the response type for the Service.TxEncodeAmino
// RPC method.
//
// Since: cosmos-sdk 0.47
type TxEncodeAminoResponse struct {
AminoBinary []byte `protobuf:"bytes,1,opt,name=amino_binary,json=aminoBinary,proto3" json:"amino_binary,omitempty"`
}
func (m *TxEncodeAminoResponse) Reset() { *m = TxEncodeAminoResponse{} }
func (m *TxEncodeAminoResponse) String() string { return proto.CompactTextString(m) }
func (*TxEncodeAminoResponse) ProtoMessage() {}
func (*TxEncodeAminoResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{15}
}
func (m *TxEncodeAminoResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxEncodeAminoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxEncodeAminoResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxEncodeAminoResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxEncodeAminoResponse.Merge(m, src)
}
func (m *TxEncodeAminoResponse) XXX_Size() int {
return m.Size()
}
func (m *TxEncodeAminoResponse) XXX_DiscardUnknown() {
xxx_messageInfo_TxEncodeAminoResponse.DiscardUnknown(m)
}
var xxx_messageInfo_TxEncodeAminoResponse proto.InternalMessageInfo
func (m *TxEncodeAminoResponse) GetAminoBinary() []byte {
if m != nil {
return m.AminoBinary
}
return nil
}
// TxDecodeAminoRequest is the request type for the Service.TxDecodeAmino
// RPC method.
//
// Since: cosmos-sdk 0.47
type TxDecodeAminoRequest struct {
AminoBinary []byte `protobuf:"bytes,1,opt,name=amino_binary,json=aminoBinary,proto3" json:"amino_binary,omitempty"`
}
func (m *TxDecodeAminoRequest) Reset() { *m = TxDecodeAminoRequest{} }
func (m *TxDecodeAminoRequest) String() string { return proto.CompactTextString(m) }
func (*TxDecodeAminoRequest) ProtoMessage() {}
func (*TxDecodeAminoRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{16}
}
func (m *TxDecodeAminoRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxDecodeAminoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxDecodeAminoRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxDecodeAminoRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxDecodeAminoRequest.Merge(m, src)
}
func (m *TxDecodeAminoRequest) XXX_Size() int {
return m.Size()
}
func (m *TxDecodeAminoRequest) XXX_DiscardUnknown() {
xxx_messageInfo_TxDecodeAminoRequest.DiscardUnknown(m)
}
var xxx_messageInfo_TxDecodeAminoRequest proto.InternalMessageInfo
func (m *TxDecodeAminoRequest) GetAminoBinary() []byte {
if m != nil {
return m.AminoBinary
}
return nil
}
// TxDecodeAminoResponse is the response type for the Service.TxDecodeAmino
// RPC method.
//
// Since: cosmos-sdk 0.47
type TxDecodeAminoResponse struct {
AminoJson string `protobuf:"bytes,1,opt,name=amino_json,json=aminoJson,proto3" json:"amino_json,omitempty"`
}
func (m *TxDecodeAminoResponse) Reset() { *m = TxDecodeAminoResponse{} }
func (m *TxDecodeAminoResponse) String() string { return proto.CompactTextString(m) }
func (*TxDecodeAminoResponse) ProtoMessage() {}
func (*TxDecodeAminoResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{17}
}
func (m *TxDecodeAminoResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TxDecodeAminoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TxDecodeAminoResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TxDecodeAminoResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_TxDecodeAminoResponse.Merge(m, src)
}
func (m *TxDecodeAminoResponse) XXX_Size() int {
return m.Size()
}
func (m *TxDecodeAminoResponse) XXX_DiscardUnknown() {
xxx_messageInfo_TxDecodeAminoResponse.DiscardUnknown(m)
}
var xxx_messageInfo_TxDecodeAminoResponse proto.InternalMessageInfo
func (m *TxDecodeAminoResponse) GetAminoJson() string {
if m != nil {
return m.AminoJson
}
return ""
}
func init() {
proto.RegisterEnum("cosmos.tx.v1beta1.OrderBy", OrderBy_name, OrderBy_value)
proto.RegisterEnum("cosmos.tx.v1beta1.BroadcastMode", BroadcastMode_name, BroadcastMode_value)
proto.RegisterType((*GetTxsEventRequest)(nil), "cosmos.tx.v1beta1.GetTxsEventRequest")
proto.RegisterType((*GetTxsEventResponse)(nil), "cosmos.tx.v1beta1.GetTxsEventResponse")
proto.RegisterType((*BroadcastTxRequest)(nil), "cosmos.tx.v1beta1.BroadcastTxRequest")
proto.RegisterType((*BroadcastTxResponse)(nil), "cosmos.tx.v1beta1.BroadcastTxResponse")
proto.RegisterType((*SimulateRequest)(nil), "cosmos.tx.v1beta1.SimulateRequest")
proto.RegisterType((*SimulateResponse)(nil), "cosmos.tx.v1beta1.SimulateResponse")
proto.RegisterType((*GetTxRequest)(nil), "cosmos.tx.v1beta1.GetTxRequest")
proto.RegisterType((*GetTxResponse)(nil), "cosmos.tx.v1beta1.GetTxResponse")
proto.RegisterType((*GetBlockWithTxsRequest)(nil), "cosmos.tx.v1beta1.GetBlockWithTxsRequest")
proto.RegisterType((*GetBlockWithTxsResponse)(nil), "cosmos.tx.v1beta1.GetBlockWithTxsResponse")
proto.RegisterType((*TxDecodeRequest)(nil), "cosmos.tx.v1beta1.TxDecodeRequest")
proto.RegisterType((*TxDecodeResponse)(nil), "cosmos.tx.v1beta1.TxDecodeResponse")
proto.RegisterType((*TxEncodeRequest)(nil), "cosmos.tx.v1beta1.TxEncodeRequest")
proto.RegisterType((*TxEncodeResponse)(nil), "cosmos.tx.v1beta1.TxEncodeResponse")
proto.RegisterType((*TxEncodeAminoRequest)(nil), "cosmos.tx.v1beta1.TxEncodeAminoRequest")
proto.RegisterType((*TxEncodeAminoResponse)(nil), "cosmos.tx.v1beta1.TxEncodeAminoResponse")
proto.RegisterType((*TxDecodeAminoRequest)(nil), "cosmos.tx.v1beta1.TxDecodeAminoRequest")
proto.RegisterType((*TxDecodeAminoResponse)(nil), "cosmos.tx.v1beta1.TxDecodeAminoResponse")
}
func init() { proto.RegisterFile("cosmos/tx/v1beta1/service.proto", fileDescriptor_e0b00a618705eca7) }
var fileDescriptor_e0b00a618705eca7 = []byte{
// 1237 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x57, 0x4d, 0x4f, 0x1b, 0x47,
0x18, 0x66, 0x6d, 0x83, 0xcd, 0x6b, 0x08, 0xce, 0x40, 0xc0, 0x38, 0xc4, 0x98, 0x0d, 0x1f, 0x8e,
0x55, 0xbc, 0x0a, 0x4d, 0xaa, 0x24, 0xaa, 0x54, 0xe1, 0x8f, 0x50, 0x92, 0x26, 0x44, 0x6b, 0xaa,
0x28, 0x55, 0x25, 0x6b, 0x6d, 0x4f, 0xec, 0x6d, 0xec, 0x5d, 0xe3, 0x19, 0xd0, 0x5a, 0x14, 0xb5,
0xea, 0xb1, 0x87, 0xaa, 0x52, 0x0f, 0xfd, 0x0f, 0xfd, 0x25, 0x3d, 0x46, 0xea, 0xa5, 0xc7, 0x0a,
0x7a, 0xea, 0xa9, 0x52, 0xff, 0x40, 0xb5, 0x33, 0xb3, 0xb6, 0xd7, 0xde, 0xc5, 0x90, 0x0b, 0xcc,
0xc7, 0xf3, 0xbe, 0xcf, 0x33, 0xef, 0xcc, 0x3c, 0x3b, 0x86, 0xd5, 0xaa, 0x49, 0x5a, 0x26, 0x51,
0xa8, 0xa5, 0x9c, 0xdc, 0xaf, 0x60, 0xaa, 0xdd, 0x57, 0x08, 0xee, 0x9c, 0xe8, 0x55, 0x9c, 0x6d,
0x77, 0x4c, 0x6a, 0xa2, 0x9b, 0x1c, 0x90, 0xa5, 0x56, 0x56, 0x00, 0x12, 0x2b, 0x75, 0xd3, 0xac,
0x37, 0xb1, 0xa2, 0xb5, 0x75, 0x45, 0x33, 0x0c, 0x93, 0x6a, 0x54, 0x37, 0x0d, 0xc2, 0x03, 0x12,
0x77, 0x45, 0xc6, 0x8a, 0x46, 0xb0, 0xa2, 0x55, 0xaa, 0x7a, 0x2f, 0xb1, 0xdd, 0x11, 0xa0, 0xc4,
0x28, 0x2d, 0xb5, 0xc4, 0x5c, 0x66, 0x30, 0xc1, 0xd1, 0x31, 0xee, 0x74, 0x7b, 0x98, 0xb6, 0x56,
0xd7, 0x0d, 0xc6, 0x26, 0xb0, 0x2b, 0x14, 0x1b, 0x35, 0xdc, 0x69, 0xe9, 0x06, 0x55, 0x68, 0xb7,
0x8d, 0x89, 0x52, 0x69, 0x9a, 0xd5, 0x77, 0xbe, 0xb3, 0xec, 0x2f, 0x9f, 0x95, 0xff, 0x93, 0x00,
0xed, 0x61, 0x7a, 0x68, 0x91, 0xe2, 0x09, 0x36, 0xa8, 0x8a, 0x8f, 0x8e, 0x31, 0xa1, 0x28, 0x01,
0x53, 0xd8, 0xee, 0x93, 0xb8, 0x94, 0x0a, 0xa6, 0xa7, 0x73, 0x81, 0xb8, 0xa4, 0x8a, 0x11, 0xf4,
0x0c, 0xa0, 0x2f, 0x21, 0x1e, 0x48, 0x49, 0xe9, 0xe8, 0xce, 0x66, 0x56, 0x54, 0xc8, 0xd6, 0x9b,
0x65, 0x7a, 0x9d, 0x4a, 0x65, 0x5f, 0x69, 0x75, 0x2c, 0xf2, 0xb2, 0x3c, 0x03, 0xd1, 0xe8, 0x21,
0x44, 0xcc, 0x4e, 0x0d, 0x77, 0xca, 0x95, 0x6e, 0x3c, 0x98, 0x92, 0xd2, 0x37, 0x76, 0x12, 0xd9,
0x91, 0x5a, 0x67, 0x0f, 0x6c, 0x48, 0xae, 0xab, 0x86, 0x4d, 0xde, 0x40, 0x08, 0x42, 0x6d, 0xad,
0x8e, 0xe3, 0xa1, 0x94, 0x94, 0x0e, 0xa9, 0xac, 0x8d, 0x16, 0x60, 0xb2, 0xa9, 0xb7, 0x74, 0x1a,
0x9f, 0x64, 0x83, 0xbc, 0x63, 0x8f, 0x32, 0x35, 0xf1, 0xa9, 0x94, 0x94, 0x9e, 0x56, 0x79, 0x47,
0xfe, 0x47, 0x82, 0x79, 0xd7, 0xaa, 0x49, 0xdb, 0x34, 0x08, 0x46, 0x5b, 0x10, 0xa4, 0x16, 0x5f,
0x73, 0x74, 0xe7, 0x96, 0x87, 0x92, 0x43, 0x4b, 0xb5, 0x11, 0x68, 0x0f, 0x66, 0xa8, 0x55, 0xee,
0x88, 0x38, 0x12, 0x0f, 0xb0, 0x88, 0x75, 0x57, 0x15, 0xd8, 0x4e, 0x0f, 0x04, 0x0a, 0xb0, 0x1a,
0xa5, 0xbd, 0x36, 0x41, 0xcf, 0x5d, 0xc5, 0x0c, 0xb2, 0x62, 0x6e, 0x8d, 0x2d, 0x26, 0x8f, 0x1e,
0xa9, 0xe6, 0x02, 0x4c, 0x52, 0x93, 0x6a, 0x4d, 0x51, 0x17, 0xde, 0x91, 0x31, 0xa0, 0x5c, 0xc7,
0xd4, 0x6a, 0x55, 0x8d, 0x50, 0x5b, 0x06, 0xdf, 0xe1, 0x65, 0x88, 0x50, 0xab, 0x5c, 0xe9, 0x52,
0x6c, 0xaf, 0x57, 0x4a, 0xcf, 0xa8, 0x61, 0x6a, 0xe5, 0xec, 0x2e, 0x7a, 0x00, 0xa1, 0x96, 0x59,
0xc3, 0x6c, 0x6b, 0x6f, 0xec, 0xa4, 0x3c, 0xca, 0xd0, 0xcb, 0xf7, 0xc2, 0xac, 0x61, 0x95, 0xa1,
0xe5, 0xaf, 0x61, 0xde, 0x45, 0x23, 0x4a, 0x5a, 0x84, 0xe8, 0x40, 0xa5, 0x18, 0xd5, 0x55, 0x0b,
0x05, 0xfd, 0x42, 0xc9, 0xaf, 0x61, 0xae, 0xa4, 0xb7, 0x8e, 0x9b, 0x1a, 0x75, 0xce, 0x12, 0xba,
0x07, 0x01, 0x6a, 0x89, 0x84, 0xde, 0x7b, 0xc5, 0x0a, 0x14, 0xa0, 0x96, 0x6b, 0xb1, 0x01, 0xd7,
0x62, 0xe5, 0x1f, 0x25, 0x88, 0xf5, 0x33, 0x0b, 0xd1, 0x9f, 0x42, 0xa4, 0xae, 0x91, 0xb2, 0x6e,
0xbc, 0x35, 0x05, 0xc1, 0x9a, 0xbf, 0xe2, 0x3d, 0x8d, 0xec, 0x1b, 0x6f, 0x4d, 0x35, 0x5c, 0xe7,
0x0d, 0xf4, 0x08, 0xa6, 0x3a, 0x98, 0x1c, 0x37, 0xa9, 0xb8, 0x1c, 0x29, 0xff, 0x58, 0x95, 0xe1,
0x54, 0x81, 0x97, 0x65, 0x98, 0x61, 0xc7, 0xd2, 0x59, 0x22, 0x82, 0x50, 0x43, 0x23, 0x0d, 0xa6,
0x61, 0x5a, 0x65, 0x6d, 0xf9, 0x0c, 0x66, 0x05, 0x46, 0x88, 0xdd, 0x18, 0x5b, 0x07, 0x56, 0x83,
0xa1, 0x8d, 0x08, 0x7c, 0xe0, 0x46, 0x58, 0xb0, 0xb8, 0x87, 0x69, 0xce, 0x36, 0x98, 0xd7, 0x3a,
0x6d, 0x1c, 0x5a, 0xc4, 0x11, 0xbb, 0x08, 0x53, 0x0d, 0xac, 0xd7, 0x1b, 0x94, 0x69, 0x09, 0xaa,
0xa2, 0x87, 0x9e, 0x7e, 0xb8, 0x5f, 0x0c, 0x9e, 0x6e, 0xf9, 0x5f, 0x09, 0x96, 0x46, 0xa8, 0xaf,
0x7b, 0x71, 0x1f, 0x40, 0x84, 0x99, 0x63, 0x59, 0xaf, 0x09, 0x29, 0xcb, 0xd9, 0xbe, 0x41, 0x66,
0xb9, 0x35, 0x32, 0x8a, 0xfd, 0x82, 0x1a, 0x66, 0xd0, 0xfd, 0x1a, 0xda, 0x86, 0x49, 0xd6, 0x14,
0x17, 0x74, 0xc9, 0x27, 0x44, 0xe5, 0x28, 0xb4, 0xe7, 0x5a, 0x71, 0xe8, 0x5a, 0x97, 0xda, 0xb5,
0xe4, 0x8f, 0x60, 0xee, 0xd0, 0x2a, 0xe0, 0xaa, 0x7d, 0xcb, 0xc6, 0xde, 0x5b, 0xf9, 0x31, 0xc4,
0xfa, 0xe8, 0x6b, 0x1d, 0x0e, 0xf9, 0x91, 0x4d, 0x54, 0x34, 0x06, 0x89, 0xae, 0x18, 0xb9, 0x6d,
0x93, 0x3a, 0x91, 0x82, 0xf4, 0x12, 0x8d, 0x0f, 0x61, 0xc1, 0x81, 0xef, 0xb6, 0x74, 0xc3, 0x74,
0xd8, 0xee, 0x00, 0x68, 0x76, 0xbf, 0xfc, 0x0d, 0x31, 0x0d, 0x71, 0xde, 0xa7, 0xd9, 0xc8, 0x33,
0x62, 0x1a, 0xf2, 0x13, 0xb8, 0x35, 0x14, 0x26, 0xa8, 0xd6, 0x60, 0x86, 0xc7, 0x55, 0x74, 0x43,
0xeb, 0x74, 0x05, 0x5d, 0x94, 0x8d, 0xe5, 0xd8, 0x90, 0xfc, 0xd8, 0xa6, 0xe4, 0x65, 0x71, 0x51,
0x5e, 0x21, 0xf4, 0x13, 0x9b, 0xd6, 0x15, 0x2a, 0x68, 0x2f, 0x97, 0x9b, 0xf9, 0x1c, 0xc2, 0xe2,
0x9b, 0x85, 0xe2, 0xb0, 0x70, 0xa0, 0x16, 0x8a, 0x6a, 0x39, 0xf7, 0xa6, 0xfc, 0xe5, 0xcb, 0xd2,
0xab, 0x62, 0x7e, 0xff, 0xe9, 0x7e, 0xb1, 0x10, 0x9b, 0x40, 0x31, 0x98, 0xe9, 0xcd, 0xec, 0x96,
0xf2, 0x31, 0x09, 0xdd, 0x84, 0xd9, 0xde, 0x48, 0xa1, 0x58, 0xca, 0xc7, 0x02, 0x99, 0xef, 0x25,
0x98, 0x75, 0xb9, 0x2d, 0x4a, 0x42, 0x22, 0xa7, 0x1e, 0xec, 0x16, 0xf2, 0xbb, 0xa5, 0xc3, 0xf2,
0x8b, 0x83, 0x42, 0x71, 0x28, 0xed, 0x0a, 0x2c, 0x0c, 0xcd, 0xe7, 0xbe, 0x38, 0xc8, 0x3f, 0x8f,
0x49, 0x89, 0x40, 0x44, 0x42, 0x4b, 0x30, 0x3f, 0x34, 0x5b, 0x7a, 0xf3, 0x32, 0x1f, 0x0b, 0xd8,
0x3a, 0x87, 0x26, 0x76, 0xd9, 0x4c, 0x70, 0xe7, 0xb7, 0x69, 0x08, 0x97, 0xf8, 0x73, 0x08, 0x9d,
0x42, 0xc4, 0x31, 0x4b, 0x24, 0x7b, 0x1c, 0x8a, 0x21, 0x8f, 0x4e, 0xdc, 0xbd, 0x14, 0x23, 0x2c,
0x65, 0xf3, 0x87, 0x3f, 0xfe, 0xfe, 0x25, 0x90, 0x7a, 0x22, 0x65, 0xe4, 0xdb, 0x8a, 0xc7, 0x53,
0xcc, 0x21, 0x3c, 0x82, 0x49, 0xe6, 0x7c, 0x68, 0xd5, 0x23, 0xeb, 0xa0, 0x6f, 0x26, 0x52, 0xfe,
0x00, 0xc1, 0xb9, 0xc1, 0x38, 0x57, 0xd1, 0x1d, 0xc5, 0xeb, 0x11, 0x46, 0x94, 0x53, 0xdb, 0x6b,
0xcf, 0xd0, 0x77, 0x10, 0x1d, 0xf8, 0xa8, 0xa1, 0x8d, 0xcb, 0xbe, 0x85, 0x7d, 0xfa, 0xcd, 0x71,
0x30, 0x21, 0x62, 0x8d, 0x89, 0xb8, 0x6d, 0x2f, 0x7c, 0xd1, 0x5b, 0x07, 0xfa, 0x16, 0xa2, 0x03,
0x0f, 0x15, 0x4f, 0x01, 0xa3, 0xcf, 0x37, 0x4f, 0x01, 0x1e, 0xef, 0x1d, 0x39, 0xc9, 0x04, 0xc4,
0x91, 0x1f, 0xfb, 0xaf, 0x12, 0xcc, 0x0d, 0x59, 0x2e, 0xba, 0xe7, 0x9d, 0xdb, 0xe3, 0x8b, 0x90,
0xc8, 0x5c, 0x05, 0x2a, 0xa4, 0x6c, 0x33, 0x29, 0x5b, 0x68, 0xc3, 0x67, 0x43, 0x98, 0xb3, 0x2a,
0xa7, 0xfc, 0x9b, 0x72, 0x86, 0xba, 0x10, 0x71, 0x6e, 0xa6, 0xe7, 0x41, 0x1c, 0xb2, 0x4d, 0xcf,
0x83, 0x38, 0x6c, 0x96, 0xf2, 0x3a, 0xd3, 0x90, 0xb4, 0xf7, 0x63, 0xd9, 0x43, 0x46, 0x8d, 0xd3,
0x31, 0x6a, 0xee, 0x45, 0x3e, 0xd4, 0x2e, 0x23, 0xf5, 0xa1, 0x76, 0x5b, 0xe6, 0x38, 0x6a, 0xcc,
0xe9, 0x7e, 0x92, 0x60, 0xd6, 0xe5, 0x83, 0x68, 0xeb, 0x92, 0xe4, 0x83, 0x6e, 0x97, 0x48, 0x8f,
0x07, 0x0a, 0x29, 0x19, 0x26, 0x65, 0xdd, 0x96, 0xb2, 0xea, 0x2b, 0x45, 0x61, 0x66, 0x27, 0x04,
0x0d, 0x38, 0xa4, 0x8f, 0xa0, 0x51, 0xfb, 0xf5, 0x11, 0xe4, 0x61, 0xb6, 0xe3, 0x04, 0xf1, 0x6d,
0xe1, 0x82, 0x72, 0x9f, 0xfd, 0x7e, 0x9e, 0x94, 0xde, 0x9f, 0x27, 0xa5, 0xbf, 0xce, 0x93, 0xd2,
0xcf, 0x17, 0xc9, 0x89, 0xf7, 0x17, 0xc9, 0x89, 0x3f, 0x2f, 0x92, 0x13, 0x5f, 0x6d, 0xd4, 0x75,
0xda, 0x38, 0xae, 0x64, 0xab, 0x66, 0xcb, 0x49, 0xc2, 0xff, 0x6d, 0x93, 0xda, 0x3b, 0xe7, 0x97,
0x91, 0x55, 0x99, 0x62, 0xbf, 0x8b, 0x3e, 0xfe, 0x3f, 0x00, 0x00, 0xff, 0xff, 0x42, 0xa8, 0xd7,
0x97, 0x14, 0x0e, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// ServiceClient is the client API for Service service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type ServiceClient interface {
// Simulate simulates executing a transaction for estimating gas usage.
Simulate(ctx context.Context, in *SimulateRequest, opts ...grpc.CallOption) (*SimulateResponse, error)
// GetTx fetches a tx by hash.
GetTx(ctx context.Context, in *GetTxRequest, opts ...grpc.CallOption) (*GetTxResponse, error)
// BroadcastTx broadcast transaction.
BroadcastTx(ctx context.Context, in *BroadcastTxRequest, opts ...grpc.CallOption) (*BroadcastTxResponse, error)
// GetTxsEvent fetches txs by event.
GetTxsEvent(ctx context.Context, in *GetTxsEventRequest, opts ...grpc.CallOption) (*GetTxsEventResponse, error)
// GetBlockWithTxs fetches a block with decoded txs.
//
// Since: cosmos-sdk 0.45.2
GetBlockWithTxs(ctx context.Context, in *GetBlockWithTxsRequest, opts ...grpc.CallOption) (*GetBlockWithTxsResponse, error)
// TxDecode decodes the transaction.
//
// Since: cosmos-sdk 0.47
TxDecode(ctx context.Context, in *TxDecodeRequest, opts ...grpc.CallOption) (*TxDecodeResponse, error)
// TxEncode encodes the transaction.
//
// Since: cosmos-sdk 0.47
TxEncode(ctx context.Context, in *TxEncodeRequest, opts ...grpc.CallOption) (*TxEncodeResponse, error)
// TxEncodeAmino encodes an Amino transaction from JSON to encoded bytes.
//
// Since: cosmos-sdk 0.47
TxEncodeAmino(ctx context.Context, in *TxEncodeAminoRequest, opts ...grpc.CallOption) (*TxEncodeAminoResponse, error)
// TxDecodeAmino decodes an Amino transaction from encoded bytes to JSON.
//
// Since: cosmos-sdk 0.47
TxDecodeAmino(ctx context.Context, in *TxDecodeAminoRequest, opts ...grpc.CallOption) (*TxDecodeAminoResponse, error)
}
type serviceClient struct {
cc grpc1.ClientConn
}
func NewServiceClient(cc grpc1.ClientConn) ServiceClient {
return &serviceClient{cc}
}
func (c *serviceClient) Simulate(ctx context.Context, in *SimulateRequest, opts ...grpc.CallOption) (*SimulateResponse, error) {
out := new(SimulateResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/Simulate", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *serviceClient) GetTx(ctx context.Context, in *GetTxRequest, opts ...grpc.CallOption) (*GetTxResponse, error) {
out := new(GetTxResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/GetTx", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *serviceClient) BroadcastTx(ctx context.Context, in *BroadcastTxRequest, opts ...grpc.CallOption) (*BroadcastTxResponse, error) {
out := new(BroadcastTxResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/BroadcastTx", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *serviceClient) GetTxsEvent(ctx context.Context, in *GetTxsEventRequest, opts ...grpc.CallOption) (*GetTxsEventResponse, error) {
out := new(GetTxsEventResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/GetTxsEvent", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *serviceClient) GetBlockWithTxs(ctx context.Context, in *GetBlockWithTxsRequest, opts ...grpc.CallOption) (*GetBlockWithTxsResponse, error) {
out := new(GetBlockWithTxsResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/GetBlockWithTxs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *serviceClient) TxDecode(ctx context.Context, in *TxDecodeRequest, opts ...grpc.CallOption) (*TxDecodeResponse, error) {
out := new(TxDecodeResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/TxDecode", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *serviceClient) TxEncode(ctx context.Context, in *TxEncodeRequest, opts ...grpc.CallOption) (*TxEncodeResponse, error) {
out := new(TxEncodeResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/TxEncode", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *serviceClient) TxEncodeAmino(ctx context.Context, in *TxEncodeAminoRequest, opts ...grpc.CallOption) (*TxEncodeAminoResponse, error) {
out := new(TxEncodeAminoResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/TxEncodeAmino", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *serviceClient) TxDecodeAmino(ctx context.Context, in *TxDecodeAminoRequest, opts ...grpc.CallOption) (*TxDecodeAminoResponse, error) {
out := new(TxDecodeAminoResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/TxDecodeAmino", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// ServiceServer is the server API for Service service.
type ServiceServer interface {
// Simulate simulates executing a transaction for estimating gas usage.
Simulate(context.Context, *SimulateRequest) (*SimulateResponse, error)
// GetTx fetches a tx by hash.
GetTx(context.Context, *GetTxRequest) (*GetTxResponse, error)
// BroadcastTx broadcast transaction.
BroadcastTx(context.Context, *BroadcastTxRequest) (*BroadcastTxResponse, error)
// GetTxsEvent fetches txs by event.
GetTxsEvent(context.Context, *GetTxsEventRequest) (*GetTxsEventResponse, error)
// GetBlockWithTxs fetches a block with decoded txs.
//
// Since: cosmos-sdk 0.45.2
GetBlockWithTxs(context.Context, *GetBlockWithTxsRequest) (*GetBlockWithTxsResponse, error)
// TxDecode decodes the transaction.
//
// Since: cosmos-sdk 0.47
TxDecode(context.Context, *TxDecodeRequest) (*TxDecodeResponse, error)
// TxEncode encodes the transaction.
//
// Since: cosmos-sdk 0.47
TxEncode(context.Context, *TxEncodeRequest) (*TxEncodeResponse, error)
// TxEncodeAmino encodes an Amino transaction from JSON to encoded bytes.
//
// Since: cosmos-sdk 0.47
TxEncodeAmino(context.Context, *TxEncodeAminoRequest) (*TxEncodeAminoResponse, error)
// TxDecodeAmino decodes an Amino transaction from encoded bytes to JSON.
//
// Since: cosmos-sdk 0.47
TxDecodeAmino(context.Context, *TxDecodeAminoRequest) (*TxDecodeAminoResponse, error)
}
// UnimplementedServiceServer can be embedded to have forward compatible implementations.
type UnimplementedServiceServer struct {
}
func (*UnimplementedServiceServer) Simulate(ctx context.Context, req *SimulateRequest) (*SimulateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Simulate not implemented")
}
func (*UnimplementedServiceServer) GetTx(ctx context.Context, req *GetTxRequest) (*GetTxResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetTx not implemented")
}
func (*UnimplementedServiceServer) BroadcastTx(ctx context.Context, req *BroadcastTxRequest) (*BroadcastTxResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BroadcastTx not implemented")
}
func (*UnimplementedServiceServer) GetTxsEvent(ctx context.Context, req *GetTxsEventRequest) (*GetTxsEventResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetTxsEvent not implemented")
}
func (*UnimplementedServiceServer) GetBlockWithTxs(ctx context.Context, req *GetBlockWithTxsRequest) (*GetBlockWithTxsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetBlockWithTxs not implemented")
}
func (*UnimplementedServiceServer) TxDecode(ctx context.Context, req *TxDecodeRequest) (*TxDecodeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method TxDecode not implemented")
}
func (*UnimplementedServiceServer) TxEncode(ctx context.Context, req *TxEncodeRequest) (*TxEncodeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method TxEncode not implemented")
}
func (*UnimplementedServiceServer) TxEncodeAmino(ctx context.Context, req *TxEncodeAminoRequest) (*TxEncodeAminoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method TxEncodeAmino not implemented")
}
func (*UnimplementedServiceServer) TxDecodeAmino(ctx context.Context, req *TxDecodeAminoRequest) (*TxDecodeAminoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method TxDecodeAmino not implemented")
}
func RegisterServiceServer(s grpc1.Server, srv ServiceServer) {
s.RegisterService(&_Service_serviceDesc, srv)
}
func _Service_Simulate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimulateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).Simulate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/Simulate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).Simulate(ctx, req.(*SimulateRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Service_GetTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetTxRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).GetTx(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/GetTx",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).GetTx(ctx, req.(*GetTxRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Service_BroadcastTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BroadcastTxRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).BroadcastTx(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/BroadcastTx",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).BroadcastTx(ctx, req.(*BroadcastTxRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Service_GetTxsEvent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetTxsEventRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).GetTxsEvent(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/GetTxsEvent",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).GetTxsEvent(ctx, req.(*GetTxsEventRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Service_GetBlockWithTxs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetBlockWithTxsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).GetBlockWithTxs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/GetBlockWithTxs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).GetBlockWithTxs(ctx, req.(*GetBlockWithTxsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Service_TxDecode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TxDecodeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).TxDecode(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/TxDecode",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).TxDecode(ctx, req.(*TxDecodeRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Service_TxEncode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TxEncodeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).TxEncode(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/TxEncode",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).TxEncode(ctx, req.(*TxEncodeRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Service_TxEncodeAmino_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TxEncodeAminoRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).TxEncodeAmino(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/TxEncodeAmino",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).TxEncodeAmino(ctx, req.(*TxEncodeAminoRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Service_TxDecodeAmino_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TxDecodeAminoRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).TxDecodeAmino(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/TxDecodeAmino",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).TxDecodeAmino(ctx, req.(*TxDecodeAminoRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Service_serviceDesc = grpc.ServiceDesc{
ServiceName: "cosmos.tx.v1beta1.Service",
HandlerType: (*ServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Simulate",
Handler: _Service_Simulate_Handler,
},
{
MethodName: "GetTx",
Handler: _Service_GetTx_Handler,
},
{
MethodName: "BroadcastTx",
Handler: _Service_BroadcastTx_Handler,
},
{
MethodName: "GetTxsEvent",
Handler: _Service_GetTxsEvent_Handler,
},
{
MethodName: "GetBlockWithTxs",
Handler: _Service_GetBlockWithTxs_Handler,
},
{
MethodName: "TxDecode",
Handler: _Service_TxDecode_Handler,
},
{
MethodName: "TxEncode",
Handler: _Service_TxEncode_Handler,
},
{
MethodName: "TxEncodeAmino",
Handler: _Service_TxEncodeAmino_Handler,
},
{
MethodName: "TxDecodeAmino",
Handler: _Service_TxDecodeAmino_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "cosmos/tx/v1beta1/service.proto",
}
func (m *GetTxsEventRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GetTxsEventRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GetTxsEventRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Query) > 0 {
i -= len(m.Query)
copy(dAtA[i:], m.Query)
i = encodeVarintService(dAtA, i, uint64(len(m.Query)))
i--
dAtA[i] = 0x32
}
if m.Limit != 0 {
i = encodeVarintService(dAtA, i, uint64(m.Limit))
i--
dAtA[i] = 0x28
}
if m.Page != 0 {
i = encodeVarintService(dAtA, i, uint64(m.Page))
i--
dAtA[i] = 0x20
}
if m.OrderBy != 0 {
i = encodeVarintService(dAtA, i, uint64(m.OrderBy))
i--
dAtA[i] = 0x18
}
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.Events) > 0 {
for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Events[iNdEx])
copy(dAtA[i:], m.Events[iNdEx])
i = encodeVarintService(dAtA, i, uint64(len(m.Events[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *GetTxsEventResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GetTxsEventResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GetTxsEventResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Total != 0 {
i = encodeVarintService(dAtA, i, uint64(m.Total))
i--
dAtA[i] = 0x20
}
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
if len(m.TxResponses) > 0 {
for iNdEx := len(m.TxResponses) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.TxResponses[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Txs[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *BroadcastTxRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *BroadcastTxRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *BroadcastTxRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Mode != 0 {
i = encodeVarintService(dAtA, i, uint64(m.Mode))
i--
dAtA[i] = 0x10
}
if len(m.TxBytes) > 0 {
i -= len(m.TxBytes)
copy(dAtA[i:], m.TxBytes)
i = encodeVarintService(dAtA, i, uint64(len(m.TxBytes)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *BroadcastTxResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *BroadcastTxResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *BroadcastTxResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.TxResponse != nil {
{
size, err := m.TxResponse.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *SimulateRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SimulateRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SimulateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.TxBytes) > 0 {
i -= len(m.TxBytes)
copy(dAtA[i:], m.TxBytes)
i = encodeVarintService(dAtA, i, uint64(len(m.TxBytes)))
i--
dAtA[i] = 0x12
}
if m.Tx != nil {
{
size, err := m.Tx.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *SimulateResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SimulateResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SimulateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Result != nil {
{
size, err := m.Result.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if m.GasInfo != nil {
{
size, err := m.GasInfo.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *GetTxRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GetTxRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GetTxRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Hash) > 0 {
i -= len(m.Hash)
copy(dAtA[i:], m.Hash)
i = encodeVarintService(dAtA, i, uint64(len(m.Hash)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *GetTxResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GetTxResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GetTxResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.TxResponse != nil {
{
size, err := m.TxResponse.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if m.Tx != nil {
{
size, err := m.Tx.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *GetBlockWithTxsRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GetBlockWithTxsRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GetBlockWithTxsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if m.Height != 0 {
i = encodeVarintService(dAtA, i, uint64(m.Height))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *GetBlockWithTxsResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GetBlockWithTxsResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GetBlockWithTxsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
if m.Block != nil {
{
size, err := m.Block.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
if m.BlockId != nil {
{
size, err := m.BlockId.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.Txs) > 0 {
for iNdEx := len(m.Txs) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Txs[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *TxDecodeRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxDecodeRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxDecodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.TxBytes) > 0 {
i -= len(m.TxBytes)
copy(dAtA[i:], m.TxBytes)
i = encodeVarintService(dAtA, i, uint64(len(m.TxBytes)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *TxDecodeResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxDecodeResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxDecodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Tx != nil {
{
size, err := m.Tx.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *TxEncodeRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxEncodeRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxEncodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Tx != nil {
{
size, err := m.Tx.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *TxEncodeResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxEncodeResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxEncodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.TxBytes) > 0 {
i -= len(m.TxBytes)
copy(dAtA[i:], m.TxBytes)
i = encodeVarintService(dAtA, i, uint64(len(m.TxBytes)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *TxEncodeAminoRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxEncodeAminoRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxEncodeAminoRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AminoJson) > 0 {
i -= len(m.AminoJson)
copy(dAtA[i:], m.AminoJson)
i = encodeVarintService(dAtA, i, uint64(len(m.AminoJson)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *TxEncodeAminoResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxEncodeAminoResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxEncodeAminoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AminoBinary) > 0 {
i -= len(m.AminoBinary)
copy(dAtA[i:], m.AminoBinary)
i = encodeVarintService(dAtA, i, uint64(len(m.AminoBinary)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *TxDecodeAminoRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxDecodeAminoRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxDecodeAminoRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AminoBinary) > 0 {
i -= len(m.AminoBinary)
copy(dAtA[i:], m.AminoBinary)
i = encodeVarintService(dAtA, i, uint64(len(m.AminoBinary)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *TxDecodeAminoResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TxDecodeAminoResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TxDecodeAminoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AminoJson) > 0 {
i -= len(m.AminoJson)
copy(dAtA[i:], m.AminoJson)
i = encodeVarintService(dAtA, i, uint64(len(m.AminoJson)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintService(dAtA []byte, offset int, v uint64) int {
offset -= sovService(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *GetTxsEventRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Events) > 0 {
for _, s := range m.Events {
l = len(s)
n += 1 + l + sovService(uint64(l))
}
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovService(uint64(l))
}
if m.OrderBy != 0 {
n += 1 + sovService(uint64(m.OrderBy))
}
if m.Page != 0 {
n += 1 + sovService(uint64(m.Page))
}
if m.Limit != 0 {
n += 1 + sovService(uint64(m.Limit))
}
l = len(m.Query)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *GetTxsEventResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Txs) > 0 {
for _, e := range m.Txs {
l = e.Size()
n += 1 + l + sovService(uint64(l))
}
}
if len(m.TxResponses) > 0 {
for _, e := range m.TxResponses {
l = e.Size()
n += 1 + l + sovService(uint64(l))
}
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovService(uint64(l))
}
if m.Total != 0 {
n += 1 + sovService(uint64(m.Total))
}
return n
}
func (m *BroadcastTxRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.TxBytes)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
if m.Mode != 0 {
n += 1 + sovService(uint64(m.Mode))
}
return n
}
func (m *BroadcastTxResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.TxResponse != nil {
l = m.TxResponse.Size()
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *SimulateRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Tx != nil {
l = m.Tx.Size()
n += 1 + l + sovService(uint64(l))
}
l = len(m.TxBytes)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *SimulateResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.GasInfo != nil {
l = m.GasInfo.Size()
n += 1 + l + sovService(uint64(l))
}
if m.Result != nil {
l = m.Result.Size()
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *GetTxRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Hash)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *GetTxResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Tx != nil {
l = m.Tx.Size()
n += 1 + l + sovService(uint64(l))
}
if m.TxResponse != nil {
l = m.TxResponse.Size()
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *GetBlockWithTxsRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Height != 0 {
n += 1 + sovService(uint64(m.Height))
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *GetBlockWithTxsResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Txs) > 0 {
for _, e := range m.Txs {
l = e.Size()
n += 1 + l + sovService(uint64(l))
}
}
if m.BlockId != nil {
l = m.BlockId.Size()
n += 1 + l + sovService(uint64(l))
}
if m.Block != nil {
l = m.Block.Size()
n += 1 + l + sovService(uint64(l))
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *TxDecodeRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.TxBytes)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *TxDecodeResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Tx != nil {
l = m.Tx.Size()
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *TxEncodeRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Tx != nil {
l = m.Tx.Size()
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *TxEncodeResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.TxBytes)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *TxEncodeAminoRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AminoJson)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *TxEncodeAminoResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AminoBinary)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *TxDecodeAminoRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AminoBinary)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func (m *TxDecodeAminoResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AminoJson)
if l > 0 {
n += 1 + l + sovService(uint64(l))
}
return n
}
func sovService(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozService(x uint64) (n int) {
return sovService(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *GetTxsEventRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GetTxsEventRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GetTxsEventRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Events = append(m.Events, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field OrderBy", wireType)
}
m.OrderBy = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.OrderBy |= OrderBy(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Page", wireType)
}
m.Page = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Page |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
}
m.Limit = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Limit |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Query", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Query = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GetTxsEventResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GetTxsEventResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GetTxsEventResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, &Tx{})
if err := m.Txs[len(m.Txs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxResponses", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TxResponses = append(m.TxResponses, &types.TxResponse{})
if err := m.TxResponses[len(m.TxResponses)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType)
}
m.Total = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Total |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *BroadcastTxRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: BroadcastTxRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: BroadcastTxRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxBytes", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TxBytes = append(m.TxBytes[:0], dAtA[iNdEx:postIndex]...)
if m.TxBytes == nil {
m.TxBytes = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Mode", wireType)
}
m.Mode = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Mode |= BroadcastMode(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *BroadcastTxResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: BroadcastTxResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: BroadcastTxResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxResponse", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.TxResponse == nil {
m.TxResponse = &types.TxResponse{}
}
if err := m.TxResponse.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SimulateRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SimulateRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SimulateRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Tx == nil {
m.Tx = &Tx{}
}
if err := m.Tx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxBytes", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TxBytes = append(m.TxBytes[:0], dAtA[iNdEx:postIndex]...)
if m.TxBytes == nil {
m.TxBytes = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SimulateResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SimulateResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SimulateResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field GasInfo", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.GasInfo == nil {
m.GasInfo = &types.GasInfo{}
}
if err := m.GasInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Result == nil {
m.Result = &types.Result{}
}
if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GetTxRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GetTxRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GetTxRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Hash = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GetTxResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GetTxResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GetTxResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Tx == nil {
m.Tx = &Tx{}
}
if err := m.Tx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxResponse", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.TxResponse == nil {
m.TxResponse = &types.TxResponse{}
}
if err := m.TxResponse.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GetBlockWithTxsRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GetBlockWithTxsRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GetBlockWithTxsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType)
}
m.Height = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Height |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GetBlockWithTxsResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GetBlockWithTxsResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GetBlockWithTxsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Txs", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Txs = append(m.Txs, &Tx{})
if err := m.Txs[len(m.Txs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockId", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.BlockId == nil {
m.BlockId = &types1.BlockID{}
}
if err := m.BlockId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Block", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Block == nil {
m.Block = &types1.Block{}
}
if err := m.Block.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxDecodeRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxDecodeRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxDecodeRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxBytes", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TxBytes = append(m.TxBytes[:0], dAtA[iNdEx:postIndex]...)
if m.TxBytes == nil {
m.TxBytes = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxDecodeResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxDecodeResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxDecodeResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Tx == nil {
m.Tx = &Tx{}
}
if err := m.Tx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxEncodeRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxEncodeRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxEncodeRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Tx == nil {
m.Tx = &Tx{}
}
if err := m.Tx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxEncodeResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxEncodeResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxEncodeResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field TxBytes", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TxBytes = append(m.TxBytes[:0], dAtA[iNdEx:postIndex]...)
if m.TxBytes == nil {
m.TxBytes = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxEncodeAminoRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxEncodeAminoRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxEncodeAminoRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AminoJson", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AminoJson = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxEncodeAminoResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxEncodeAminoResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxEncodeAminoResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AminoBinary", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AminoBinary = append(m.AminoBinary[:0], dAtA[iNdEx:postIndex]...)
if m.AminoBinary == nil {
m.AminoBinary = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxDecodeAminoRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxDecodeAminoRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxDecodeAminoRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AminoBinary", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AminoBinary = append(m.AminoBinary[:0], dAtA[iNdEx:postIndex]...)
if m.AminoBinary == nil {
m.AminoBinary = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TxDecodeAminoResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TxDecodeAminoResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TxDecodeAminoResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AminoJson", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthService
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthService
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AminoJson = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthService
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipService(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowService
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowService
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowService
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthService
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupService
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthService
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthService = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowService = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupService = fmt.Errorf("proto: unexpected end of group")
)
package ante
import (
errorsmod "cosmossdk.io/errors"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec/legacy"
"github.com/cosmos/cosmos-sdk/crypto/keys/multisig"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
)
// ValidateBasicDecorator will call tx.ValidateBasic and return any non-nil error.
// If ValidateBasic passes, decorator calls next AnteHandler in chain. Note,
// ValidateBasicDecorator decorator will not get executed on ReCheckTx since it
// is not dependent on application state.
type ValidateBasicDecorator struct{}
func NewValidateBasicDecorator() ValidateBasicDecorator {
return ValidateBasicDecorator{}
}
func (vbd ValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
// no need to validate basic on recheck tx, call next antehandler
if ctx.IsReCheckTx() {
return next(ctx, tx, simulate)
}
if validateBasic, ok := tx.(sdk.HasValidateBasic); ok {
if err := validateBasic.ValidateBasic(); err != nil {
return ctx, err
}
}
return next(ctx, tx, simulate)
}
// ValidateMemoDecorator will validate memo given the parameters passed in
// If memo is too large decorator returns with error, otherwise call next AnteHandler
// CONTRACT: Tx must implement TxWithMemo interface
type ValidateMemoDecorator struct {
ak AccountKeeper
}
func NewValidateMemoDecorator(ak AccountKeeper) ValidateMemoDecorator {
return ValidateMemoDecorator{
ak: ak,
}
}
func (vmd ValidateMemoDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
memoTx, ok := tx.(sdk.TxWithMemo)
if !ok {
return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type")
}
memoLength := len(memoTx.GetMemo())
if memoLength > 0 {
params := vmd.ak.GetParams(ctx)
if uint64(memoLength) > params.MaxMemoCharacters {
return ctx, errorsmod.Wrapf(sdkerrors.ErrMemoTooLarge,
"maximum number of characters is %d but received %d characters",
params.MaxMemoCharacters, memoLength,
)
}
}
return next(ctx, tx, simulate)
}
// ConsumeTxSizeGasDecorator will take in parameters and consume gas proportional
// to the size of tx before calling next AnteHandler. Note, the gas costs will be
// slightly over estimated due to the fact that any given signing account may need
// to be retrieved from state.
//
// CONTRACT: If simulate=true, then signatures must either be completely filled
// in or empty.
// CONTRACT: To use this decorator, signatures of transaction must be represented
// as legacytx.StdSignature otherwise simulate mode will incorrectly estimate gas cost.
type ConsumeTxSizeGasDecorator struct {
ak AccountKeeper
}
func NewConsumeGasForTxSizeDecorator(ak AccountKeeper) ConsumeTxSizeGasDecorator {
return ConsumeTxSizeGasDecorator{
ak: ak,
}
}
func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid tx type")
}
params := cgts.ak.GetParams(ctx)
ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*storetypes.Gas(len(ctx.TxBytes())), "txSize")
// simulate gas cost for signatures in simulate mode
if simulate {
// in simulate mode, each element should be a nil signature
sigs, err := sigTx.GetSignaturesV2()
if err != nil {
return ctx, err
}
n := len(sigs)
signers, err := sigTx.GetSigners()
if err != nil {
return sdk.Context{}, err
}
for i, signer := range signers {
// if signature is already filled in, no need to simulate gas cost
if i < n && !isIncompleteSignature(sigs[i].Data) {
continue
}
var pubkey cryptotypes.PubKey
acc := cgts.ak.GetAccount(ctx, signer)
// use placeholder simSecp256k1Pubkey if sig is nil
if acc == nil || acc.GetPubKey() == nil {
pubkey = simSecp256k1Pubkey
} else {
pubkey = acc.GetPubKey()
}
// use stdsignature to mock the size of a full signature
simSig := legacytx.StdSignature{ //nolint:staticcheck // SA1019: legacytx.StdSignature is deprecated
Signature: simSecp256k1Sig[:],
PubKey: pubkey,
}
sigBz := legacy.Cdc.MustMarshal(simSig)
cost := storetypes.Gas(len(sigBz) + 6)
// If the pubkey is a multi-signature pubkey, then we estimate for the maximum
// number of signers.
if _, ok := pubkey.(*multisig.LegacyAminoPubKey); ok {
cost *= params.TxSigLimit
}
ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*cost, "txSize")
}
}
return next(ctx, tx, simulate)
}
// isIncompleteSignature tests whether SignatureData is fully filled in for simulation purposes
func isIncompleteSignature(data signing.SignatureData) bool {
if data == nil {
return true
}
switch data := data.(type) {
case *signing.SingleSignatureData:
return len(data.Signature) == 0
case *signing.MultiSignatureData:
if len(data.Signatures) == 0 {
return true
}
for _, s := range data.Signatures {
if isIncompleteSignature(s) {
return true
}
}
}
return false
}
type (
// TxTimeoutHeightDecorator defines an AnteHandler decorator that checks for a
// tx height timeout.
TxTimeoutHeightDecorator struct{}
// TxWithTimeoutHeight defines the interface a tx must implement in order for
// TxHeightTimeoutDecorator to process the tx.
TxWithTimeoutHeight interface {
sdk.Tx
GetTimeoutHeight() uint64
}
)
// TxTimeoutHeightDecorator defines an AnteHandler decorator that checks for a
// tx height timeout.
func NewTxTimeoutHeightDecorator() TxTimeoutHeightDecorator {
return TxTimeoutHeightDecorator{}
}
// AnteHandle implements an AnteHandler decorator for the TxHeightTimeoutDecorator
// type where the current block height is checked against the tx's height timeout.
// If a height timeout is provided (non-zero) and is less than the current block
// height, then an error is returned.
func (txh TxTimeoutHeightDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
timeoutTx, ok := tx.(TxWithTimeoutHeight)
if !ok {
return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "expected tx to implement TxWithTimeoutHeight")
}
timeoutHeight := timeoutTx.GetTimeoutHeight()
if timeoutHeight > 0 && uint64(ctx.BlockHeight()) > timeoutHeight {
return ctx, errorsmod.Wrapf(
sdkerrors.ErrTxTimeoutHeight, "block height: %d, timeout height: %d", ctx.BlockHeight(), timeoutHeight,
)
}
return next(ctx, tx, simulate)
}
package keeper
import (
"context"
"errors"
"sort"
"strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/x/auth/types"
)
var _ types.QueryServer = queryServer{}
func NewQueryServer(k AccountKeeper) types.QueryServer {
return queryServer{k: k}
}
type queryServer struct{ k AccountKeeper }
func (s queryServer) AccountAddressByID(ctx context.Context, req *types.QueryAccountAddressByIDRequest) (*types.QueryAccountAddressByIDResponse, error) {
if req == nil {
return nil, status.Errorf(codes.InvalidArgument, "empty request")
}
if req.Id != 0 { // ignoring `0` case since it is default value.
return nil, status.Error(codes.InvalidArgument, "requesting with id isn't supported, try to request using account-id")
}
accID := req.AccountId
address, err := s.k.Accounts.Indexes.Number.MatchExact(ctx, accID)
if err != nil {
return nil, status.Errorf(codes.NotFound, "account address not found with account number %d", accID)
}
return &types.QueryAccountAddressByIDResponse{AccountAddress: address.String()}, nil
}
func (s queryServer) Accounts(ctx context.Context, req *types.QueryAccountsRequest) (*types.QueryAccountsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
accounts, pageRes, err := query.CollectionPaginate(
ctx,
s.k.Accounts,
req.Pagination,
func(_ sdk.AccAddress, value sdk.AccountI) (*codectypes.Any, error) {
return codectypes.NewAnyWithValue(value)
},
)
return &types.QueryAccountsResponse{Accounts: accounts, Pagination: pageRes}, err
}
// Account returns account details based on address
func (s queryServer) Account(ctx context.Context, req *types.QueryAccountRequest) (*types.QueryAccountResponse, error) {
if req == nil {
return nil, status.Errorf(codes.InvalidArgument, "empty request")
}
if req.Address == "" {
return nil, status.Error(codes.InvalidArgument, "Address cannot be empty")
}
addr, err := s.k.addressCodec.StringToBytes(req.Address)
if err != nil {
return nil, err
}
account := s.k.GetAccount(ctx, addr)
if account == nil {
return nil, status.Errorf(codes.NotFound, "account %s not found", req.Address)
}
any, err := codectypes.NewAnyWithValue(account)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
return &types.QueryAccountResponse{Account: any}, nil
}
// Params returns parameters of auth module
func (s queryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
params := s.k.GetParams(ctx)
return &types.QueryParamsResponse{Params: params}, nil
}
// ModuleAccounts returns all the existing Module Accounts
func (s queryServer) ModuleAccounts(c context.Context, req *types.QueryModuleAccountsRequest) (*types.QueryModuleAccountsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
// For deterministic output, sort the permAddrs by module name.
sortedPermAddrs := make([]string, 0, len(s.k.permAddrs))
for moduleName := range s.k.permAddrs {
sortedPermAddrs = append(sortedPermAddrs, moduleName)
}
sort.Strings(sortedPermAddrs)
modAccounts := make([]*codectypes.Any, 0, len(s.k.permAddrs))
for _, moduleName := range sortedPermAddrs {
account := s.k.GetModuleAccount(ctx, moduleName)
if account == nil {
return nil, status.Errorf(codes.NotFound, "account %s not found", moduleName)
}
any, err := codectypes.NewAnyWithValue(account)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
modAccounts = append(modAccounts, any)
}
return &types.QueryModuleAccountsResponse{Accounts: modAccounts}, nil
}
// ModuleAccountByName returns module account by module name
func (s queryServer) ModuleAccountByName(c context.Context, req *types.QueryModuleAccountByNameRequest) (*types.QueryModuleAccountByNameResponse, error) {
if req == nil {
return nil, status.Errorf(codes.InvalidArgument, "empty request")
}
if len(req.Name) == 0 {
return nil, status.Error(codes.InvalidArgument, "module name is empty")
}
ctx := sdk.UnwrapSDKContext(c)
moduleName := req.Name
account := s.k.GetModuleAccount(ctx, moduleName)
if account == nil {
return nil, status.Errorf(codes.NotFound, "account %s not found", moduleName)
}
any, err := codectypes.NewAnyWithValue(account)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
return &types.QueryModuleAccountByNameResponse{Account: any}, nil
}
// Bech32Prefix returns the keeper internally stored bech32 prefix.
func (s queryServer) Bech32Prefix(ctx context.Context, req *types.Bech32PrefixRequest) (*types.Bech32PrefixResponse, error) {
bech32Prefix, err := s.k.getBech32Prefix()
if err != nil {
return nil, err
}
if bech32Prefix == "" {
return &types.Bech32PrefixResponse{Bech32Prefix: "bech32 is not used on this chain"}, nil
}
return &types.Bech32PrefixResponse{Bech32Prefix: bech32Prefix}, nil
}
// AddressBytesToString converts an address from bytes to string, using the
// keeper's bech32 prefix.
func (s queryServer) AddressBytesToString(ctx context.Context, req *types.AddressBytesToStringRequest) (*types.AddressBytesToStringResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if len(req.AddressBytes) == 0 {
return nil, errors.New("empty address bytes is not allowed")
}
text, err := s.k.addressCodec.BytesToString(req.AddressBytes)
if err != nil {
return nil, err
}
return &types.AddressBytesToStringResponse{AddressString: text}, nil
}
// AddressStringToBytes converts an address from string to bytes, using the
// keeper's bech32 prefix.
func (s queryServer) AddressStringToBytes(ctx context.Context, req *types.AddressStringToBytesRequest) (*types.AddressStringToBytesResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if len(strings.TrimSpace(req.AddressString)) == 0 {
return nil, errors.New("empty address string is not allowed")
}
bz, err := s.k.addressCodec.StringToBytes(req.AddressString)
if err != nil {
return nil, err
}
return &types.AddressStringToBytesResponse{AddressBytes: bz}, nil
}
// AccountInfo implements the AccountInfo query.
func (s queryServer) AccountInfo(ctx context.Context, req *types.QueryAccountInfoRequest) (*types.QueryAccountInfoResponse, error) {
if req == nil {
return nil, status.Errorf(codes.InvalidArgument, "empty request")
}
if req.Address == "" {
return nil, status.Error(codes.InvalidArgument, "address cannot be empty")
}
addr, err := s.k.addressCodec.StringToBytes(req.Address)
if err != nil {
return nil, err
}
account := s.k.GetAccount(ctx, addr)
if account == nil {
return nil, status.Errorf(codes.NotFound, "account %s not found", req.Address)
}
// if there is no public key, avoid serializing the nil value
pubKey := account.GetPubKey()
var pkAny *codectypes.Any
if pubKey != nil {
pkAny, err = codectypes.NewAnyWithValue(account.GetPubKey())
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
}
return &types.QueryAccountInfoResponse{
Info: &types.BaseAccount{
Address: req.Address,
PubKey: pkAny,
AccountNumber: account.GetAccountNumber(),
Sequence: account.GetSequence(),
},
}, nil
}
package legacytx
import (
"encoding/json"
"fmt"
"sigs.k8s.io/yaml"
"cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/legacy"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/crypto/types/multisig"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
)
// LegacyMsg defines the old interface a message must fulfill,
// containing Amino signing method.
// Deprecated: Please use `Msg` instead.
type LegacyMsg interface {
sdk.Msg
// Get the canonical byte representation of the Msg.
GetSignBytes() []byte
}
// StdSignDoc is replay-prevention structure.
// It includes the result of msg.GetSignBytes(),
// as well as the ChainID (prevent cross chain replay)
// and the Sequence numbers for each signature (prevent
// inchain replay and enforce tx ordering per account).
type StdSignDoc struct {
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
TimeoutHeight uint64 `json:"timeout_height,omitempty" yaml:"timeout_height"`
ChainID string `json:"chain_id" yaml:"chain_id"`
Memo string `json:"memo" yaml:"memo"`
Fee json.RawMessage `json:"fee" yaml:"fee"`
Msgs []json.RawMessage `json:"msgs" yaml:"msgs"`
}
var RegressionTestingAminoCodec *codec.LegacyAmino
// Deprecated: please delete this code eventually.
func mustSortJSON(bz []byte) []byte {
var c any
err := json.Unmarshal(bz, &c)
if err != nil {
panic(err)
}
js, err := json.Marshal(c)
if err != nil {
panic(err)
}
return js
}
// StdSignBytes returns the bytes to sign for a transaction.
// Deprecated: Please use x/tx/signing/aminojson instead.
func StdSignBytes(chainID string, accnum, sequence, timeout uint64, fee StdFee, msgs []sdk.Msg, memo string) []byte {
if RegressionTestingAminoCodec == nil {
panic(fmt.Errorf("must set RegressionTestingAminoCodec before calling StdSignBytes"))
}
msgsBytes := make([]json.RawMessage, 0, len(msgs))
for _, msg := range msgs {
bz := RegressionTestingAminoCodec.MustMarshalJSON(msg)
msgsBytes = append(msgsBytes, mustSortJSON(bz))
}
bz, err := legacy.Cdc.MarshalJSON(StdSignDoc{
AccountNumber: accnum,
ChainID: chainID,
Fee: json.RawMessage(fee.Bytes()),
Memo: memo,
Msgs: msgsBytes,
Sequence: sequence,
TimeoutHeight: timeout,
})
if err != nil {
panic(err)
}
return mustSortJSON(bz)
}
// Deprecated: StdSignature represents a sig
type StdSignature struct {
cryptotypes.PubKey `json:"pub_key" yaml:"pub_key"` // optional
Signature []byte `json:"signature" yaml:"signature"`
}
// Deprecated
func NewStdSignature(pk cryptotypes.PubKey, sig []byte) StdSignature {
return StdSignature{PubKey: pk, Signature: sig}
}
// GetSignature returns the raw signature bytes.
func (ss StdSignature) GetSignature() []byte {
return ss.Signature
}
// GetPubKey returns the public key of a signature as a cryptotypes.PubKey using the
// Amino codec.
func (ss StdSignature) GetPubKey() cryptotypes.PubKey {
return ss.PubKey
}
// MarshalYAML returns the YAML representation of the signature.
func (ss StdSignature) MarshalYAML() (interface{}, error) {
pk := ""
if ss.PubKey != nil {
pk = ss.PubKey.String()
}
bz, err := yaml.Marshal(struct {
PubKey string `json:"pub_key"`
Signature string `json:"signature"`
}{
pk,
fmt.Sprintf("%X", ss.Signature),
})
if err != nil {
return nil, err
}
return string(bz), err
}
func (ss StdSignature) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
return codectypes.UnpackInterfaces(ss.PubKey, unpacker)
}
// StdSignatureToSignatureV2 converts a StdSignature to a SignatureV2
func StdSignatureToSignatureV2(cdc *codec.LegacyAmino, sig StdSignature) (signing.SignatureV2, error) {
pk := sig.GetPubKey()
data, err := pubKeySigToSigData(cdc, pk, sig.Signature)
if err != nil {
return signing.SignatureV2{}, err
}
return signing.SignatureV2{
PubKey: pk,
Data: data,
}, nil
}
func pubKeySigToSigData(cdc *codec.LegacyAmino, key cryptotypes.PubKey, sig []byte) (signing.SignatureData, error) {
multiPK, ok := key.(multisig.PubKey)
if !ok {
return &signing.SingleSignatureData{
SignMode: signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON,
Signature: sig,
}, nil
}
var multiSig multisig.AminoMultisignature
err := cdc.Unmarshal(sig, &multiSig)
if err != nil {
return nil, err
}
sigs := multiSig.Sigs
sigDatas := make([]signing.SignatureData, len(sigs))
pubKeys := multiPK.GetPubKeys()
bitArray := multiSig.BitArray
n := multiSig.BitArray.Count()
signatures := multisig.NewMultisig(n)
sigIdx := 0
for i := 0; i < n; i++ {
if bitArray.GetIndex(i) {
data, err := pubKeySigToSigData(cdc, pubKeys[i], multiSig.Sigs[sigIdx])
if err != nil {
return nil, errors.Wrapf(err, "Unable to convert Signature to SigData %d", sigIdx)
}
sigDatas[sigIdx] = data
multisig.AddSignature(signatures, data, sigIdx)
sigIdx++
}
}
return signatures, nil
}
package tx
import (
"context"
"fmt"
"strings"
gogogrpc "github.com/cosmos/gogoproto/grpc"
"github.com/golang/protobuf/proto" //nolint:staticcheck // keep legacy for now
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/grpc/cmtservice"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/query"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
)
// baseAppSimulateFn is the signature of the Baseapp#Simulate function.
type baseAppSimulateFn func(txBytes []byte) (sdk.GasInfo, *sdk.Result, error)
// txServer is the server for the protobuf Tx service.
type txServer struct {
clientCtx client.Context
simulate baseAppSimulateFn
interfaceRegistry codectypes.InterfaceRegistry
}
// NewTxServer creates a new Tx service server.
func NewTxServer(clientCtx client.Context, simulate baseAppSimulateFn, interfaceRegistry codectypes.InterfaceRegistry) txtypes.ServiceServer {
return txServer{
clientCtx: clientCtx,
simulate: simulate,
interfaceRegistry: interfaceRegistry,
}
}
var _ txtypes.ServiceServer = txServer{}
// GetTxsEvent implements the ServiceServer.TxsByEvents RPC method.
func (s txServer) GetTxsEvent(ctx context.Context, req *txtypes.GetTxsEventRequest) (*txtypes.GetTxsEventResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "request cannot be nil")
}
orderBy := parseOrderBy(req.OrderBy)
result, err := QueryTxsByEvents(s.clientCtx, int(req.Page), int(req.Limit), req.Query, orderBy)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
txsList := make([]*txtypes.Tx, len(result.Txs))
for i, tx := range result.Txs {
protoTx, ok := tx.Tx.GetCachedValue().(*txtypes.Tx)
if !ok {
return nil, status.Errorf(codes.Internal, "expected %T, got %T", txtypes.Tx{}, tx.Tx.GetCachedValue())
}
txsList[i] = protoTx
}
return &txtypes.GetTxsEventResponse{
Txs: txsList,
TxResponses: result.Txs,
Total: result.TotalCount,
}, nil
}
// Simulate implements the ServiceServer.Simulate RPC method.
func (s txServer) Simulate(ctx context.Context, req *txtypes.SimulateRequest) (*txtypes.SimulateResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx")
}
txBytes := req.TxBytes
if txBytes == nil && req.Tx != nil {
// This block is for backwards-compatibility.
// We used to support passing a `Tx` in req. But if we do that, sig
// verification might not pass, because the .Marshal() below might not
// be the same marshaling done by the client.
var err error
txBytes, err = proto.Marshal(req.Tx)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid tx; %v", err)
}
}
if txBytes == nil {
return nil, status.Errorf(codes.InvalidArgument, "empty txBytes is not allowed")
}
gasInfo, result, err := s.simulate(txBytes)
if err != nil {
return nil, sdkerrors.GRPCWrap(err, codes.Unknown, fmt.Sprintf("%v With gas wanted: '%d' and gas used: '%d' ", err, gasInfo.GasWanted, gasInfo.GasUsed))
}
return &txtypes.SimulateResponse{
GasInfo: &gasInfo,
Result: result,
}, nil
}
// GetTx implements the ServiceServer.GetTx RPC method.
func (s txServer) GetTx(ctx context.Context, req *txtypes.GetTxRequest) (*txtypes.GetTxResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "request cannot be nil")
}
if len(req.Hash) == 0 {
return nil, status.Error(codes.InvalidArgument, "tx hash cannot be empty")
}
// TODO We should also check the proof flag in gRPC header.
// https://github.com/cosmos/cosmos-sdk/issues/7036.
result, err := QueryTx(s.clientCtx, req.Hash)
if err != nil {
if strings.Contains(err.Error(), "not found") {
return nil, status.Errorf(codes.NotFound, "tx not found: %s", req.Hash)
}
return nil, err
}
protoTx, ok := result.Tx.GetCachedValue().(*txtypes.Tx)
if !ok {
return nil, status.Errorf(codes.Internal, "expected %T, got %T", txtypes.Tx{}, result.Tx.GetCachedValue())
}
return &txtypes.GetTxResponse{
Tx: protoTx,
TxResponse: result,
}, nil
}
// protoTxProvider is a type which can provide a proto transaction. It is a
// workaround to get access to the wrapper TxBuilder's method GetProtoTx().
// ref: https://github.com/cosmos/cosmos-sdk/issues/10347
type protoTxProvider interface {
GetProtoTx() *txtypes.Tx
}
// GetBlockWithTxs returns a block with decoded txs.
func (s txServer) GetBlockWithTxs(ctx context.Context, req *txtypes.GetBlockWithTxsRequest) (*txtypes.GetBlockWithTxsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "request cannot be nil")
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
currentHeight := sdkCtx.BlockHeight()
if req.Height < 1 || req.Height > currentHeight {
return nil, sdkerrors.ErrInvalidHeight.Wrapf("requested height %d but height must not be less than 1 "+
"or greater than the current height %d", req.Height, currentHeight)
}
blockID, block, err := cmtservice.GetProtoBlock(ctx, s.clientCtx, &req.Height)
if err != nil {
return nil, err
}
var offset, limit uint64
if req.Pagination != nil {
offset = req.Pagination.Offset
limit = req.Pagination.Limit
} else {
offset = 0
limit = query.DefaultLimit
}
blockTxs := block.Data.Txs
blockTxsLn := uint64(len(blockTxs))
txs := make([]*txtypes.Tx, 0, limit)
if offset >= blockTxsLn && blockTxsLn != 0 {
return nil, sdkerrors.ErrInvalidRequest.Wrapf("out of range: cannot paginate %d txs with offset %d and limit %d", blockTxsLn, offset, limit)
}
decodeTxAt := func(i uint64) error {
tx := blockTxs[i]
txb, err := s.clientCtx.TxConfig.TxDecoder()(tx)
if err != nil {
return err
}
p, ok := txb.(protoTxProvider)
if !ok {
return sdkerrors.ErrTxDecode.Wrapf("could not cast %T to %T", txb, txtypes.Tx{})
}
txs = append(txs, p.GetProtoTx())
return nil
}
if req.Pagination != nil && req.Pagination.Reverse {
for i, count := offset, uint64(0); i > 0 && count != limit; i, count = i-1, count+1 {
if err = decodeTxAt(i); err != nil {
sdkCtx.Logger().Error("failed to decode tx", "error", err)
}
}
} else {
for i, count := offset, uint64(0); i < blockTxsLn && count != limit; i, count = i+1, count+1 {
if err = decodeTxAt(i); err != nil {
sdkCtx.Logger().Error("failed to decode tx", "error", err)
}
}
}
return &txtypes.GetBlockWithTxsResponse{
Txs: txs,
BlockId: &blockID,
Block: block,
Pagination: &query.PageResponse{
Total: blockTxsLn,
},
}, nil
}
// BroadcastTx implements the ServiceServer.BroadcastTx RPC method.
func (s txServer) BroadcastTx(ctx context.Context, req *txtypes.BroadcastTxRequest) (*txtypes.BroadcastTxResponse, error) {
return client.TxServiceBroadcast(ctx, s.clientCtx, req)
}
// TxEncode implements the ServiceServer.TxEncode RPC method.
func (s txServer) TxEncode(ctx context.Context, req *txtypes.TxEncodeRequest) (*txtypes.TxEncodeResponse, error) {
if req.Tx == nil {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx")
}
txBuilder := &wrapper{tx: req.Tx}
encodedBytes, err := s.clientCtx.TxConfig.TxEncoder()(txBuilder)
if err != nil {
return nil, err
}
return &txtypes.TxEncodeResponse{
TxBytes: encodedBytes,
}, nil
}
// TxEncodeAmino implements the ServiceServer.TxEncodeAmino RPC method.
func (s txServer) TxEncodeAmino(ctx context.Context, req *txtypes.TxEncodeAminoRequest) (*txtypes.TxEncodeAminoResponse, error) {
if req.AminoJson == "" {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx json")
}
var stdTx legacytx.StdTx
err := s.clientCtx.LegacyAmino.UnmarshalJSON([]byte(req.AminoJson), &stdTx)
if err != nil {
return nil, err
}
encodedBytes, err := s.clientCtx.LegacyAmino.Marshal(stdTx)
if err != nil {
return nil, err
}
return &txtypes.TxEncodeAminoResponse{
AminoBinary: encodedBytes,
}, nil
}
// TxDecode implements the ServiceServer.TxDecode RPC method.
func (s txServer) TxDecode(ctx context.Context, req *txtypes.TxDecodeRequest) (*txtypes.TxDecodeResponse, error) {
if req.TxBytes == nil {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx bytes")
}
txb, err := s.clientCtx.TxConfig.TxDecoder()(req.TxBytes)
if err != nil {
return nil, err
}
txWrapper, ok := txb.(*wrapper)
if ok {
return &txtypes.TxDecodeResponse{
Tx: txWrapper.tx,
}, nil
}
return nil, fmt.Errorf("expected %T, got %T", &wrapper{}, txb)
}
// TxDecodeAmino implements the ServiceServer.TxDecodeAmino RPC method.
func (s txServer) TxDecodeAmino(ctx context.Context, req *txtypes.TxDecodeAminoRequest) (*txtypes.TxDecodeAminoResponse, error) {
if req.AminoBinary == nil {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx bytes")
}
var stdTx legacytx.StdTx
err := s.clientCtx.LegacyAmino.Unmarshal(req.AminoBinary, &stdTx)
if err != nil {
return nil, err
}
res, err := s.clientCtx.LegacyAmino.MarshalJSON(stdTx)
if err != nil {
return nil, err
}
return &txtypes.TxDecodeAminoResponse{
AminoJson: string(res),
}, nil
}
// RegisterTxService registers the tx service on the gRPC router.
func RegisterTxService(
qrt gogogrpc.Server,
clientCtx client.Context,
simulateFn baseAppSimulateFn,
interfaceRegistry codectypes.InterfaceRegistry,
) {
txtypes.RegisterServiceServer(
qrt,
NewTxServer(clientCtx, simulateFn, interfaceRegistry),
)
}
// RegisterGRPCGatewayRoutes mounts the tx service's GRPC-gateway routes on the
// given Mux.
func RegisterGRPCGatewayRoutes(clientConn gogogrpc.ClientConn, mux *runtime.ServeMux) {
txtypes.RegisterServiceHandlerClient(context.Background(), mux, txtypes.NewServiceClient(clientConn))
}
func parseOrderBy(orderBy txtypes.OrderBy) string {
switch orderBy {
case txtypes.OrderBy_ORDER_BY_ASC:
return "asc"
case txtypes.OrderBy_ORDER_BY_DESC:
return "desc"
default:
return "" // Defaults to CometBFT's default, which is `asc` now.
}
}
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/auth/v1beta1/query.proto
package types
import (
context "context"
fmt "fmt"
_ "github.com/cosmos/cosmos-proto"
types "github.com/cosmos/cosmos-sdk/codec/types"
query "github.com/cosmos/cosmos-sdk/types/query"
_ "github.com/cosmos/gogoproto/gogoproto"
grpc1 "github.com/cosmos/gogoproto/grpc"
proto "github.com/cosmos/gogoproto/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// QueryAccountsRequest is the request type for the Query/Accounts RPC method.
//
// Since: cosmos-sdk 0.43
type QueryAccountsRequest struct {
// pagination defines an optional pagination for the request.
Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryAccountsRequest) Reset() { *m = QueryAccountsRequest{} }
func (m *QueryAccountsRequest) String() string { return proto.CompactTextString(m) }
func (*QueryAccountsRequest) ProtoMessage() {}
func (*QueryAccountsRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{0}
}
func (m *QueryAccountsRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAccountsRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAccountsRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAccountsRequest.Merge(m, src)
}
func (m *QueryAccountsRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryAccountsRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAccountsRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAccountsRequest proto.InternalMessageInfo
func (m *QueryAccountsRequest) GetPagination() *query.PageRequest {
if m != nil {
return m.Pagination
}
return nil
}
// QueryAccountsResponse is the response type for the Query/Accounts RPC method.
//
// Since: cosmos-sdk 0.43
type QueryAccountsResponse struct {
// accounts are the existing accounts
Accounts []*types.Any `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts,omitempty"`
// pagination defines the pagination in the response.
Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
func (m *QueryAccountsResponse) Reset() { *m = QueryAccountsResponse{} }
func (m *QueryAccountsResponse) String() string { return proto.CompactTextString(m) }
func (*QueryAccountsResponse) ProtoMessage() {}
func (*QueryAccountsResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{1}
}
func (m *QueryAccountsResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAccountsResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAccountsResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAccountsResponse.Merge(m, src)
}
func (m *QueryAccountsResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryAccountsResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAccountsResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAccountsResponse proto.InternalMessageInfo
func (m *QueryAccountsResponse) GetAccounts() []*types.Any {
if m != nil {
return m.Accounts
}
return nil
}
func (m *QueryAccountsResponse) GetPagination() *query.PageResponse {
if m != nil {
return m.Pagination
}
return nil
}
// QueryAccountRequest is the request type for the Query/Account RPC method.
type QueryAccountRequest struct {
// address defines the address to query for.
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
}
func (m *QueryAccountRequest) Reset() { *m = QueryAccountRequest{} }
func (m *QueryAccountRequest) String() string { return proto.CompactTextString(m) }
func (*QueryAccountRequest) ProtoMessage() {}
func (*QueryAccountRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{2}
}
func (m *QueryAccountRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAccountRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAccountRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAccountRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAccountRequest.Merge(m, src)
}
func (m *QueryAccountRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryAccountRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAccountRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAccountRequest proto.InternalMessageInfo
// QueryAccountResponse is the response type for the Query/Account RPC method.
type QueryAccountResponse struct {
// account defines the account of the corresponding address.
Account *types.Any `protobuf:"bytes,1,opt,name=account,proto3" json:"account,omitempty"`
}
func (m *QueryAccountResponse) Reset() { *m = QueryAccountResponse{} }
func (m *QueryAccountResponse) String() string { return proto.CompactTextString(m) }
func (*QueryAccountResponse) ProtoMessage() {}
func (*QueryAccountResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{3}
}
func (m *QueryAccountResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAccountResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAccountResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAccountResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAccountResponse.Merge(m, src)
}
func (m *QueryAccountResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryAccountResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAccountResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAccountResponse proto.InternalMessageInfo
func (m *QueryAccountResponse) GetAccount() *types.Any {
if m != nil {
return m.Account
}
return nil
}
// QueryParamsRequest is the request type for the Query/Params RPC method.
type QueryParamsRequest struct {
}
func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} }
func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) }
func (*QueryParamsRequest) ProtoMessage() {}
func (*QueryParamsRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{4}
}
func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryParamsRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryParamsRequest.Merge(m, src)
}
func (m *QueryParamsRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryParamsRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo
// QueryParamsResponse is the response type for the Query/Params RPC method.
type QueryParamsResponse struct {
// params defines the parameters of the module.
Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"`
}
func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} }
func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) }
func (*QueryParamsResponse) ProtoMessage() {}
func (*QueryParamsResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{5}
}
func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryParamsResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryParamsResponse.Merge(m, src)
}
func (m *QueryParamsResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryParamsResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo
func (m *QueryParamsResponse) GetParams() Params {
if m != nil {
return m.Params
}
return Params{}
}
// QueryModuleAccountsRequest is the request type for the Query/ModuleAccounts RPC method.
//
// Since: cosmos-sdk 0.46
type QueryModuleAccountsRequest struct {
}
func (m *QueryModuleAccountsRequest) Reset() { *m = QueryModuleAccountsRequest{} }
func (m *QueryModuleAccountsRequest) String() string { return proto.CompactTextString(m) }
func (*QueryModuleAccountsRequest) ProtoMessage() {}
func (*QueryModuleAccountsRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{6}
}
func (m *QueryModuleAccountsRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryModuleAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryModuleAccountsRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryModuleAccountsRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryModuleAccountsRequest.Merge(m, src)
}
func (m *QueryModuleAccountsRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryModuleAccountsRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryModuleAccountsRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryModuleAccountsRequest proto.InternalMessageInfo
// QueryModuleAccountsResponse is the response type for the Query/ModuleAccounts RPC method.
//
// Since: cosmos-sdk 0.46
type QueryModuleAccountsResponse struct {
Accounts []*types.Any `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts,omitempty"`
}
func (m *QueryModuleAccountsResponse) Reset() { *m = QueryModuleAccountsResponse{} }
func (m *QueryModuleAccountsResponse) String() string { return proto.CompactTextString(m) }
func (*QueryModuleAccountsResponse) ProtoMessage() {}
func (*QueryModuleAccountsResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{7}
}
func (m *QueryModuleAccountsResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryModuleAccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryModuleAccountsResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryModuleAccountsResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryModuleAccountsResponse.Merge(m, src)
}
func (m *QueryModuleAccountsResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryModuleAccountsResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryModuleAccountsResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryModuleAccountsResponse proto.InternalMessageInfo
func (m *QueryModuleAccountsResponse) GetAccounts() []*types.Any {
if m != nil {
return m.Accounts
}
return nil
}
// QueryModuleAccountByNameRequest is the request type for the Query/ModuleAccountByName RPC method.
type QueryModuleAccountByNameRequest struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
}
func (m *QueryModuleAccountByNameRequest) Reset() { *m = QueryModuleAccountByNameRequest{} }
func (m *QueryModuleAccountByNameRequest) String() string { return proto.CompactTextString(m) }
func (*QueryModuleAccountByNameRequest) ProtoMessage() {}
func (*QueryModuleAccountByNameRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{8}
}
func (m *QueryModuleAccountByNameRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryModuleAccountByNameRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryModuleAccountByNameRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryModuleAccountByNameRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryModuleAccountByNameRequest.Merge(m, src)
}
func (m *QueryModuleAccountByNameRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryModuleAccountByNameRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryModuleAccountByNameRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryModuleAccountByNameRequest proto.InternalMessageInfo
func (m *QueryModuleAccountByNameRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
// QueryModuleAccountByNameResponse is the response type for the Query/ModuleAccountByName RPC method.
type QueryModuleAccountByNameResponse struct {
Account *types.Any `protobuf:"bytes,1,opt,name=account,proto3" json:"account,omitempty"`
}
func (m *QueryModuleAccountByNameResponse) Reset() { *m = QueryModuleAccountByNameResponse{} }
func (m *QueryModuleAccountByNameResponse) String() string { return proto.CompactTextString(m) }
func (*QueryModuleAccountByNameResponse) ProtoMessage() {}
func (*QueryModuleAccountByNameResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{9}
}
func (m *QueryModuleAccountByNameResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryModuleAccountByNameResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryModuleAccountByNameResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryModuleAccountByNameResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryModuleAccountByNameResponse.Merge(m, src)
}
func (m *QueryModuleAccountByNameResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryModuleAccountByNameResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryModuleAccountByNameResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryModuleAccountByNameResponse proto.InternalMessageInfo
func (m *QueryModuleAccountByNameResponse) GetAccount() *types.Any {
if m != nil {
return m.Account
}
return nil
}
// Bech32PrefixRequest is the request type for Bech32Prefix rpc method.
//
// Since: cosmos-sdk 0.46
type Bech32PrefixRequest struct {
}
func (m *Bech32PrefixRequest) Reset() { *m = Bech32PrefixRequest{} }
func (m *Bech32PrefixRequest) String() string { return proto.CompactTextString(m) }
func (*Bech32PrefixRequest) ProtoMessage() {}
func (*Bech32PrefixRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{10}
}
func (m *Bech32PrefixRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Bech32PrefixRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Bech32PrefixRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Bech32PrefixRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_Bech32PrefixRequest.Merge(m, src)
}
func (m *Bech32PrefixRequest) XXX_Size() int {
return m.Size()
}
func (m *Bech32PrefixRequest) XXX_DiscardUnknown() {
xxx_messageInfo_Bech32PrefixRequest.DiscardUnknown(m)
}
var xxx_messageInfo_Bech32PrefixRequest proto.InternalMessageInfo
// Bech32PrefixResponse is the response type for Bech32Prefix rpc method.
//
// Since: cosmos-sdk 0.46
type Bech32PrefixResponse struct {
Bech32Prefix string `protobuf:"bytes,1,opt,name=bech32_prefix,json=bech32Prefix,proto3" json:"bech32_prefix,omitempty"`
}
func (m *Bech32PrefixResponse) Reset() { *m = Bech32PrefixResponse{} }
func (m *Bech32PrefixResponse) String() string { return proto.CompactTextString(m) }
func (*Bech32PrefixResponse) ProtoMessage() {}
func (*Bech32PrefixResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{11}
}
func (m *Bech32PrefixResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Bech32PrefixResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Bech32PrefixResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Bech32PrefixResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_Bech32PrefixResponse.Merge(m, src)
}
func (m *Bech32PrefixResponse) XXX_Size() int {
return m.Size()
}
func (m *Bech32PrefixResponse) XXX_DiscardUnknown() {
xxx_messageInfo_Bech32PrefixResponse.DiscardUnknown(m)
}
var xxx_messageInfo_Bech32PrefixResponse proto.InternalMessageInfo
func (m *Bech32PrefixResponse) GetBech32Prefix() string {
if m != nil {
return m.Bech32Prefix
}
return ""
}
// AddressBytesToStringRequest is the request type for AddressString rpc method.
//
// Since: cosmos-sdk 0.46
type AddressBytesToStringRequest struct {
AddressBytes []byte `protobuf:"bytes,1,opt,name=address_bytes,json=addressBytes,proto3" json:"address_bytes,omitempty"`
}
func (m *AddressBytesToStringRequest) Reset() { *m = AddressBytesToStringRequest{} }
func (m *AddressBytesToStringRequest) String() string { return proto.CompactTextString(m) }
func (*AddressBytesToStringRequest) ProtoMessage() {}
func (*AddressBytesToStringRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{12}
}
func (m *AddressBytesToStringRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *AddressBytesToStringRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_AddressBytesToStringRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *AddressBytesToStringRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_AddressBytesToStringRequest.Merge(m, src)
}
func (m *AddressBytesToStringRequest) XXX_Size() int {
return m.Size()
}
func (m *AddressBytesToStringRequest) XXX_DiscardUnknown() {
xxx_messageInfo_AddressBytesToStringRequest.DiscardUnknown(m)
}
var xxx_messageInfo_AddressBytesToStringRequest proto.InternalMessageInfo
func (m *AddressBytesToStringRequest) GetAddressBytes() []byte {
if m != nil {
return m.AddressBytes
}
return nil
}
// AddressBytesToStringResponse is the response type for AddressString rpc method.
//
// Since: cosmos-sdk 0.46
type AddressBytesToStringResponse struct {
AddressString string `protobuf:"bytes,1,opt,name=address_string,json=addressString,proto3" json:"address_string,omitempty"`
}
func (m *AddressBytesToStringResponse) Reset() { *m = AddressBytesToStringResponse{} }
func (m *AddressBytesToStringResponse) String() string { return proto.CompactTextString(m) }
func (*AddressBytesToStringResponse) ProtoMessage() {}
func (*AddressBytesToStringResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{13}
}
func (m *AddressBytesToStringResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *AddressBytesToStringResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_AddressBytesToStringResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *AddressBytesToStringResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_AddressBytesToStringResponse.Merge(m, src)
}
func (m *AddressBytesToStringResponse) XXX_Size() int {
return m.Size()
}
func (m *AddressBytesToStringResponse) XXX_DiscardUnknown() {
xxx_messageInfo_AddressBytesToStringResponse.DiscardUnknown(m)
}
var xxx_messageInfo_AddressBytesToStringResponse proto.InternalMessageInfo
func (m *AddressBytesToStringResponse) GetAddressString() string {
if m != nil {
return m.AddressString
}
return ""
}
// AddressStringToBytesRequest is the request type for AccountBytes rpc method.
//
// Since: cosmos-sdk 0.46
type AddressStringToBytesRequest struct {
AddressString string `protobuf:"bytes,1,opt,name=address_string,json=addressString,proto3" json:"address_string,omitempty"`
}
func (m *AddressStringToBytesRequest) Reset() { *m = AddressStringToBytesRequest{} }
func (m *AddressStringToBytesRequest) String() string { return proto.CompactTextString(m) }
func (*AddressStringToBytesRequest) ProtoMessage() {}
func (*AddressStringToBytesRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{14}
}
func (m *AddressStringToBytesRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *AddressStringToBytesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_AddressStringToBytesRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *AddressStringToBytesRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_AddressStringToBytesRequest.Merge(m, src)
}
func (m *AddressStringToBytesRequest) XXX_Size() int {
return m.Size()
}
func (m *AddressStringToBytesRequest) XXX_DiscardUnknown() {
xxx_messageInfo_AddressStringToBytesRequest.DiscardUnknown(m)
}
var xxx_messageInfo_AddressStringToBytesRequest proto.InternalMessageInfo
func (m *AddressStringToBytesRequest) GetAddressString() string {
if m != nil {
return m.AddressString
}
return ""
}
// AddressStringToBytesResponse is the response type for AddressBytes rpc method.
//
// Since: cosmos-sdk 0.46
type AddressStringToBytesResponse struct {
AddressBytes []byte `protobuf:"bytes,1,opt,name=address_bytes,json=addressBytes,proto3" json:"address_bytes,omitempty"`
}
func (m *AddressStringToBytesResponse) Reset() { *m = AddressStringToBytesResponse{} }
func (m *AddressStringToBytesResponse) String() string { return proto.CompactTextString(m) }
func (*AddressStringToBytesResponse) ProtoMessage() {}
func (*AddressStringToBytesResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{15}
}
func (m *AddressStringToBytesResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *AddressStringToBytesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_AddressStringToBytesResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *AddressStringToBytesResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_AddressStringToBytesResponse.Merge(m, src)
}
func (m *AddressStringToBytesResponse) XXX_Size() int {
return m.Size()
}
func (m *AddressStringToBytesResponse) XXX_DiscardUnknown() {
xxx_messageInfo_AddressStringToBytesResponse.DiscardUnknown(m)
}
var xxx_messageInfo_AddressStringToBytesResponse proto.InternalMessageInfo
func (m *AddressStringToBytesResponse) GetAddressBytes() []byte {
if m != nil {
return m.AddressBytes
}
return nil
}
// QueryAccountAddressByIDRequest is the request type for AccountAddressByID rpc method
//
// Since: cosmos-sdk 0.46.2
type QueryAccountAddressByIDRequest struct {
// Deprecated, use account_id instead
//
// id is the account number of the address to be queried. This field
// should have been an uint64 (like all account numbers), and will be
// updated to uint64 in a future version of the auth query.
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` // Deprecated: Do not use.
// account_id is the account number of the address to be queried.
//
// Since: cosmos-sdk 0.47
AccountId uint64 `protobuf:"varint,2,opt,name=account_id,json=accountId,proto3" json:"account_id,omitempty"`
}
func (m *QueryAccountAddressByIDRequest) Reset() { *m = QueryAccountAddressByIDRequest{} }
func (m *QueryAccountAddressByIDRequest) String() string { return proto.CompactTextString(m) }
func (*QueryAccountAddressByIDRequest) ProtoMessage() {}
func (*QueryAccountAddressByIDRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{16}
}
func (m *QueryAccountAddressByIDRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAccountAddressByIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAccountAddressByIDRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAccountAddressByIDRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAccountAddressByIDRequest.Merge(m, src)
}
func (m *QueryAccountAddressByIDRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryAccountAddressByIDRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAccountAddressByIDRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAccountAddressByIDRequest proto.InternalMessageInfo
// Deprecated: Do not use.
func (m *QueryAccountAddressByIDRequest) GetId() int64 {
if m != nil {
return m.Id
}
return 0
}
func (m *QueryAccountAddressByIDRequest) GetAccountId() uint64 {
if m != nil {
return m.AccountId
}
return 0
}
// QueryAccountAddressByIDResponse is the response type for AccountAddressByID rpc method
//
// Since: cosmos-sdk 0.46.2
type QueryAccountAddressByIDResponse struct {
AccountAddress string `protobuf:"bytes,1,opt,name=account_address,json=accountAddress,proto3" json:"account_address,omitempty"`
}
func (m *QueryAccountAddressByIDResponse) Reset() { *m = QueryAccountAddressByIDResponse{} }
func (m *QueryAccountAddressByIDResponse) String() string { return proto.CompactTextString(m) }
func (*QueryAccountAddressByIDResponse) ProtoMessage() {}
func (*QueryAccountAddressByIDResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{17}
}
func (m *QueryAccountAddressByIDResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAccountAddressByIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAccountAddressByIDResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAccountAddressByIDResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAccountAddressByIDResponse.Merge(m, src)
}
func (m *QueryAccountAddressByIDResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryAccountAddressByIDResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAccountAddressByIDResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAccountAddressByIDResponse proto.InternalMessageInfo
func (m *QueryAccountAddressByIDResponse) GetAccountAddress() string {
if m != nil {
return m.AccountAddress
}
return ""
}
// QueryAccountInfoRequest is the Query/AccountInfo request type.
//
// Since: cosmos-sdk 0.47
type QueryAccountInfoRequest struct {
// address is the account address string.
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
}
func (m *QueryAccountInfoRequest) Reset() { *m = QueryAccountInfoRequest{} }
func (m *QueryAccountInfoRequest) String() string { return proto.CompactTextString(m) }
func (*QueryAccountInfoRequest) ProtoMessage() {}
func (*QueryAccountInfoRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{18}
}
func (m *QueryAccountInfoRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAccountInfoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAccountInfoRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAccountInfoRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAccountInfoRequest.Merge(m, src)
}
func (m *QueryAccountInfoRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryAccountInfoRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAccountInfoRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAccountInfoRequest proto.InternalMessageInfo
func (m *QueryAccountInfoRequest) GetAddress() string {
if m != nil {
return m.Address
}
return ""
}
// QueryAccountInfoResponse is the Query/AccountInfo response type.
//
// Since: cosmos-sdk 0.47
type QueryAccountInfoResponse struct {
// info is the account info which is represented by BaseAccount.
Info *BaseAccount `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"`
}
func (m *QueryAccountInfoResponse) Reset() { *m = QueryAccountInfoResponse{} }
func (m *QueryAccountInfoResponse) String() string { return proto.CompactTextString(m) }
func (*QueryAccountInfoResponse) ProtoMessage() {}
func (*QueryAccountInfoResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_c451370b3929a27c, []int{19}
}
func (m *QueryAccountInfoResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryAccountInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryAccountInfoResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryAccountInfoResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryAccountInfoResponse.Merge(m, src)
}
func (m *QueryAccountInfoResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryAccountInfoResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryAccountInfoResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryAccountInfoResponse proto.InternalMessageInfo
func (m *QueryAccountInfoResponse) GetInfo() *BaseAccount {
if m != nil {
return m.Info
}
return nil
}
func init() {
proto.RegisterType((*QueryAccountsRequest)(nil), "cosmos.auth.v1beta1.QueryAccountsRequest")
proto.RegisterType((*QueryAccountsResponse)(nil), "cosmos.auth.v1beta1.QueryAccountsResponse")
proto.RegisterType((*QueryAccountRequest)(nil), "cosmos.auth.v1beta1.QueryAccountRequest")
proto.RegisterType((*QueryAccountResponse)(nil), "cosmos.auth.v1beta1.QueryAccountResponse")
proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.auth.v1beta1.QueryParamsRequest")
proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.auth.v1beta1.QueryParamsResponse")
proto.RegisterType((*QueryModuleAccountsRequest)(nil), "cosmos.auth.v1beta1.QueryModuleAccountsRequest")
proto.RegisterType((*QueryModuleAccountsResponse)(nil), "cosmos.auth.v1beta1.QueryModuleAccountsResponse")
proto.RegisterType((*QueryModuleAccountByNameRequest)(nil), "cosmos.auth.v1beta1.QueryModuleAccountByNameRequest")
proto.RegisterType((*QueryModuleAccountByNameResponse)(nil), "cosmos.auth.v1beta1.QueryModuleAccountByNameResponse")
proto.RegisterType((*Bech32PrefixRequest)(nil), "cosmos.auth.v1beta1.Bech32PrefixRequest")
proto.RegisterType((*Bech32PrefixResponse)(nil), "cosmos.auth.v1beta1.Bech32PrefixResponse")
proto.RegisterType((*AddressBytesToStringRequest)(nil), "cosmos.auth.v1beta1.AddressBytesToStringRequest")
proto.RegisterType((*AddressBytesToStringResponse)(nil), "cosmos.auth.v1beta1.AddressBytesToStringResponse")
proto.RegisterType((*AddressStringToBytesRequest)(nil), "cosmos.auth.v1beta1.AddressStringToBytesRequest")
proto.RegisterType((*AddressStringToBytesResponse)(nil), "cosmos.auth.v1beta1.AddressStringToBytesResponse")
proto.RegisterType((*QueryAccountAddressByIDRequest)(nil), "cosmos.auth.v1beta1.QueryAccountAddressByIDRequest")
proto.RegisterType((*QueryAccountAddressByIDResponse)(nil), "cosmos.auth.v1beta1.QueryAccountAddressByIDResponse")
proto.RegisterType((*QueryAccountInfoRequest)(nil), "cosmos.auth.v1beta1.QueryAccountInfoRequest")
proto.RegisterType((*QueryAccountInfoResponse)(nil), "cosmos.auth.v1beta1.QueryAccountInfoResponse")
}
func init() { proto.RegisterFile("cosmos/auth/v1beta1/query.proto", fileDescriptor_c451370b3929a27c) }
var fileDescriptor_c451370b3929a27c = []byte{
// 1065 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x96, 0xcf, 0x6f, 0xe3, 0x44,
0x14, 0xc7, 0xe3, 0x6e, 0x69, 0xbb, 0xaf, 0xd9, 0x22, 0x4d, 0xb3, 0x22, 0x38, 0x6d, 0x12, 0xb9,
0xd0, 0xa6, 0x65, 0x63, 0xd3, 0x34, 0x2b, 0xf1, 0xe3, 0x54, 0xef, 0x02, 0xea, 0x61, 0x51, 0x70,
0x57, 0x08, 0x71, 0x20, 0x72, 0x62, 0x27, 0xb5, 0xd8, 0x78, 0xb2, 0xb1, 0x03, 0x1b, 0xaa, 0x5c,
0x90, 0x90, 0x7a, 0x41, 0x42, 0x82, 0x3f, 0x60, 0x0f, 0x88, 0xf3, 0x22, 0x95, 0x1b, 0x7f, 0xc0,
0x6a, 0x4f, 0x2b, 0xb8, 0x70, 0x42, 0xa8, 0x45, 0x82, 0x1b, 0xff, 0x02, 0xca, 0xcc, 0xb3, 0x63,
0xb7, 0x93, 0xc4, 0x85, 0x53, 0x9d, 0x99, 0xf7, 0xbe, 0xef, 0x33, 0x6f, 0x9e, 0xfd, 0x2d, 0x14,
0x9a, 0xd4, 0xeb, 0x50, 0x4f, 0x33, 0xfb, 0xfe, 0x91, 0xf6, 0xd9, 0x6e, 0xc3, 0xf6, 0xcd, 0x5d,
0xed, 0x61, 0xdf, 0xee, 0x0d, 0xd4, 0x6e, 0x8f, 0xfa, 0x94, 0xac, 0xf2, 0x00, 0x75, 0x14, 0xa0,
0x62, 0x80, 0xbc, 0x83, 0x59, 0x0d, 0xd3, 0xb3, 0x79, 0x74, 0x98, 0xdb, 0x35, 0xdb, 0x8e, 0x6b,
0xfa, 0x0e, 0x75, 0xb9, 0x80, 0x9c, 0x69, 0xd3, 0x36, 0x65, 0x8f, 0xda, 0xe8, 0x09, 0x57, 0x5f,
0x6e, 0x53, 0xda, 0x7e, 0x60, 0x6b, 0xec, 0x57, 0xa3, 0xdf, 0xd2, 0x4c, 0x17, 0x2b, 0xca, 0x6b,
0xb8, 0x65, 0x76, 0x1d, 0xcd, 0x74, 0x5d, 0xea, 0x33, 0x35, 0x0f, 0x77, 0xf3, 0x22, 0x60, 0x06,
0x87, 0xc2, 0x7c, 0xbf, 0xce, 0x2b, 0x22, 0x3c, 0xdf, 0xca, 0x61, 0x6a, 0x00, 0x1c, 0x3d, 0xa7,
0xf2, 0x09, 0x64, 0x3e, 0x18, 0xfd, 0xdc, 0x6f, 0x36, 0x69, 0xdf, 0xf5, 0x3d, 0xc3, 0x7e, 0xd8,
0xb7, 0x3d, 0x9f, 0xbc, 0x0b, 0x30, 0x3e, 0x52, 0x56, 0x2a, 0x4a, 0xa5, 0xe5, 0xca, 0xa6, 0x8a,
0xba, 0xa3, 0xf3, 0xab, 0x5c, 0x05, 0x51, 0xd4, 0x9a, 0xd9, 0xb6, 0x31, 0xd7, 0x88, 0x64, 0x2a,
0xa7, 0x12, 0xdc, 0xbc, 0x50, 0xc0, 0xeb, 0x52, 0xd7, 0xb3, 0x89, 0x01, 0x4b, 0x26, 0xae, 0x65,
0xa5, 0xe2, 0xb5, 0xd2, 0x72, 0x25, 0xa3, 0xf2, 0x16, 0xa8, 0x41, 0x77, 0xd4, 0x7d, 0x77, 0xa0,
0x17, 0x9f, 0x9d, 0x96, 0xd7, 0x04, 0xb7, 0xa1, 0xa2, 0xe2, 0x81, 0x11, 0xea, 0x90, 0xf7, 0x62,
0xd4, 0x73, 0x8c, 0x7a, 0x6b, 0x26, 0x35, 0x07, 0x8a, 0x61, 0x1f, 0xc2, 0x6a, 0x94, 0x3a, 0xe8,
0x4a, 0x05, 0x16, 0x4d, 0xcb, 0xea, 0xd9, 0x9e, 0xc7, 0x5a, 0x72, 0x5d, 0xcf, 0xfe, 0x72, 0x5a,
0xce, 0xa0, 0xfe, 0x3e, 0xdf, 0x39, 0xf4, 0x7b, 0x8e, 0xdb, 0x36, 0x82, 0xc0, 0xb7, 0x96, 0x4e,
0x1e, 0x17, 0x52, 0x7f, 0x3f, 0x2e, 0xa4, 0x94, 0xa3, 0x78, 0xaf, 0xc3, 0x4e, 0xd4, 0x60, 0x11,
0x4f, 0x80, 0x8d, 0xfe, 0xaf, 0x8d, 0x08, 0x64, 0x94, 0x0c, 0x10, 0x56, 0xa9, 0x66, 0xf6, 0xcc,
0x4e, 0x70, 0xa7, 0x4a, 0x0d, 0x0f, 0x15, 0xac, 0x62, 0xf9, 0x37, 0x61, 0xa1, 0xcb, 0x56, 0xb0,
0x7a, 0x4e, 0x15, 0x15, 0xe1, 0x49, 0xfa, 0xfc, 0xd3, 0xdf, 0x0b, 0x29, 0x03, 0x13, 0x94, 0x35,
0x90, 0x99, 0xe2, 0x3d, 0x6a, 0xf5, 0x1f, 0xd8, 0x17, 0x66, 0x48, 0xf9, 0x1c, 0x72, 0xc2, 0x5d,
0xac, 0xfb, 0x51, 0xc2, 0x01, 0xd8, 0x7c, 0x76, 0x5a, 0x56, 0x44, 0x48, 0x31, 0xdd, 0xc8, 0x18,
0x28, 0xb7, 0xa1, 0x70, 0xb9, 0xb0, 0x3e, 0x78, 0xdf, 0xec, 0x04, 0x33, 0x4a, 0x08, 0xcc, 0xbb,
0x66, 0xc7, 0xe6, 0xd7, 0x68, 0xb0, 0x67, 0xe5, 0x0b, 0x28, 0x4e, 0x4e, 0x43, 0xe8, 0x0f, 0x93,
0xdd, 0x55, 0x52, 0xe6, 0xf0, 0xc6, 0x6e, 0xc2, 0xaa, 0x6e, 0x37, 0x8f, 0xf6, 0x2a, 0xb5, 0x9e,
0xdd, 0x72, 0x1e, 0x05, 0x2d, 0x7c, 0x1b, 0x32, 0xf1, 0x65, 0xc4, 0xd8, 0x80, 0x1b, 0x0d, 0xb6,
0x5e, 0xef, 0xb2, 0x0d, 0x3c, 0x47, 0xba, 0x11, 0x09, 0x56, 0x74, 0xc8, 0xe1, 0x4c, 0xea, 0x03,
0xdf, 0xf6, 0xee, 0x53, 0x1c, 0x4d, 0x6c, 0xc1, 0x06, 0xdc, 0xc0, 0x19, 0xad, 0x37, 0x46, 0xfb,
0x4c, 0x23, 0x6d, 0xa4, 0xcd, 0x48, 0x8e, 0xf2, 0x0e, 0xac, 0x89, 0x35, 0x10, 0xe4, 0x55, 0x58,
0x09, 0x44, 0x3c, 0xb6, 0x83, 0x24, 0x81, 0x34, 0x0f, 0x57, 0xee, 0x86, 0x28, 0x7c, 0xe1, 0x3e,
0x65, 0x72, 0x01, 0x4a, 0x42, 0x95, 0x3b, 0x21, 0xcc, 0x05, 0x95, 0x71, 0x57, 0x66, 0x9f, 0xe8,
0x10, 0xf2, 0xd1, 0xb7, 0x30, 0x3c, 0xdd, 0xc1, 0xdd, 0xf1, 0x6c, 0xcc, 0x39, 0x16, 0xcb, 0xbd,
0xa6, 0xcf, 0x65, 0x25, 0x63, 0xce, 0xb1, 0xc8, 0x3a, 0x00, 0x5e, 0x55, 0xdd, 0xb1, 0xd8, 0x97,
0x65, 0xde, 0xb8, 0x8e, 0x2b, 0x07, 0x96, 0x62, 0xe1, 0xc4, 0x89, 0x44, 0x11, 0x6e, 0x1f, 0x5e,
0x0c, 0x14, 0x92, 0x7e, 0x43, 0x56, 0xcc, 0x98, 0x9c, 0x72, 0x0f, 0x5e, 0x8a, 0x56, 0x39, 0x70,
0x5b, 0xf4, 0x7f, 0x7c, 0x99, 0x94, 0x1a, 0x64, 0x2f, 0xcb, 0x21, 0x6d, 0x15, 0xe6, 0x1d, 0xb7,
0x45, 0x71, 0xc8, 0x8b, 0xc2, 0x4f, 0x82, 0x6e, 0x7a, 0xc1, 0x24, 0x1b, 0x2c, 0xba, 0xf2, 0x4f,
0x1a, 0x5e, 0x60, 0x92, 0xe4, 0x6b, 0x09, 0x96, 0x82, 0x37, 0x9e, 0x6c, 0x0b, 0xd3, 0x45, 0xbe,
0x23, 0xef, 0x24, 0x09, 0xe5, 0x8c, 0xca, 0xce, 0xc9, 0x5f, 0x4f, 0x76, 0xa4, 0x2f, 0x7f, 0xfd,
0xf3, 0xdb, 0xb9, 0x02, 0x59, 0xd7, 0x84, 0x0e, 0x19, 0x20, 0x7c, 0x27, 0xc1, 0x22, 0x0a, 0x90,
0xd2, 0xcc, 0x1a, 0x01, 0xcd, 0x76, 0x82, 0x48, 0x84, 0xa9, 0x8e, 0x61, 0xb6, 0xc9, 0xd6, 0x54,
0x18, 0xed, 0x18, 0x6f, 0x60, 0x48, 0x7e, 0x92, 0x80, 0x5c, 0x9e, 0x19, 0xb2, 0x37, 0xb3, 0xee,
0xe5, 0xb1, 0x95, 0xab, 0x57, 0x4b, 0xba, 0x02, 0x77, 0xf8, 0x4e, 0xd5, 0x1d, 0x4b, 0x3b, 0x76,
0xac, 0x21, 0xf9, 0x4a, 0x82, 0x05, 0xee, 0x08, 0x64, 0x6b, 0x72, 0xd9, 0x98, 0xfd, 0xc8, 0xa5,
0xd9, 0x81, 0xc8, 0x54, 0x1a, 0x33, 0xad, 0x93, 0x9c, 0x90, 0x89, 0x1b, 0x10, 0xf9, 0x41, 0x82,
0x95, 0xb8, 0xbd, 0x10, 0x6d, 0x72, 0x19, 0xa1, 0x4d, 0xc9, 0xaf, 0x27, 0x4f, 0x40, 0xbe, 0xdd,
0x31, 0xdf, 0x26, 0x79, 0x45, 0xc8, 0xd7, 0x61, 0x99, 0xf5, 0x70, 0xfe, 0x7e, 0x96, 0x60, 0x55,
0xe0, 0x2b, 0xa4, 0x9a, 0xb0, 0x78, 0xcc, 0xbd, 0xe4, 0xdb, 0x57, 0xcc, 0x42, 0xee, 0x37, 0xc6,
0xdc, 0x65, 0xf2, 0x5a, 0x12, 0x6e, 0xed, 0x78, 0xe4, 0x8c, 0x43, 0x72, 0x22, 0x41, 0x3a, 0x6a,
0x44, 0x13, 0xde, 0x21, 0x81, 0x85, 0x4d, 0x78, 0x87, 0x44, 0xae, 0xa6, 0x6c, 0x4c, 0xbd, 0x72,
0xee, 0x6d, 0xe4, 0x89, 0x04, 0x19, 0x91, 0x25, 0x11, 0xf1, 0x3d, 0x4e, 0x71, 0x40, 0x79, 0xf7,
0x0a, 0x19, 0x88, 0xb8, 0x37, 0xb5, 0x7b, 0x1c, 0x31, 0x7c, 0xbf, 0xb9, 0x0b, 0x0d, 0xc9, 0x8f,
0x63, 0xe4, 0x98, 0x71, 0x4d, 0x47, 0x16, 0x39, 0xe5, 0x74, 0x64, 0xa1, 0x2b, 0x2a, 0x55, 0x86,
0xac, 0x92, 0x5b, 0x89, 0x90, 0xb9, 0xff, 0x0e, 0xc9, 0xf7, 0x12, 0x2c, 0x47, 0x8c, 0x81, 0xdc,
0x9a, 0xf9, 0x75, 0x89, 0xd8, 0x91, 0x5c, 0x4e, 0x18, 0x9d, 0x7c, 0x30, 0x43, 0xf7, 0x75, 0x5b,
0x74, 0xfc, 0x01, 0xd5, 0xef, 0x3c, 0x3d, 0xcb, 0x4b, 0xcf, 0xcf, 0xf2, 0xd2, 0x1f, 0x67, 0x79,
0xe9, 0x9b, 0xf3, 0x7c, 0xea, 0xf9, 0x79, 0x3e, 0xf5, 0xdb, 0x79, 0x3e, 0xf5, 0xf1, 0x76, 0xdb,
0xf1, 0x8f, 0xfa, 0x0d, 0xb5, 0x49, 0x3b, 0x81, 0x20, 0xff, 0x53, 0xf6, 0xac, 0x4f, 0xb5, 0x47,
0x5c, 0xdd, 0x1f, 0x74, 0x6d, 0xaf, 0xb1, 0xc0, 0xfe, 0x77, 0xdb, 0xfb, 0x37, 0x00, 0x00, 0xff,
0xff, 0x1f, 0xa2, 0x5f, 0xef, 0x16, 0x0e, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// QueryClient is the client API for Query service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type QueryClient interface {
// Accounts returns all the existing accounts.
//
// When called from another module, this query might consume a high amount of
// gas if the pagination field is incorrectly set.
//
// Since: cosmos-sdk 0.43
Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error)
// Account returns account details based on address.
Account(ctx context.Context, in *QueryAccountRequest, opts ...grpc.CallOption) (*QueryAccountResponse, error)
// AccountAddressByID returns account address based on account number.
//
// Since: cosmos-sdk 0.46.2
AccountAddressByID(ctx context.Context, in *QueryAccountAddressByIDRequest, opts ...grpc.CallOption) (*QueryAccountAddressByIDResponse, error)
// Params queries all parameters.
Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error)
// ModuleAccounts returns all the existing module accounts.
//
// Since: cosmos-sdk 0.46
ModuleAccounts(ctx context.Context, in *QueryModuleAccountsRequest, opts ...grpc.CallOption) (*QueryModuleAccountsResponse, error)
// ModuleAccountByName returns the module account info by module name
ModuleAccountByName(ctx context.Context, in *QueryModuleAccountByNameRequest, opts ...grpc.CallOption) (*QueryModuleAccountByNameResponse, error)
// Bech32Prefix queries bech32Prefix
//
// Since: cosmos-sdk 0.46
Bech32Prefix(ctx context.Context, in *Bech32PrefixRequest, opts ...grpc.CallOption) (*Bech32PrefixResponse, error)
// AddressBytesToString converts Account Address bytes to string
//
// Since: cosmos-sdk 0.46
AddressBytesToString(ctx context.Context, in *AddressBytesToStringRequest, opts ...grpc.CallOption) (*AddressBytesToStringResponse, error)
// AddressStringToBytes converts Address string to bytes
//
// Since: cosmos-sdk 0.46
AddressStringToBytes(ctx context.Context, in *AddressStringToBytesRequest, opts ...grpc.CallOption) (*AddressStringToBytesResponse, error)
// AccountInfo queries account info which is common to all account types.
//
// Since: cosmos-sdk 0.47
AccountInfo(ctx context.Context, in *QueryAccountInfoRequest, opts ...grpc.CallOption) (*QueryAccountInfoResponse, error)
}
type queryClient struct {
cc grpc1.ClientConn
}
func NewQueryClient(cc grpc1.ClientConn) QueryClient {
return &queryClient{cc}
}
func (c *queryClient) Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) {
out := new(QueryAccountsResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/Accounts", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) Account(ctx context.Context, in *QueryAccountRequest, opts ...grpc.CallOption) (*QueryAccountResponse, error) {
out := new(QueryAccountResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/Account", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) AccountAddressByID(ctx context.Context, in *QueryAccountAddressByIDRequest, opts ...grpc.CallOption) (*QueryAccountAddressByIDResponse, error) {
out := new(QueryAccountAddressByIDResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/AccountAddressByID", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) {
out := new(QueryParamsResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/Params", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) ModuleAccounts(ctx context.Context, in *QueryModuleAccountsRequest, opts ...grpc.CallOption) (*QueryModuleAccountsResponse, error) {
out := new(QueryModuleAccountsResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/ModuleAccounts", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) ModuleAccountByName(ctx context.Context, in *QueryModuleAccountByNameRequest, opts ...grpc.CallOption) (*QueryModuleAccountByNameResponse, error) {
out := new(QueryModuleAccountByNameResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/ModuleAccountByName", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) Bech32Prefix(ctx context.Context, in *Bech32PrefixRequest, opts ...grpc.CallOption) (*Bech32PrefixResponse, error) {
out := new(Bech32PrefixResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/Bech32Prefix", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) AddressBytesToString(ctx context.Context, in *AddressBytesToStringRequest, opts ...grpc.CallOption) (*AddressBytesToStringResponse, error) {
out := new(AddressBytesToStringResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/AddressBytesToString", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) AddressStringToBytes(ctx context.Context, in *AddressStringToBytesRequest, opts ...grpc.CallOption) (*AddressStringToBytesResponse, error) {
out := new(AddressStringToBytesResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/AddressStringToBytes", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) AccountInfo(ctx context.Context, in *QueryAccountInfoRequest, opts ...grpc.CallOption) (*QueryAccountInfoResponse, error) {
out := new(QueryAccountInfoResponse)
err := c.cc.Invoke(ctx, "/cosmos.auth.v1beta1.Query/AccountInfo", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// QueryServer is the server API for Query service.
type QueryServer interface {
// Accounts returns all the existing accounts.
//
// When called from another module, this query might consume a high amount of
// gas if the pagination field is incorrectly set.
//
// Since: cosmos-sdk 0.43
Accounts(context.Context, *QueryAccountsRequest) (*QueryAccountsResponse, error)
// Account returns account details based on address.
Account(context.Context, *QueryAccountRequest) (*QueryAccountResponse, error)
// AccountAddressByID returns account address based on account number.
//
// Since: cosmos-sdk 0.46.2
AccountAddressByID(context.Context, *QueryAccountAddressByIDRequest) (*QueryAccountAddressByIDResponse, error)
// Params queries all parameters.
Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error)
// ModuleAccounts returns all the existing module accounts.
//
// Since: cosmos-sdk 0.46
ModuleAccounts(context.Context, *QueryModuleAccountsRequest) (*QueryModuleAccountsResponse, error)
// ModuleAccountByName returns the module account info by module name
ModuleAccountByName(context.Context, *QueryModuleAccountByNameRequest) (*QueryModuleAccountByNameResponse, error)
// Bech32Prefix queries bech32Prefix
//
// Since: cosmos-sdk 0.46
Bech32Prefix(context.Context, *Bech32PrefixRequest) (*Bech32PrefixResponse, error)
// AddressBytesToString converts Account Address bytes to string
//
// Since: cosmos-sdk 0.46
AddressBytesToString(context.Context, *AddressBytesToStringRequest) (*AddressBytesToStringResponse, error)
// AddressStringToBytes converts Address string to bytes
//
// Since: cosmos-sdk 0.46
AddressStringToBytes(context.Context, *AddressStringToBytesRequest) (*AddressStringToBytesResponse, error)
// AccountInfo queries account info which is common to all account types.
//
// Since: cosmos-sdk 0.47
AccountInfo(context.Context, *QueryAccountInfoRequest) (*QueryAccountInfoResponse, error)
}
// UnimplementedQueryServer can be embedded to have forward compatible implementations.
type UnimplementedQueryServer struct {
}
func (*UnimplementedQueryServer) Accounts(ctx context.Context, req *QueryAccountsRequest) (*QueryAccountsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Accounts not implemented")
}
func (*UnimplementedQueryServer) Account(ctx context.Context, req *QueryAccountRequest) (*QueryAccountResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Account not implemented")
}
func (*UnimplementedQueryServer) AccountAddressByID(ctx context.Context, req *QueryAccountAddressByIDRequest) (*QueryAccountAddressByIDResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method AccountAddressByID not implemented")
}
func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Params not implemented")
}
func (*UnimplementedQueryServer) ModuleAccounts(ctx context.Context, req *QueryModuleAccountsRequest) (*QueryModuleAccountsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ModuleAccounts not implemented")
}
func (*UnimplementedQueryServer) ModuleAccountByName(ctx context.Context, req *QueryModuleAccountByNameRequest) (*QueryModuleAccountByNameResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ModuleAccountByName not implemented")
}
func (*UnimplementedQueryServer) Bech32Prefix(ctx context.Context, req *Bech32PrefixRequest) (*Bech32PrefixResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Bech32Prefix not implemented")
}
func (*UnimplementedQueryServer) AddressBytesToString(ctx context.Context, req *AddressBytesToStringRequest) (*AddressBytesToStringResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method AddressBytesToString not implemented")
}
func (*UnimplementedQueryServer) AddressStringToBytes(ctx context.Context, req *AddressStringToBytesRequest) (*AddressStringToBytesResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method AddressStringToBytes not implemented")
}
func (*UnimplementedQueryServer) AccountInfo(ctx context.Context, req *QueryAccountInfoRequest) (*QueryAccountInfoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method AccountInfo not implemented")
}
func RegisterQueryServer(s grpc1.Server, srv QueryServer) {
s.RegisterService(&_Query_serviceDesc, srv)
}
func _Query_Accounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryAccountsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).Accounts(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/Accounts",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).Accounts(ctx, req.(*QueryAccountsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_Account_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryAccountRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).Account(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/Account",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).Account(ctx, req.(*QueryAccountRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_AccountAddressByID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryAccountAddressByIDRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).AccountAddressByID(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/AccountAddressByID",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).AccountAddressByID(ctx, req.(*QueryAccountAddressByIDRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryParamsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).Params(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/Params",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_ModuleAccounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryModuleAccountsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).ModuleAccounts(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/ModuleAccounts",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).ModuleAccounts(ctx, req.(*QueryModuleAccountsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_ModuleAccountByName_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryModuleAccountByNameRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).ModuleAccountByName(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/ModuleAccountByName",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).ModuleAccountByName(ctx, req.(*QueryModuleAccountByNameRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_Bech32Prefix_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Bech32PrefixRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).Bech32Prefix(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/Bech32Prefix",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).Bech32Prefix(ctx, req.(*Bech32PrefixRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_AddressBytesToString_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddressBytesToStringRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).AddressBytesToString(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/AddressBytesToString",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).AddressBytesToString(ctx, req.(*AddressBytesToStringRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_AddressStringToBytes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddressStringToBytesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).AddressStringToBytes(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/AddressStringToBytes",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).AddressStringToBytes(ctx, req.(*AddressStringToBytesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_AccountInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryAccountInfoRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).AccountInfo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.auth.v1beta1.Query/AccountInfo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).AccountInfo(ctx, req.(*QueryAccountInfoRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Query_serviceDesc = grpc.ServiceDesc{
ServiceName: "cosmos.auth.v1beta1.Query",
HandlerType: (*QueryServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Accounts",
Handler: _Query_Accounts_Handler,
},
{
MethodName: "Account",
Handler: _Query_Account_Handler,
},
{
MethodName: "AccountAddressByID",
Handler: _Query_AccountAddressByID_Handler,
},
{
MethodName: "Params",
Handler: _Query_Params_Handler,
},
{
MethodName: "ModuleAccounts",
Handler: _Query_ModuleAccounts_Handler,
},
{
MethodName: "ModuleAccountByName",
Handler: _Query_ModuleAccountByName_Handler,
},
{
MethodName: "Bech32Prefix",
Handler: _Query_Bech32Prefix_Handler,
},
{
MethodName: "AddressBytesToString",
Handler: _Query_AddressBytesToString_Handler,
},
{
MethodName: "AddressStringToBytes",
Handler: _Query_AddressStringToBytes_Handler,
},
{
MethodName: "AccountInfo",
Handler: _Query_AccountInfo_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "cosmos/auth/v1beta1/query.proto",
}
func (m *QueryAccountsRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAccountsRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAccountsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryAccountsResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAccountsResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAccountsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Pagination != nil {
{
size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
if len(m.Accounts) > 0 {
for iNdEx := len(m.Accounts) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Accounts[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *QueryAccountRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAccountRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAccountRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryAccountResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAccountResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAccountResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Account != nil {
{
size, err := m.Account.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.Params.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *QueryModuleAccountsRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryModuleAccountsRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryModuleAccountsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *QueryModuleAccountsResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryModuleAccountsResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryModuleAccountsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Accounts) > 0 {
for iNdEx := len(m.Accounts) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Accounts[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *QueryModuleAccountByNameRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryModuleAccountByNameRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryModuleAccountByNameRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Name) > 0 {
i -= len(m.Name)
copy(dAtA[i:], m.Name)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Name)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryModuleAccountByNameResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryModuleAccountByNameResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryModuleAccountByNameResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Account != nil {
{
size, err := m.Account.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *Bech32PrefixRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Bech32PrefixRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Bech32PrefixRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *Bech32PrefixResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Bech32PrefixResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Bech32PrefixResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Bech32Prefix) > 0 {
i -= len(m.Bech32Prefix)
copy(dAtA[i:], m.Bech32Prefix)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Bech32Prefix)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *AddressBytesToStringRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AddressBytesToStringRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *AddressBytesToStringRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AddressBytes) > 0 {
i -= len(m.AddressBytes)
copy(dAtA[i:], m.AddressBytes)
i = encodeVarintQuery(dAtA, i, uint64(len(m.AddressBytes)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *AddressBytesToStringResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AddressBytesToStringResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *AddressBytesToStringResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AddressString) > 0 {
i -= len(m.AddressString)
copy(dAtA[i:], m.AddressString)
i = encodeVarintQuery(dAtA, i, uint64(len(m.AddressString)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *AddressStringToBytesRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AddressStringToBytesRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *AddressStringToBytesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AddressString) > 0 {
i -= len(m.AddressString)
copy(dAtA[i:], m.AddressString)
i = encodeVarintQuery(dAtA, i, uint64(len(m.AddressString)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *AddressStringToBytesResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AddressStringToBytesResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *AddressStringToBytesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AddressBytes) > 0 {
i -= len(m.AddressBytes)
copy(dAtA[i:], m.AddressBytes)
i = encodeVarintQuery(dAtA, i, uint64(len(m.AddressBytes)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryAccountAddressByIDRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAccountAddressByIDRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAccountAddressByIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.AccountId != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.AccountId))
i--
dAtA[i] = 0x10
}
if m.Id != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.Id))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *QueryAccountAddressByIDResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAccountAddressByIDResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAccountAddressByIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.AccountAddress) > 0 {
i -= len(m.AccountAddress)
copy(dAtA[i:], m.AccountAddress)
i = encodeVarintQuery(dAtA, i, uint64(len(m.AccountAddress)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryAccountInfoRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAccountInfoRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAccountInfoRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintQuery(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *QueryAccountInfoResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryAccountInfoResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryAccountInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Info != nil {
{
size, err := m.Info.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintQuery(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintQuery(dAtA []byte, offset int, v uint64) int {
offset -= sovQuery(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *QueryAccountsRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryAccountsResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Accounts) > 0 {
for _, e := range m.Accounts {
l = e.Size()
n += 1 + l + sovQuery(uint64(l))
}
}
if m.Pagination != nil {
l = m.Pagination.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryAccountRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryAccountResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Account != nil {
l = m.Account.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryParamsRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *QueryParamsResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.Params.Size()
n += 1 + l + sovQuery(uint64(l))
return n
}
func (m *QueryModuleAccountsRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *QueryModuleAccountsResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Accounts) > 0 {
for _, e := range m.Accounts {
l = e.Size()
n += 1 + l + sovQuery(uint64(l))
}
}
return n
}
func (m *QueryModuleAccountByNameRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Name)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryModuleAccountByNameResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Account != nil {
l = m.Account.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *Bech32PrefixRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *Bech32PrefixResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Bech32Prefix)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *AddressBytesToStringRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AddressBytes)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *AddressBytesToStringResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AddressString)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *AddressStringToBytesRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AddressString)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *AddressStringToBytesResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AddressBytes)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryAccountAddressByIDRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Id != 0 {
n += 1 + sovQuery(uint64(m.Id))
}
if m.AccountId != 0 {
n += 1 + sovQuery(uint64(m.AccountId))
}
return n
}
func (m *QueryAccountAddressByIDResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.AccountAddress)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryAccountInfoRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func (m *QueryAccountInfoResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Info != nil {
l = m.Info.Size()
n += 1 + l + sovQuery(uint64(l))
}
return n
}
func sovQuery(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozQuery(x uint64) (n int) {
return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *QueryAccountsRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAccountsRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAccountsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageRequest{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAccountsResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAccountsResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Accounts", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Accounts = append(m.Accounts, &types.Any{})
if err := m.Accounts[len(m.Accounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Pagination == nil {
m.Pagination = &query.PageResponse{}
}
if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAccountRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAccountRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAccountRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAccountResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAccountResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAccountResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Account", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Account == nil {
m.Account = &types.Any{}
}
if err := m.Account.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryModuleAccountsRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryModuleAccountsRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryModuleAccountsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryModuleAccountsResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryModuleAccountsResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryModuleAccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Accounts", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Accounts = append(m.Accounts, &types.Any{})
if err := m.Accounts[len(m.Accounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryModuleAccountByNameRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryModuleAccountByNameRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryModuleAccountByNameRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Name = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryModuleAccountByNameResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryModuleAccountByNameResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryModuleAccountByNameResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Account", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Account == nil {
m.Account = &types.Any{}
}
if err := m.Account.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Bech32PrefixRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Bech32PrefixRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Bech32PrefixRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Bech32PrefixResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Bech32PrefixResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Bech32PrefixResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Bech32Prefix", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Bech32Prefix = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *AddressBytesToStringRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AddressBytesToStringRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AddressBytesToStringRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AddressBytes", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AddressBytes = append(m.AddressBytes[:0], dAtA[iNdEx:postIndex]...)
if m.AddressBytes == nil {
m.AddressBytes = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *AddressBytesToStringResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AddressBytesToStringResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AddressBytesToStringResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AddressString", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AddressString = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *AddressStringToBytesRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AddressStringToBytesRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AddressStringToBytesRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AddressString", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AddressString = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *AddressStringToBytesResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AddressStringToBytesResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AddressStringToBytesResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AddressBytes", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AddressBytes = append(m.AddressBytes[:0], dAtA[iNdEx:postIndex]...)
if m.AddressBytes == nil {
m.AddressBytes = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAccountAddressByIDRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAccountAddressByIDRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAccountAddressByIDRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
}
m.Id = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Id |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field AccountId", wireType)
}
m.AccountId = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.AccountId |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAccountAddressByIDResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAccountAddressByIDResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAccountAddressByIDResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AccountAddress", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.AccountAddress = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAccountInfoRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAccountInfoRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAccountInfoRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryAccountInfoResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryAccountInfoResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryAccountInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Info == nil {
m.Info = &BaseAccount{}
}
if err := m.Info.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipQuery(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthQuery
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupQuery
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthQuery
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group")
)
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2015 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json.
This package produces a different output than the standard "encoding/json" package,
which does not operate correctly on protocol buffers.
*/
package jsonpb
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"reflect"
"sort"
"strconv"
"strings"
"time"
"google.golang.org/protobuf/encoding/protojson"
protov2 "google.golang.org/protobuf/proto"
"github.com/cosmos/gogoproto/proto"
"github.com/cosmos/gogoproto/types"
)
const secondInNanos = int64(time.Second / time.Nanosecond)
const maxSecondsInDuration = 315576000000
// Marshaler is a configurable object for converting between
// protocol buffer objects and a JSON representation for them.
type Marshaler struct {
// Whether to render enum values as integers, as opposed to string values.
EnumsAsInts bool
// Whether to render fields with zero values.
EmitDefaults bool
// A string to indent each level by. The presence of this field will
// also cause a space to appear between the field separator and
// value, and for newlines to be appear between fields and array
// elements.
Indent string
// Whether to use the original (.proto) name for fields.
OrigName bool
// A custom URL resolver to use when marshaling Any messages to JSON.
// If unset, the default resolution strategy is to extract the
// fully-qualified type name from the type URL and pass that to
// proto.MessageType(string).
AnyResolver AnyResolver
}
// AnyResolver takes a type URL, present in an Any message, and resolves it into
// an instance of the associated message.
type AnyResolver = interface {
Resolve(typeUrl string) (proto.Message, error)
}
func defaultResolveAny(typeUrl string) (proto.Message, error) {
// Only the part of typeUrl after the last slash is relevant.
mname := typeUrl
if slash := strings.LastIndex(mname, "/"); slash >= 0 {
mname = mname[slash+1:]
}
mt := proto.MessageType(mname)
if mt == nil {
return nil, fmt.Errorf("unknown message type %q", mname)
}
return reflect.New(mt.Elem()).Interface().(proto.Message), nil
}
// JSONPBMarshaler is implemented by protobuf messages that customize the
// way they are marshaled to JSON. Messages that implement this should
// also implement JSONPBUnmarshaler so that the custom format can be
// parsed.
//
// The JSON marshaling must follow the proto to JSON specification:
//
// https://developers.google.com/protocol-buffers/docs/proto3#json
type JSONPBMarshaler interface {
MarshalJSONPB(*Marshaler) ([]byte, error)
}
// JSONPBUnmarshaler is implemented by protobuf messages that customize
// the way they are unmarshaled from JSON. Messages that implement this
// should also implement JSONPBMarshaler so that the custom format can be
// produced.
//
// The JSON unmarshaling must follow the JSON to proto specification:
//
// https://developers.google.com/protocol-buffers/docs/proto3#json
type JSONPBUnmarshaler interface {
UnmarshalJSONPB(*Unmarshaler, []byte) error
}
// Marshal marshals a protocol buffer into JSON.
func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
if msgV2, ok := pb.(protov2.Message); ok {
bz, err := protojson.MarshalOptions{
Indent: m.Indent,
UseProtoNames: m.OrigName,
UseEnumNumbers: m.EnumsAsInts,
EmitUnpopulated: m.EmitDefaults,
}.Marshal(msgV2)
if err != nil {
return err
}
_, err = out.Write(bz)
return err
}
v := reflect.ValueOf(pb)
if pb == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
return errors.New("Marshal called with nil")
}
// Check for unset required fields first.
if err := checkRequiredFields(pb); err != nil {
return err
}
writer := &errWriter{writer: out}
return m.marshalObject(writer, pb, "", "")
}
// MarshalToString converts a protocol buffer object to JSON string.
func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) {
var buf bytes.Buffer
if err := m.Marshal(&buf, pb); err != nil {
return "", err
}
return buf.String(), nil
}
type int32Slice []int32
var nonFinite = map[string]float64{
`"NaN"`: math.NaN(),
`"Infinity"`: math.Inf(1),
`"-Infinity"`: math.Inf(-1),
}
// For sorting extensions ids to ensure stable output.
func (s int32Slice) Len() int { return len(s) }
func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type isWkt interface {
XXX_WellKnownType() string
}
var (
wktType = reflect.TypeOf((*isWkt)(nil)).Elem()
messageType = reflect.TypeOf((*proto.Message)(nil)).Elem()
)
// marshalObject writes a struct to the Writer.
func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error {
if jsm, ok := v.(JSONPBMarshaler); ok {
b, err := jsm.MarshalJSONPB(m)
if err != nil {
return err
}
if typeURL != "" {
// we are marshaling this object to an Any type
var js map[string]*json.RawMessage
if err = json.Unmarshal(b, &js); err != nil {
return fmt.Errorf("type %T produced invalid JSON: %v", v, err)
}
turl, err := json.Marshal(typeURL)
if err != nil {
return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
}
js["@type"] = (*json.RawMessage)(&turl)
if m.Indent != "" {
b, err = json.MarshalIndent(js, indent, m.Indent)
} else {
b, err = json.Marshal(js)
}
if err != nil {
return err
}
}
out.write(string(b))
return out.err
}
s := reflect.ValueOf(v).Elem()
// Handle well-known types.
if wkt, ok := v.(isWkt); ok {
switch wkt.XXX_WellKnownType() {
case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
"Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
// "Wrappers use the same representation in JSON
// as the wrapped primitive type, ..."
sprop := proto.GetProperties(s.Type())
return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent)
case "Any":
// Any is a bit more involved.
return m.marshalAny(out, v, indent)
case "Duration":
s, ns := s.Field(0).Int(), s.Field(1).Int()
if s < -maxSecondsInDuration || s > maxSecondsInDuration {
return fmt.Errorf("seconds out of range %v", s)
}
if ns <= -secondInNanos || ns >= secondInNanos {
return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos)
}
if (s > 0 && ns < 0) || (s < 0 && ns > 0) {
return errors.New("signs of seconds and nanos do not match")
}
// Generated output always contains 0, 3, 6, or 9 fractional digits,
// depending on required precision, followed by the suffix "s".
f := "%d.%09d"
if ns < 0 {
ns = -ns
if s == 0 {
f = "-%d.%09d"
}
}
x := fmt.Sprintf(f, s, ns)
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, ".000")
out.write(`"`)
out.write(x)
out.write(`s"`)
return out.err
case "Struct", "ListValue":
// Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice.
// TODO: pass the correct Properties if needed.
return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent)
case "Timestamp":
// "RFC 3339, where generated output will always be Z-normalized
// and uses 0, 3, 6 or 9 fractional digits."
s, ns := s.Field(0).Int(), s.Field(1).Int()
if ns < 0 || ns >= secondInNanos {
return fmt.Errorf("ns out of range [0, %v)", secondInNanos)
}
t := time.Unix(s, ns).UTC()
// time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits).
x := t.Format("2006-01-02T15:04:05.000000000")
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, ".000")
out.write(`"`)
out.write(x)
out.write(`Z"`)
return out.err
case "Value":
// Value has a single oneof.
kind := s.Field(0)
if kind.IsNil() {
// "absence of any variant indicates an error"
return errors.New("nil Value")
}
// oneof -> *T -> T -> T.F
x := kind.Elem().Elem().Field(0)
// TODO: pass the correct Properties if needed.
return m.marshalValue(out, &proto.Properties{}, x, indent)
}
}
out.write("{")
if m.Indent != "" {
out.write("\n")
}
firstField := true
if typeURL != "" {
if err := m.marshalTypeURL(out, indent, typeURL); err != nil {
return err
}
firstField = false
}
for i := 0; i < s.NumField(); i++ {
value := s.Field(i)
valueField := s.Type().Field(i)
if strings.HasPrefix(valueField.Name, "XXX_") {
continue
}
//this is not a protobuf field
if valueField.Tag.Get("protobuf") == "" && valueField.Tag.Get("protobuf_oneof") == "" {
continue
}
// IsNil will panic on most value kinds.
switch value.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface:
if value.IsNil() {
continue
}
}
if !m.EmitDefaults {
switch value.Kind() {
case reflect.Bool:
if !value.Bool() {
continue
}
case reflect.Int32, reflect.Int64:
if value.Int() == 0 {
continue
}
case reflect.Uint32, reflect.Uint64:
if value.Uint() == 0 {
continue
}
case reflect.Float32, reflect.Float64:
if value.Float() == 0 {
continue
}
case reflect.String:
if value.Len() == 0 {
continue
}
case reflect.Map, reflect.Ptr, reflect.Slice:
if value.IsNil() {
continue
}
}
}
// Oneof fields need special handling.
if valueField.Tag.Get("protobuf_oneof") != "" {
// value is an interface containing &T{real_value}.
sv := value.Elem().Elem() // interface -> *T -> T
value = sv.Field(0)
valueField = sv.Type().Field(0)
}
prop := jsonProperties(valueField, m.OrigName)
if !firstField {
m.writeSep(out)
}
// If the map value is a cast type, it may not implement proto.Message, therefore
// allow the struct tag to declare the underlying message type. Change the property
// of the child types, use CustomType as a passer. CastType currently property is
// not used in json encoding.
if value.Kind() == reflect.Map {
if tag := valueField.Tag.Get("protobuf"); tag != "" {
for _, v := range strings.Split(tag, ",") {
if !strings.HasPrefix(v, "castvaluetype=") {
continue
}
v = strings.TrimPrefix(v, "castvaluetype=")
prop.MapValProp.CustomType = v
break
}
}
}
if err := m.marshalField(out, prop, value, indent); err != nil {
return err
}
firstField = false
}
// Handle proto2 extensions.
if ep, ok := v.(proto.Message); ok {
extensions := proto.RegisteredExtensions(v)
// Sort extensions for stable output.
ids := make([]int32, 0, len(extensions))
for id, desc := range extensions {
if !proto.HasExtension(ep, desc) {
continue
}
ids = append(ids, id)
}
sort.Sort(int32Slice(ids))
for _, id := range ids {
desc := extensions[id]
if desc == nil {
// unknown extension
continue
}
ext, extErr := proto.GetExtension(ep, desc)
if extErr != nil {
return extErr
}
value := reflect.ValueOf(ext)
var prop proto.Properties
prop.Parse(desc.Tag)
prop.JSONName = fmt.Sprintf("[%s]", desc.Name)
if !firstField {
m.writeSep(out)
}
if err := m.marshalField(out, &prop, value, indent); err != nil {
return err
}
firstField = false
}
}
if m.Indent != "" {
out.write("\n")
out.write(indent)
}
out.write("}")
return out.err
}
func (m *Marshaler) writeSep(out *errWriter) {
if m.Indent != "" {
out.write(",\n")
} else {
out.write(",")
}
}
func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error {
// "If the Any contains a value that has a special JSON mapping,
// it will be converted as follows: {"@type": xxx, "value": yyy}.
// Otherwise, the value will be converted into a JSON object,
// and the "@type" field will be inserted to indicate the actual data type."
v := reflect.ValueOf(any).Elem()
turl := v.Field(0).String()
val := v.Field(1).Bytes()
var msg proto.Message
var err error
if m.AnyResolver != nil {
msg, err = m.AnyResolver.Resolve(turl)
} else {
msg, err = defaultResolveAny(turl)
}
if err != nil {
return err
}
if err := proto.Unmarshal(val, msg); err != nil {
return err
}
if _, ok := msg.(isWkt); ok {
out.write("{")
if m.Indent != "" {
out.write("\n")
}
if err := m.marshalTypeURL(out, indent, turl); err != nil {
return err
}
m.writeSep(out)
if m.Indent != "" {
out.write(indent)
out.write(m.Indent)
out.write(`"value": `)
} else {
out.write(`"value":`)
}
if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil {
return err
}
if m.Indent != "" {
out.write("\n")
out.write(indent)
}
out.write("}")
return out.err
}
return m.marshalObject(out, msg, indent, turl)
}
func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error {
if m.Indent != "" {
out.write(indent)
out.write(m.Indent)
}
out.write(`"@type":`)
if m.Indent != "" {
out.write(" ")
}
b, err := json.Marshal(typeURL)
if err != nil {
return err
}
out.write(string(b))
return out.err
}
// marshalField writes field description and value to the Writer.
func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
if m.Indent != "" {
out.write(indent)
out.write(m.Indent)
}
out.write(`"`)
out.write(prop.JSONName)
out.write(`":`)
if m.Indent != "" {
out.write(" ")
}
if err := m.marshalValue(out, prop, v, indent); err != nil {
return err
}
return nil
}
// marshalValue writes the value to the Writer.
func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
v = reflect.Indirect(v)
// Handle nil pointer
if v.Kind() == reflect.Invalid {
out.write("null")
return out.err
}
// Handle repeated elements.
if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
out.write("[")
comma := ""
for i := 0; i < v.Len(); i++ {
sliceVal := v.Index(i)
out.write(comma)
if m.Indent != "" {
out.write("\n")
out.write(indent)
out.write(m.Indent)
out.write(m.Indent)
}
if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil {
return err
}
comma = ","
}
if m.Indent != "" {
out.write("\n")
out.write(indent)
out.write(m.Indent)
}
out.write("]")
return out.err
}
// Handle well-known types.
// Most are handled up in marshalObject (because 99% are messages).
if v.Type().Implements(wktType) {
wkt := v.Interface().(isWkt)
switch wkt.XXX_WellKnownType() {
case "NullValue":
out.write("null")
return out.err
}
}
if t, ok := v.Interface().(time.Time); ok {
ts, err := types.TimestampProto(t)
if err != nil {
return err
}
return m.marshalValue(out, prop, reflect.ValueOf(ts), indent)
}
if d, ok := v.Interface().(time.Duration); ok {
dur := types.DurationProto(d)
return m.marshalValue(out, prop, reflect.ValueOf(dur), indent)
}
// Handle enumerations.
if !m.EnumsAsInts && prop.Enum != "" {
// Unknown enum values will are stringified by the proto library as their
// value. Such values should _not_ be quoted or they will be interpreted
// as an enum string instead of their value.
enumStr := v.Interface().(fmt.Stringer).String()
var valStr string
if v.Kind() == reflect.Ptr {
valStr = strconv.Itoa(int(v.Elem().Int()))
} else {
valStr = strconv.Itoa(int(v.Int()))
}
if m, ok := v.Interface().(interface {
MarshalJSON() ([]byte, error)
}); ok {
data, err := m.MarshalJSON()
if err != nil {
return err
}
enumStr = string(data)
enumStr, err = strconv.Unquote(enumStr)
if err != nil {
return err
}
}
isKnownEnum := enumStr != valStr
if isKnownEnum {
out.write(`"`)
}
out.write(enumStr)
if isKnownEnum {
out.write(`"`)
}
return out.err
}
// Handle nested messages.
if v.Kind() == reflect.Struct {
i := v
if v.CanAddr() {
i = v.Addr()
} else {
i = reflect.New(v.Type())
i.Elem().Set(v)
}
iface := i.Interface()
if iface == nil {
out.write(`null`)
return out.err
}
if m, ok := v.Interface().(interface {
MarshalJSON() ([]byte, error)
}); ok {
data, err := m.MarshalJSON()
if err != nil {
return err
}
out.write(string(data))
return nil
}
pm, ok := iface.(proto.Message)
if !ok {
if prop.CustomType == "" {
return fmt.Errorf("%v does not implement proto.Message", v.Type())
}
t := proto.MessageType(prop.CustomType)
if t == nil || !i.Type().ConvertibleTo(t) {
return fmt.Errorf("%v declared custom type %s but it is not convertible to %v", v.Type(), prop.CustomType, t)
}
pm = i.Convert(t).Interface().(proto.Message)
}
return m.marshalObject(out, pm, indent+m.Indent, "")
}
// Handle maps.
// Since Go randomizes map iteration, we sort keys for stable output.
if v.Kind() == reflect.Map {
out.write(`{`)
keys := v.MapKeys()
sort.Sort(mapKeys(keys))
for i, k := range keys {
if i > 0 {
out.write(`,`)
}
if m.Indent != "" {
out.write("\n")
out.write(indent)
out.write(m.Indent)
out.write(m.Indent)
}
// TODO handle map key prop properly
b, err := json.Marshal(k.Interface())
if err != nil {
return err
}
s := string(b)
// If the JSON is not a string value, encode it again to make it one.
if !strings.HasPrefix(s, `"`) {
b, err := json.Marshal(s)
if err != nil {
return err
}
s = string(b)
}
out.write(s)
out.write(`:`)
if m.Indent != "" {
out.write(` `)
}
vprop := prop
if prop != nil && prop.MapValProp != nil {
vprop = prop.MapValProp
}
if err := m.marshalValue(out, vprop, v.MapIndex(k), indent+m.Indent); err != nil {
return err
}
}
if m.Indent != "" {
out.write("\n")
out.write(indent)
out.write(m.Indent)
}
out.write(`}`)
return out.err
}
// Handle non-finite floats, e.g. NaN, Infinity and -Infinity.
if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
f := v.Float()
var sval string
switch {
case math.IsInf(f, 1):
sval = `"Infinity"`
case math.IsInf(f, -1):
sval = `"-Infinity"`
case math.IsNaN(f):
sval = `"NaN"`
}
if sval != "" {
out.write(sval)
return out.err
}
}
// Default handling defers to the encoding/json library.
b, err := json.Marshal(v.Interface())
if err != nil {
return err
}
needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
if needToQuote {
out.write(`"`)
}
out.write(string(b))
if needToQuote {
out.write(`"`)
}
return out.err
}
// Unmarshaler is a configurable object for converting from a JSON
// representation to a protocol buffer object.
type Unmarshaler struct {
// Whether to allow messages to contain unknown fields, as opposed to
// failing to unmarshal.
AllowUnknownFields bool
// A custom URL resolver to use when unmarshaling Any messages from JSON.
// If unset, the default resolution strategy is to extract the
// fully-qualified type name from the type URL and pass that to
// proto.MessageType(string).
AnyResolver AnyResolver
}
// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
// This function is lenient and will decode any options permutations of the
// related Marshaler.
func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
inputValue := json.RawMessage{}
if err := dec.Decode(&inputValue); err != nil {
return err
}
if msgV2, ok := pb.(protov2.Message); ok {
return protojson.UnmarshalOptions{
AllowPartial: u.AllowUnknownFields,
}.Unmarshal(inputValue, msgV2)
}
if err := u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil); err != nil {
return err
}
return checkRequiredFields(pb)
}
// Unmarshal unmarshals a JSON object stream into a protocol
// buffer. This function is lenient and will decode any options
// permutations of the related Marshaler.
func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error {
dec := json.NewDecoder(r)
return u.UnmarshalNext(dec, pb)
}
// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
// This function is lenient and will decode any options permutations of the
// related Marshaler.
func UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
return new(Unmarshaler).UnmarshalNext(dec, pb)
}
// Unmarshal unmarshals a JSON object stream into a protocol
// buffer. This function is lenient and will decode any options
// permutations of the related Marshaler.
func Unmarshal(r io.Reader, pb proto.Message) error {
return new(Unmarshaler).Unmarshal(r, pb)
}
// UnmarshalString will populate the fields of a protocol buffer based
// on a JSON string. This function is lenient and will decode any options
// permutations of the related Marshaler.
func UnmarshalString(str string, pb proto.Message) error {
return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb)
}
// unmarshalValue converts/copies a value into the target.
// prop may be nil.
func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error {
targetType := target.Type()
// Allocate memory for pointer fields.
if targetType.Kind() == reflect.Ptr {
// If input value is "null" and target is a pointer type, then the field should be treated as not set
// UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue.
_, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler)
if string(inputValue) == "null" && targetType != reflect.TypeOf(&types.Value{}) && !isJSONPBUnmarshaler {
return nil
}
target.Set(reflect.New(targetType.Elem()))
return u.unmarshalValue(target.Elem(), inputValue, prop)
}
if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok {
return jsu.UnmarshalJSONPB(u, []byte(inputValue))
}
// Handle well-known types that are not pointers.
if w, ok := target.Addr().Interface().(isWkt); ok {
switch w.XXX_WellKnownType() {
case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
"Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
return u.unmarshalValue(target.Field(0), inputValue, prop)
case "Any":
// Use json.RawMessage pointer type instead of value to support pre-1.8 version.
// 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see
// https://github.com/golang/go/issues/14493
var jsonFields map[string]*json.RawMessage
if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
return err
}
val, ok := jsonFields["@type"]
if !ok || val == nil {
return errors.New("Any JSON doesn't have '@type'")
}
var turl string
if err := json.Unmarshal([]byte(*val), &turl); err != nil {
return fmt.Errorf("can't unmarshal Any's '@type': %q", *val)
}
target.Field(0).SetString(turl)
var m proto.Message
var err error
if u.AnyResolver != nil {
m, err = u.AnyResolver.Resolve(turl)
} else {
m, err = defaultResolveAny(turl)
}
if err != nil {
return err
}
if _, ok := m.(isWkt); ok {
val, ok := jsonFields["value"]
if !ok {
return errors.New("Any JSON doesn't have 'value'")
}
if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil {
return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
}
} else {
delete(jsonFields, "@type")
nestedProto, uerr := json.Marshal(jsonFields)
if uerr != nil {
return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", uerr)
}
if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil {
return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
}
}
b, err := proto.Marshal(m)
if err != nil {
return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err)
}
target.Field(1).SetBytes(b)
return nil
case "Duration":
unq, err := unquote(string(inputValue))
if err != nil {
return err
}
d, err := time.ParseDuration(unq)
if err != nil {
return fmt.Errorf("bad Duration: %v", err)
}
ns := d.Nanoseconds()
s := ns / 1e9
ns %= 1e9
target.Field(0).SetInt(s)
target.Field(1).SetInt(ns)
return nil
case "Timestamp":
unq, err := unquote(string(inputValue))
if err != nil {
return err
}
t, err := time.Parse(time.RFC3339Nano, unq)
if err != nil {
return fmt.Errorf("bad Timestamp, should be RFC 3339 encoded: %v", err)
}
target.Field(0).SetInt(t.Unix())
target.Field(1).SetInt(int64(t.Nanosecond()))
return nil
case "Struct":
var m map[string]json.RawMessage
if err := json.Unmarshal(inputValue, &m); err != nil {
return fmt.Errorf("bad StructValue: %v", err)
}
target.Field(0).Set(reflect.ValueOf(map[string]*types.Value{}))
for k, jv := range m {
pv := &types.Value{}
if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil {
return fmt.Errorf("bad value in StructValue for key %q: %v", k, err)
}
target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv))
}
return nil
case "ListValue":
var s []json.RawMessage
if err := json.Unmarshal(inputValue, &s); err != nil {
return fmt.Errorf("bad ListValue: %v", err)
}
target.Field(0).Set(reflect.ValueOf(make([]*types.Value, len(s))))
for i, sv := range s {
if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil {
return err
}
}
return nil
case "Value":
ivStr := string(inputValue)
if ivStr == "null" {
target.Field(0).Set(reflect.ValueOf(&types.Value_NullValue{}))
} else if v, err := strconv.ParseFloat(ivStr, 0); err == nil {
target.Field(0).Set(reflect.ValueOf(&types.Value_NumberValue{NumberValue: v}))
} else if v, err := unquote(ivStr); err == nil {
target.Field(0).Set(reflect.ValueOf(&types.Value_StringValue{StringValue: v}))
} else if v, err := strconv.ParseBool(ivStr); err == nil {
target.Field(0).Set(reflect.ValueOf(&types.Value_BoolValue{BoolValue: v}))
} else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil {
lv := &types.ListValue{}
target.Field(0).Set(reflect.ValueOf(&types.Value_ListValue{ListValue: lv}))
return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop)
} else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil {
sv := &types.Struct{}
target.Field(0).Set(reflect.ValueOf(&types.Value_StructValue{StructValue: sv}))
return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop)
} else {
return fmt.Errorf("unrecognized type for Value %q", ivStr)
}
return nil
}
}
if t, ok := target.Addr().Interface().(*time.Time); ok {
ts := &types.Timestamp{}
if err := u.unmarshalValue(reflect.ValueOf(ts).Elem(), inputValue, prop); err != nil {
return err
}
tt, err := types.TimestampFromProto(ts)
if err != nil {
return err
}
*t = tt
return nil
}
if d, ok := target.Addr().Interface().(*time.Duration); ok {
dur := &types.Duration{}
if err := u.unmarshalValue(reflect.ValueOf(dur).Elem(), inputValue, prop); err != nil {
return err
}
dd, err := types.DurationFromProto(dur)
if err != nil {
return err
}
*d = dd
return nil
}
// Handle enums, which have an underlying type of int32,
// and may appear as strings.
// The case of an enum appearing as a number is handled
// at the bottom of this function.
if inputValue[0] == '"' && prop != nil && prop.Enum != "" {
vmap := proto.EnumValueMap(prop.Enum)
// Don't need to do unquoting; valid enum names
// are from a limited character set.
s := inputValue[1 : len(inputValue)-1]
n, ok := vmap[string(s)]
if !ok {
return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum)
}
if target.Kind() == reflect.Ptr { // proto2
target.Set(reflect.New(targetType.Elem()))
target = target.Elem()
}
if targetType.Kind() != reflect.Int32 {
return fmt.Errorf("invalid target %q for enum %s", targetType.Kind(), prop.Enum)
}
target.SetInt(int64(n))
return nil
}
if prop != nil && len(prop.CustomType) > 0 && target.CanAddr() {
if m, ok := target.Addr().Interface().(interface {
UnmarshalJSON([]byte) error
}); ok {
return json.Unmarshal(inputValue, m)
}
}
// Handle nested messages.
if targetType.Kind() == reflect.Struct {
var jsonFields map[string]json.RawMessage
if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
return err
}
consumeField := func(prop *proto.Properties) (json.RawMessage, bool) {
// Be liberal in what names we accept; both orig_name and camelName are okay.
fieldNames := acceptedJSONFieldNames(prop)
vOrig, okOrig := jsonFields[fieldNames.orig]
vCamel, okCamel := jsonFields[fieldNames.camel]
if !okOrig && !okCamel {
return nil, false
}
// If, for some reason, both are present in the data, favour the camelName.
var raw json.RawMessage
if okOrig {
raw = vOrig
delete(jsonFields, fieldNames.orig)
}
if okCamel {
raw = vCamel
delete(jsonFields, fieldNames.camel)
}
return raw, true
}
sprops := proto.GetProperties(targetType)
for i := 0; i < target.NumField(); i++ {
ft := target.Type().Field(i)
if strings.HasPrefix(ft.Name, "XXX_") {
continue
}
valueForField, ok := consumeField(sprops.Prop[i])
if !ok {
continue
}
if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil {
return err
}
}
// Check for any oneof fields.
if len(jsonFields) > 0 {
for _, oop := range sprops.OneofTypes {
raw, ok := consumeField(oop.Prop)
if !ok {
continue
}
nv := reflect.New(oop.Type.Elem())
target.Field(oop.Field).Set(nv)
if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil {
return err
}
}
}
// Handle proto2 extensions.
if len(jsonFields) > 0 {
if ep, ok := target.Addr().Interface().(proto.Message); ok {
for _, ext := range proto.RegisteredExtensions(ep) {
name := fmt.Sprintf("[%s]", ext.Name)
raw, ok := jsonFields[name]
if !ok {
continue
}
delete(jsonFields, name)
nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem())
if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil {
return err
}
if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil {
return err
}
}
}
}
if !u.AllowUnknownFields && len(jsonFields) > 0 {
// Pick any field to be the scapegoat.
var f string
for fname := range jsonFields {
f = fname
break
}
return fmt.Errorf("unknown field %q in %v", f, targetType)
}
return nil
}
// Handle arrays
if targetType.Kind() == reflect.Slice {
if targetType.Elem().Kind() == reflect.Uint8 {
outRef := reflect.New(targetType)
outVal := outRef.Interface()
//CustomType with underlying type []byte
if _, ok := outVal.(interface {
UnmarshalJSON([]byte) error
}); ok {
if err := json.Unmarshal(inputValue, outVal); err != nil {
return err
}
target.Set(outRef.Elem())
return nil
}
// Special case for encoded bytes. Pre-go1.5 doesn't support unmarshalling
// strings into aliased []byte types.
// https://github.com/golang/go/commit/4302fd0409da5e4f1d71471a6770dacdc3301197
// https://github.com/golang/go/commit/c60707b14d6be26bf4213114d13070bff00d0b0a
var out []byte
if err := json.Unmarshal(inputValue, &out); err != nil {
return err
}
target.SetBytes(out)
return nil
}
var slc []json.RawMessage
if err := json.Unmarshal(inputValue, &slc); err != nil {
return err
}
if slc != nil {
l := len(slc)
target.Set(reflect.MakeSlice(targetType, l, l))
for i := 0; i < l; i++ {
if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil {
return err
}
}
}
return nil
}
// Handle maps (whose keys are always strings)
if targetType.Kind() == reflect.Map {
var mp map[string]json.RawMessage
if err := json.Unmarshal(inputValue, &mp); err != nil {
return err
}
if mp != nil {
target.Set(reflect.MakeMap(targetType))
for ks, raw := range mp {
// Unmarshal map key. The core json library already decoded the key into a
// string, so we handle that specially. Other types were quoted post-serialization.
var k reflect.Value
if targetType.Key().Kind() == reflect.String {
k = reflect.ValueOf(ks)
} else {
k = reflect.New(targetType.Key()).Elem()
var kprop *proto.Properties
if prop != nil && prop.MapKeyProp != nil {
kprop = prop.MapKeyProp
}
if err := u.unmarshalValue(k, json.RawMessage(ks), kprop); err != nil {
return err
}
}
if !k.Type().AssignableTo(targetType.Key()) {
k = k.Convert(targetType.Key())
}
// Unmarshal map value.
v := reflect.New(targetType.Elem()).Elem()
var vprop *proto.Properties
if prop != nil && prop.MapValProp != nil {
vprop = prop.MapValProp
}
if err := u.unmarshalValue(v, raw, vprop); err != nil {
return err
}
target.SetMapIndex(k, v)
}
}
return nil
}
// Non-finite numbers can be encoded as strings.
isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
if isFloat {
if num, ok := nonFinite[string(inputValue)]; ok {
target.SetFloat(num)
return nil
}
}
// integers & floats can be encoded as strings. In this case we drop
// the quotes and proceed as normal.
isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 ||
targetType.Kind() == reflect.Int32 || targetType.Kind() == reflect.Uint32 ||
targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
if isNum && strings.HasPrefix(string(inputValue), `"`) {
inputValue = inputValue[1 : len(inputValue)-1]
}
// Use the encoding/json for parsing other value types.
return json.Unmarshal(inputValue, target.Addr().Interface())
}
func unquote(s string) (string, error) {
var ret string
err := json.Unmarshal([]byte(s), &ret)
return ret, err
}
// jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute.
func jsonProperties(f reflect.StructField, origName bool) *proto.Properties {
var prop proto.Properties
prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f)
if origName || prop.JSONName == "" {
prop.JSONName = prop.OrigName
}
return &prop
}
type fieldNames struct {
orig, camel string
}
func acceptedJSONFieldNames(prop *proto.Properties) fieldNames {
opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName}
if prop.JSONName != "" {
opts.camel = prop.JSONName
}
return opts
}
// Writer wrapper inspired by https://blog.golang.org/errors-are-values
type errWriter struct {
writer io.Writer
err error
}
func (w *errWriter) write(str string) {
if w.err != nil {
return
}
_, w.err = w.writer.Write([]byte(str))
}
// Map fields may have key types of non-float scalars, strings and enums.
// The easiest way to sort them in some deterministic order is to use fmt.
// If this turns out to be inefficient we can always consider other options,
// such as doing a Schwartzian transform.
//
// Numeric keys are sorted in numeric order per
// https://developers.google.com/protocol-buffers/docs/proto#maps.
type mapKeys []reflect.Value
func (s mapKeys) Len() int { return len(s) }
func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s mapKeys) Less(i, j int) bool {
if k := s[i].Kind(); k == s[j].Kind() {
switch k {
case reflect.String:
return s[i].String() < s[j].String()
case reflect.Int32, reflect.Int64:
return s[i].Int() < s[j].Int()
case reflect.Uint32, reflect.Uint64:
return s[i].Uint() < s[j].Uint()
}
}
return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
}
// checkRequiredFields returns an error if any required field in the given proto message is not set.
// This function is used by both Marshal and Unmarshal. While required fields only exist in a
// proto2 message, a proto3 message can contain proto2 message(s).
func checkRequiredFields(pb proto.Message) error {
// Most well-known type messages do not contain required fields. The "Any" type may contain
// a message that has required fields.
//
// When an Any message is being marshaled, the code will invoked proto.Unmarshal on Any.Value
// field in order to transform that into JSON, and that should have returned an error if a
// required field is not set in the embedded message.
//
// When an Any message is being unmarshaled, the code will have invoked proto.Marshal on the
// embedded message to store the serialized message in Any.Value field, and that should have
// returned an error if a required field is not set.
if _, ok := pb.(isWkt); ok {
return nil
}
v := reflect.ValueOf(pb)
// Skip message if it is not a struct pointer.
if v.Kind() != reflect.Ptr {
return nil
}
v = v.Elem()
if v.Kind() != reflect.Struct {
return nil
}
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
sfield := v.Type().Field(i)
if sfield.PkgPath != "" {
// blank PkgPath means the field is exported; skip if not exported
continue
}
if strings.HasPrefix(sfield.Name, "XXX_") {
continue
}
// Oneof field is an interface implemented by wrapper structs containing the actual oneof
// field, i.e. an interface containing &T{real_value}.
if sfield.Tag.Get("protobuf_oneof") != "" {
if field.Kind() != reflect.Interface {
continue
}
v := field.Elem()
if v.Kind() != reflect.Ptr || v.IsNil() {
continue
}
v = v.Elem()
if v.Kind() != reflect.Struct || v.NumField() < 1 {
continue
}
field = v.Field(0)
sfield = v.Type().Field(0)
}
protoTag := sfield.Tag.Get("protobuf")
if protoTag == "" {
continue
}
var prop proto.Properties
prop.Init(sfield.Type, sfield.Name, protoTag, &sfield)
switch field.Kind() {
case reflect.Map:
if field.IsNil() {
continue
}
// Check each map value.
keys := field.MapKeys()
for _, k := range keys {
v := field.MapIndex(k)
if err := checkRequiredFieldsInValue(v); err != nil {
return err
}
}
case reflect.Slice:
// Handle non-repeated type, e.g. bytes.
if !prop.Repeated {
if prop.Required && field.IsNil() {
return fmt.Errorf("required field %q is not set", prop.Name)
}
continue
}
// Handle repeated type.
if field.IsNil() {
continue
}
// Check each slice item.
for i := 0; i < field.Len(); i++ {
v := field.Index(i)
if err := checkRequiredFieldsInValue(v); err != nil {
return err
}
}
case reflect.Ptr:
if field.IsNil() {
if prop.Required {
return fmt.Errorf("required field %q is not set", prop.Name)
}
continue
}
if err := checkRequiredFieldsInValue(field); err != nil {
return err
}
}
}
// Handle proto2 extensions.
for _, ext := range proto.RegisteredExtensions(pb) {
if !proto.HasExtension(pb, ext) {
continue
}
ep, err := proto.GetExtension(pb, ext)
if err != nil {
return err
}
err = checkRequiredFieldsInValue(reflect.ValueOf(ep))
if err != nil {
return err
}
}
return nil
}
func checkRequiredFieldsInValue(v reflect.Value) error {
if v.Type().Implements(messageType) {
return checkRequiredFields(v.Interface().(proto.Message))
}
return nil
}
package keyformat
import "encoding/binary"
// This file builds some dedicated key formatters for what appears in benchmarks.
// Prefixes a single byte before a 32 byte hash.
type FastPrefixFormatter struct {
prefix byte
length int
prefixSlice []byte
}
func NewFastPrefixFormatter(prefix byte, length int) *FastPrefixFormatter {
return &FastPrefixFormatter{prefix: prefix, length: length, prefixSlice: []byte{prefix}}
}
func (f *FastPrefixFormatter) Key(bz []byte) []byte {
key := make([]byte, 1+f.length)
key[0] = f.prefix
copy(key[1:], bz)
return key
}
func (f *FastPrefixFormatter) Scan(key []byte, a interface{}) {
scan(a, key[1:])
}
func (f *FastPrefixFormatter) KeyInt64(bz int64) []byte {
key := make([]byte, 1+f.length)
key[0] = f.prefix
binary.BigEndian.PutUint64(key[1:], uint64(bz))
return key
}
func (f *FastPrefixFormatter) Prefix() []byte {
return f.prefixSlice
}
func (f *FastPrefixFormatter) Length() int {
return 1 + f.length
}
package iavl
import (
"bytes"
"errors"
"fmt"
"sort"
"sync"
log "cosmossdk.io/log"
dbm "github.com/cosmos/iavl/db"
"github.com/cosmos/iavl/fastnode"
ibytes "github.com/cosmos/iavl/internal/bytes"
)
var (
// ErrVersionDoesNotExist is returned if a requested version does not exist.
ErrVersionDoesNotExist = errors.New("version does not exist")
// ErrKeyDoesNotExist is returned if a key does not exist.
ErrKeyDoesNotExist = errors.New("key does not exist")
)
type Option func(*Options)
// MutableTree is a persistent tree which keeps track of versions. It is not safe for concurrent
// use, and should be guarded by a Mutex or RWLock as appropriate. An immutable tree at a given
// version can be returned via GetImmutable, which is safe for concurrent access.
//
// Given and returned key/value byte slices must not be modified, since they may point to data
// located inside IAVL which would also be modified.
//
// The inner ImmutableTree should not be used directly by callers.
type MutableTree struct {
logger log.Logger
*ImmutableTree // The current, working tree.
lastSaved *ImmutableTree // The most recently saved tree.
unsavedFastNodeAdditions *sync.Map // map[string]*FastNode FastNodes that have not yet been saved to disk
unsavedFastNodeRemovals *sync.Map // map[string]interface{} FastNodes that have not yet been removed from disk
ndb *nodeDB
skipFastStorageUpgrade bool // If true, the tree will work like no fast storage and always not upgrade fast storage
mtx sync.Mutex
}
// NewMutableTree returns a new tree with the specified optional options.
func NewMutableTree(db dbm.DB, cacheSize int, skipFastStorageUpgrade bool, lg log.Logger, options ...Option) *MutableTree {
opts := DefaultOptions()
for _, opt := range options {
opt(&opts)
}
ndb := newNodeDB(db, cacheSize, opts, lg)
head := &ImmutableTree{ndb: ndb, skipFastStorageUpgrade: skipFastStorageUpgrade}
return &MutableTree{
logger: lg,
ImmutableTree: head,
lastSaved: head.clone(),
unsavedFastNodeAdditions: &sync.Map{},
unsavedFastNodeRemovals: &sync.Map{},
ndb: ndb,
skipFastStorageUpgrade: skipFastStorageUpgrade,
}
}
// IsEmpty returns whether or not the tree has any keys. Only trees that are
// not empty can be saved.
func (tree *MutableTree) IsEmpty() bool {
return tree.ImmutableTree.Size() == 0
}
// VersionExists returns whether or not a version exists.
func (tree *MutableTree) VersionExists(version int64) bool {
legacyLatestVersion, err := tree.ndb.getLegacyLatestVersion()
if err != nil {
return false
}
if version <= legacyLatestVersion {
has, err := tree.ndb.hasLegacyVersion(version)
return err == nil && has
}
firstVersion, err := tree.ndb.getFirstVersion()
if err != nil {
return false
}
latestVersion, err := tree.ndb.getLatestVersion()
if err != nil {
return false
}
return firstVersion <= version && version <= latestVersion
}
// AvailableVersions returns all available versions in ascending order
func (tree *MutableTree) AvailableVersions() []int {
firstVersion, err := tree.ndb.getFirstVersion()
if err != nil {
return nil
}
latestVersion, err := tree.ndb.getLatestVersion()
if err != nil {
return nil
}
legacyLatestVersion, err := tree.ndb.getLegacyLatestVersion()
if err != nil {
return nil
}
res := make([]int, 0)
if legacyLatestVersion > firstVersion {
for version := firstVersion; version < legacyLatestVersion; version++ {
has, err := tree.ndb.hasLegacyVersion(version)
if err != nil {
return nil
}
if has {
res = append(res, int(version))
}
}
firstVersion = legacyLatestVersion
}
for version := firstVersion; version <= latestVersion; version++ {
res = append(res, int(version))
}
return res
}
// Hash returns the hash of the latest saved version of the tree, as returned
// by SaveVersion. If no versions have been saved, Hash returns nil.
func (tree *MutableTree) Hash() []byte {
return tree.lastSaved.Hash()
}
// WorkingHash returns the hash of the current working tree.
func (tree *MutableTree) WorkingHash() []byte {
return tree.root.hashWithCount(tree.WorkingVersion())
}
func (tree *MutableTree) WorkingVersion() int64 {
version := tree.version + 1
if version == 1 && tree.ndb.opts.InitialVersion > 0 {
version = int64(tree.ndb.opts.InitialVersion)
}
return version
}
// String returns a string representation of the tree.
func (tree *MutableTree) String() (string, error) {
return tree.ndb.String()
}
// Set sets a key in the working tree. Nil values are invalid. The given
// key/value byte slices must not be modified after this call, since they point
// to slices stored within IAVL. It returns true when an existing value was
// updated, while false means it was a new key.
func (tree *MutableTree) Set(key, value []byte) (updated bool, err error) {
updated, err = tree.set(key, value)
if err != nil {
return false, err
}
return updated, nil
}
// Get returns the value of the specified key if it exists, or nil otherwise.
// The returned value must not be modified, since it may point to data stored within IAVL.
func (tree *MutableTree) Get(key []byte) ([]byte, error) {
if tree.root == nil {
return nil, nil
}
if !tree.skipFastStorageUpgrade {
if fastNode, ok := tree.unsavedFastNodeAdditions.Load(ibytes.UnsafeBytesToStr(key)); ok {
return fastNode.(*fastnode.Node).GetValue(), nil
}
// check if node was deleted
if _, ok := tree.unsavedFastNodeRemovals.Load(string(key)); ok {
return nil, nil
}
}
return tree.ImmutableTree.Get(key)
}
// Import returns an importer for tree nodes previously exported by ImmutableTree.Export(),
// producing an identical IAVL tree. The caller must call Close() on the importer when done.
//
// version should correspond to the version that was initially exported. It must be greater than
// or equal to the highest ExportNode version number given.
//
// Import can only be called on an empty tree. It is the callers responsibility that no other
// modifications are made to the tree while importing.
func (tree *MutableTree) Import(version int64) (*Importer, error) {
return newImporter(tree, version)
}
// Iterate iterates over all keys of the tree. The keys and values must not be modified,
// since they may point to data stored within IAVL. Returns true if stopped by callnack, false otherwise
func (tree *MutableTree) Iterate(fn func(key []byte, value []byte) bool) (stopped bool, err error) {
if tree.root == nil {
return false, nil
}
if tree.skipFastStorageUpgrade {
return tree.ImmutableTree.Iterate(fn)
}
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
if err != nil {
return false, err
}
if !isFastCacheEnabled {
return tree.ImmutableTree.Iterate(fn)
}
itr := NewUnsavedFastIterator(nil, nil, true, tree.ndb, tree.unsavedFastNodeAdditions, tree.unsavedFastNodeRemovals)
defer itr.Close()
for ; itr.Valid(); itr.Next() {
if fn(itr.Key(), itr.Value()) {
return true, nil
}
}
return false, nil
}
// Iterator returns an iterator over the mutable tree.
// CONTRACT: no updates are made to the tree while an iterator is active.
func (tree *MutableTree) Iterator(start, end []byte, ascending bool) (dbm.Iterator, error) {
if !tree.skipFastStorageUpgrade {
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
if err != nil {
return nil, err
}
if isFastCacheEnabled {
return NewUnsavedFastIterator(start, end, ascending, tree.ndb, tree.unsavedFastNodeAdditions, tree.unsavedFastNodeRemovals), nil
}
}
return tree.ImmutableTree.Iterator(start, end, ascending)
}
func (tree *MutableTree) set(key []byte, value []byte) (updated bool, err error) {
if value == nil {
return updated, fmt.Errorf("attempt to store nil value at key '%s'", key)
}
if tree.ImmutableTree.root == nil {
if !tree.skipFastStorageUpgrade {
tree.addUnsavedAddition(key, fastnode.NewNode(key, value, tree.version+1))
}
tree.ImmutableTree.root = NewNode(key, value)
return updated, nil
}
tree.ImmutableTree.root, updated, err = tree.recursiveSet(tree.ImmutableTree.root, key, value)
return updated, err
}
func (tree *MutableTree) recursiveSet(node *Node, key []byte, value []byte) (
newSelf *Node, updated bool, err error,
) {
if node.isLeaf() {
return tree.recursiveSetLeaf(node, key, value)
}
node, err = node.clone(tree)
if err != nil {
return nil, false, err
}
if bytes.Compare(key, node.key) < 0 {
node.leftNode, updated, err = tree.recursiveSet(node.leftNode, key, value)
if err != nil {
return nil, updated, err
}
} else {
node.rightNode, updated, err = tree.recursiveSet(node.rightNode, key, value)
if err != nil {
return nil, updated, err
}
}
if updated {
return node, updated, nil
}
err = node.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, false, err
}
newNode, err := tree.balance(node)
if err != nil {
return nil, false, err
}
return newNode, updated, err
}
func (tree *MutableTree) recursiveSetLeaf(node *Node, key []byte, value []byte) (
newSelf *Node, updated bool, err error,
) {
version := tree.version + 1
if !tree.skipFastStorageUpgrade {
tree.addUnsavedAddition(key, fastnode.NewNode(key, value, version))
}
switch bytes.Compare(key, node.key) {
case -1: // setKey < leafKey
return &Node{
key: node.key,
subtreeHeight: 1,
size: 2,
nodeKey: nil,
leftNode: NewNode(key, value),
rightNode: node,
}, false, nil
case 1: // setKey > leafKey
return &Node{
key: key,
subtreeHeight: 1,
size: 2,
nodeKey: nil,
leftNode: node,
rightNode: NewNode(key, value),
}, false, nil
default:
return NewNode(key, value), true, nil
}
}
// Remove removes a key from the working tree. The given key byte slice should not be modified
// after this call, since it may point to data stored inside IAVL.
func (tree *MutableTree) Remove(key []byte) ([]byte, bool, error) {
if tree.root == nil {
return nil, false, nil
}
newRoot, _, value, removed, err := tree.recursiveRemove(tree.root, key)
if err != nil {
return nil, false, err
}
if !removed {
return nil, false, nil
}
if !tree.skipFastStorageUpgrade {
tree.addUnsavedRemoval(key)
}
tree.root = newRoot
return value, true, nil
}
// removes the node corresponding to the passed key and balances the tree.
// It returns:
// - the hash of the new node (or nil if the node is the one removed)
// - the node that replaces the orig. node after remove
// - new leftmost leaf key for tree after successfully removing 'key' if changed.
// - the removed value
func (tree *MutableTree) recursiveRemove(node *Node, key []byte) (newSelf *Node, newKey []byte, newValue []byte, removed bool, err error) {
tree.logger.Debug("recursiveRemove", "node", node, "key", key)
if node.isLeaf() {
if bytes.Equal(key, node.key) {
return nil, nil, node.value, true, nil
}
return node, nil, nil, false, nil
}
node, err = node.clone(tree)
if err != nil {
return nil, nil, nil, false, err
}
// node.key < key; we go to the left to find the key:
if bytes.Compare(key, node.key) < 0 {
newLeftNode, newKey, value, removed, err := tree.recursiveRemove(node.leftNode, key)
if err != nil {
return nil, nil, nil, false, err
}
if !removed {
return node, nil, value, removed, nil
}
if newLeftNode == nil { // left node held value, was removed
return node.rightNode, node.key, value, removed, nil
}
node.leftNode = newLeftNode
err = node.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, nil, nil, false, err
}
node, err = tree.balance(node)
if err != nil {
return nil, nil, nil, false, err
}
return node, newKey, value, removed, nil
}
// node.key >= key; either found or look to the right:
newRightNode, newKey, value, removed, err := tree.recursiveRemove(node.rightNode, key)
if err != nil {
return nil, nil, nil, false, err
}
if !removed {
return node, nil, value, removed, nil
}
if newRightNode == nil { // right node held value, was removed
return node.leftNode, nil, value, removed, nil
}
node.rightNode = newRightNode
if newKey != nil {
node.key = newKey
}
err = node.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, nil, nil, false, err
}
node, err = tree.balance(node)
if err != nil {
return nil, nil, nil, false, err
}
return node, nil, value, removed, nil
}
// Load the latest versioned tree from disk.
func (tree *MutableTree) Load() (int64, error) {
return tree.LoadVersion(int64(0))
}
// Returns the version number of the specific version found
func (tree *MutableTree) LoadVersion(targetVersion int64) (int64, error) {
firstVersion, err := tree.ndb.getFirstVersion()
if err != nil {
return 0, err
}
if firstVersion > 0 && firstVersion < int64(tree.ndb.opts.InitialVersion) {
return firstVersion, fmt.Errorf("initial version set to %v, but found earlier version %v",
tree.ndb.opts.InitialVersion, firstVersion)
}
latestVersion, err := tree.ndb.getLatestVersion()
if err != nil {
return 0, err
}
if firstVersion > 0 && firstVersion < int64(tree.ndb.opts.InitialVersion) {
return latestVersion, fmt.Errorf("initial version set to %v, but found earlier version %v",
tree.ndb.opts.InitialVersion, firstVersion)
}
if latestVersion < targetVersion {
return latestVersion, fmt.Errorf("wanted to load target %d but only found up to %d", targetVersion, latestVersion)
}
if firstVersion == 0 {
if targetVersion <= 0 {
if !tree.skipFastStorageUpgrade {
tree.mtx.Lock()
defer tree.mtx.Unlock()
_, err := tree.enableFastStorageAndCommitIfNotEnabled()
return 0, err
}
return 0, nil
}
return 0, fmt.Errorf("no versions found while trying to load %v", targetVersion)
}
if targetVersion <= 0 {
targetVersion = latestVersion
}
if !tree.VersionExists(targetVersion) {
return 0, ErrVersionDoesNotExist
}
rootNodeKey, err := tree.ndb.GetRoot(targetVersion)
if err != nil {
return 0, err
}
iTree := &ImmutableTree{
ndb: tree.ndb,
version: targetVersion,
skipFastStorageUpgrade: tree.skipFastStorageUpgrade,
}
if rootNodeKey != nil {
iTree.root, err = tree.ndb.GetNode(rootNodeKey)
if err != nil {
return 0, err
}
}
tree.ImmutableTree = iTree
tree.lastSaved = iTree.clone()
if !tree.skipFastStorageUpgrade {
// Attempt to upgrade
if _, err := tree.enableFastStorageAndCommitIfNotEnabled(); err != nil {
return 0, err
}
}
return latestVersion, nil
}
// loadVersionForOverwriting attempts to load a tree at a previously committed
// version, or the latest version below it. Any versions greater than targetVersion will be deleted.
func (tree *MutableTree) LoadVersionForOverwriting(targetVersion int64) error {
if _, err := tree.LoadVersion(targetVersion); err != nil {
return err
}
if err := tree.ndb.DeleteVersionsFrom(targetVersion + 1); err != nil {
return err
}
// Commit the tree rollback first
// The fast storage rebuild don't have to be atomic with this,
// because it's idempotent and will do again when `LoadVersion`.
if err := tree.ndb.Commit(); err != nil {
return err
}
if !tree.skipFastStorageUpgrade {
// it'll repopulates the fast node index because of version mismatch.
if _, err := tree.enableFastStorageAndCommitIfNotEnabled(); err != nil {
return err
}
}
return nil
}
// Returns true if the tree may be auto-upgraded, false otherwise
// An example of when an upgrade may be performed is when we are enaling fast storage for the first time or
// need to overwrite fast nodes due to mismatch with live state.
func (tree *MutableTree) IsUpgradeable() (bool, error) {
shouldForce, err := tree.ndb.shouldForceFastStorageUpgrade()
if err != nil {
return false, err
}
return !tree.skipFastStorageUpgrade && (!tree.ndb.hasUpgradedToFastStorage() || shouldForce), nil
}
// enableFastStorageAndCommitIfNotEnabled if nodeDB doesn't mark fast storage as enabled, enable it, and commit the update.
// Checks whether the fast cache on disk matches latest live state. If not, deletes all existing fast nodes and repopulates them
// from latest tree.
func (tree *MutableTree) enableFastStorageAndCommitIfNotEnabled() (bool, error) {
isUpgradeable, err := tree.IsUpgradeable()
if err != nil {
return false, err
}
if !isUpgradeable {
return false, nil
}
// If there is a mismatch between which fast nodes are on disk and the live state due to temporary
// downgrade and subsequent re-upgrade, we cannot know for sure which fast nodes have been removed while downgraded,
// Therefore, there might exist stale fast nodes on disk. As a result, to avoid persisting the stale state, it might
// be worth to delete the fast nodes from disk.
fastItr := NewFastIterator(nil, nil, true, tree.ndb)
defer fastItr.Close()
var deletedFastNodes uint64
for ; fastItr.Valid(); fastItr.Next() {
deletedFastNodes++
if err := tree.ndb.DeleteFastNode(fastItr.Key()); err != nil {
return false, err
}
}
if err := tree.enableFastStorageAndCommit(); err != nil {
tree.ndb.storageVersion = defaultStorageVersionValue
return false, err
}
return true, nil
}
func (tree *MutableTree) enableFastStorageAndCommit() error {
var err error
itr := NewIterator(nil, nil, true, tree.ImmutableTree)
defer itr.Close()
var upgradedFastNodes uint64
for ; itr.Valid(); itr.Next() {
upgradedFastNodes++
if err = tree.ndb.SaveFastNodeNoCache(fastnode.NewNode(itr.Key(), itr.Value(), tree.version)); err != nil {
return err
}
}
if err = itr.Error(); err != nil {
return err
}
latestVersion, err := tree.ndb.getLatestVersion()
if err != nil {
return err
}
if err = tree.ndb.SetFastStorageVersionToBatch(latestVersion); err != nil {
return err
}
return tree.ndb.Commit()
}
// GetImmutable loads an ImmutableTree at a given version for querying. The returned tree is
// safe for concurrent access, provided the version is not deleted, e.g. via `DeleteVersion()`.
func (tree *MutableTree) GetImmutable(version int64) (*ImmutableTree, error) {
rootNodeKey, err := tree.ndb.GetRoot(version)
if err != nil {
return nil, err
}
var root *Node
if rootNodeKey != nil {
root, err = tree.ndb.GetNode(rootNodeKey)
if err != nil {
return nil, err
}
}
return &ImmutableTree{
root: root,
ndb: tree.ndb,
version: version,
skipFastStorageUpgrade: tree.skipFastStorageUpgrade,
}, nil
}
// Rollback resets the working tree to the latest saved version, discarding
// any unsaved modifications.
func (tree *MutableTree) Rollback() {
if tree.version > 0 {
tree.ImmutableTree = tree.lastSaved.clone()
} else {
tree.ImmutableTree = &ImmutableTree{
ndb: tree.ndb,
version: 0,
skipFastStorageUpgrade: tree.skipFastStorageUpgrade,
}
}
if !tree.skipFastStorageUpgrade {
tree.unsavedFastNodeAdditions = &sync.Map{}
tree.unsavedFastNodeRemovals = &sync.Map{}
}
}
// GetVersioned gets the value at the specified key and version. The returned value must not be
// modified, since it may point to data stored within IAVL.
func (tree *MutableTree) GetVersioned(key []byte, version int64) ([]byte, error) {
if tree.VersionExists(version) {
if !tree.skipFastStorageUpgrade {
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
if err != nil {
return nil, err
}
if isFastCacheEnabled {
fastNode, _ := tree.ndb.GetFastNode(key)
if fastNode == nil && version == tree.ndb.latestVersion {
return nil, nil
}
if fastNode != nil && fastNode.GetVersionLastUpdatedAt() <= version {
return fastNode.GetValue(), nil
}
}
}
t, err := tree.GetImmutable(version)
if err != nil {
return nil, nil
}
value, err := t.Get(key)
if err != nil {
return nil, err
}
return value, nil
}
return nil, nil
}
// SetCommitting sets a flag to indicate that the tree is in the process of being saved.
// This is used to prevent parallel writing from async pruning.
func (tree *MutableTree) SetCommitting() {
tree.ndb.SetCommitting()
}
// UnsetCommitting unsets the flag to indicate that the tree is no longer in the process of being saved.
func (tree *MutableTree) UnsetCommitting() {
tree.ndb.UnsetCommitting()
}
// SaveVersion saves a new tree version to disk, based on the current state of
// the tree. Returns the hash and new version number.
func (tree *MutableTree) SaveVersion() ([]byte, int64, error) {
version := tree.WorkingVersion()
if tree.VersionExists(version) {
// If the version already exists, return an error as we're attempting to overwrite.
// However, the same hash means idempotent (i.e. no-op).
existingNodeKey, err := tree.ndb.GetRoot(version)
if err != nil {
return nil, version, err
}
var existingRoot *Node
if existingNodeKey != nil {
existingRoot, err = tree.ndb.GetNode(existingNodeKey)
if err != nil {
return nil, version, err
}
}
newHash := tree.WorkingHash()
if (existingRoot == nil && tree.root == nil) || (existingRoot != nil && bytes.Equal(existingRoot.hash, newHash)) { // TODO with WorkingHash
tree.version = version
tree.root = existingRoot
tree.ImmutableTree = tree.ImmutableTree.clone()
tree.lastSaved = tree.ImmutableTree.clone()
return newHash, version, nil
}
return nil, version, fmt.Errorf("version %d was already saved to different hash from %X (existing nodeKey %d)", version, newHash, existingNodeKey)
}
tree.logger.Debug("SAVE TREE", "version", version)
// save new fast nodes
if !tree.skipFastStorageUpgrade {
if err := tree.saveFastNodeVersion(version); err != nil {
return nil, version, err
}
}
// save new nodes
if tree.root == nil {
if err := tree.ndb.SaveEmptyRoot(version); err != nil {
return nil, 0, err
}
} else {
if tree.root.nodeKey != nil {
// it means there are no updated nodes
if err := tree.ndb.SaveRoot(version, tree.root.nodeKey); err != nil {
return nil, 0, err
}
// it means the reference node is a legacy node
if tree.root.isLegacy {
// it will update the legacy node to the new format
// which ensures the reference node is not a legacy node
tree.root.isLegacy = false
if err := tree.ndb.SaveNode(tree.root); err != nil {
return nil, 0, fmt.Errorf("failed to save the reference legacy node: %w", err)
}
}
} else {
if err := tree.saveNewNodes(version); err != nil {
return nil, 0, err
}
}
}
if err := tree.ndb.Commit(); err != nil {
return nil, version, err
}
tree.ndb.resetLatestVersion(version)
tree.version = version
// set new working tree
tree.ImmutableTree = tree.ImmutableTree.clone()
tree.lastSaved = tree.ImmutableTree.clone()
if !tree.skipFastStorageUpgrade {
tree.unsavedFastNodeAdditions = &sync.Map{}
tree.unsavedFastNodeRemovals = &sync.Map{}
}
return tree.Hash(), version, nil
}
func (tree *MutableTree) saveFastNodeVersion(latestVersion int64) error {
if err := tree.saveFastNodeAdditions(); err != nil {
return err
}
if err := tree.saveFastNodeRemovals(); err != nil {
return err
}
return tree.ndb.SetFastStorageVersionToBatch(latestVersion)
}
func (tree *MutableTree) getUnsavedFastNodeAdditions() map[string]*fastnode.Node {
additions := make(map[string]*fastnode.Node)
tree.unsavedFastNodeAdditions.Range(func(key, value interface{}) bool {
additions[key.(string)] = value.(*fastnode.Node)
return true
})
return additions
}
// getUnsavedFastNodeRemovals returns unsaved FastNodes to remove
func (tree *MutableTree) getUnsavedFastNodeRemovals() map[string]interface{} {
removals := make(map[string]interface{})
tree.unsavedFastNodeRemovals.Range(func(key, value interface{}) bool {
removals[key.(string)] = value
return true
})
return removals
}
// addUnsavedAddition stores an addition into the unsaved additions map
func (tree *MutableTree) addUnsavedAddition(key []byte, node *fastnode.Node) {
skey := ibytes.UnsafeBytesToStr(key)
tree.unsavedFastNodeRemovals.Delete(skey)
tree.unsavedFastNodeAdditions.Store(skey, node)
}
func (tree *MutableTree) saveFastNodeAdditions() error {
keysToSort := make([]string, 0)
tree.unsavedFastNodeAdditions.Range(func(k, v interface{}) bool {
keysToSort = append(keysToSort, k.(string))
return true
})
sort.Strings(keysToSort)
for _, key := range keysToSort {
val, _ := tree.unsavedFastNodeAdditions.Load(key)
if err := tree.ndb.SaveFastNode(val.(*fastnode.Node)); err != nil {
return err
}
}
return nil
}
// addUnsavedRemoval adds a removal to the unsaved removals map
func (tree *MutableTree) addUnsavedRemoval(key []byte) {
skey := ibytes.UnsafeBytesToStr(key)
tree.unsavedFastNodeAdditions.Delete(skey)
tree.unsavedFastNodeRemovals.Store(skey, true)
}
func (tree *MutableTree) saveFastNodeRemovals() error {
keysToSort := make([]string, 0)
tree.unsavedFastNodeRemovals.Range(func(k, v interface{}) bool {
keysToSort = append(keysToSort, k.(string))
return true
})
sort.Strings(keysToSort)
for _, key := range keysToSort {
if err := tree.ndb.DeleteFastNode(ibytes.UnsafeStrToBytes(key)); err != nil {
return err
}
}
return nil
}
// SetInitialVersion sets the initial version of the tree, replacing Options.InitialVersion.
// It is only used during the initial SaveVersion() call for a tree with no other versions,
// and is otherwise ignored.
func (tree *MutableTree) SetInitialVersion(version uint64) {
tree.ndb.opts.InitialVersion = version
}
// DeleteVersionsTo removes versions upto the given version from the MutableTree.
// It will not block the SaveVersion() call, instead it will be queued and executed deferred.
func (tree *MutableTree) DeleteVersionsTo(toVersion int64) error {
if err := tree.ndb.DeleteVersionsTo(toVersion); err != nil {
return err
}
return tree.ndb.Commit()
}
// Rotate right and return the new node and orphan.
func (tree *MutableTree) rotateRight(node *Node) (*Node, error) {
var err error
// TODO: optimize balance & rotate.
node, err = node.clone(tree)
if err != nil {
return nil, err
}
newNode, err := node.leftNode.clone(tree)
if err != nil {
return nil, err
}
node.leftNode = newNode.rightNode
newNode.rightNode = node
err = node.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, err
}
err = newNode.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, err
}
return newNode, nil
}
// Rotate left and return the new node and orphan.
func (tree *MutableTree) rotateLeft(node *Node) (*Node, error) {
var err error
// TODO: optimize balance & rotate.
node, err = node.clone(tree)
if err != nil {
return nil, err
}
newNode, err := node.rightNode.clone(tree)
if err != nil {
return nil, err
}
node.rightNode = newNode.leftNode
newNode.leftNode = node
err = node.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, err
}
err = newNode.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, err
}
return newNode, nil
}
// NOTE: assumes that node can be modified
// TODO: optimize balance & rotate
func (tree *MutableTree) balance(node *Node) (newSelf *Node, err error) {
if node.nodeKey != nil {
return nil, fmt.Errorf("unexpected balance() call on persisted node")
}
balance, err := node.calcBalance(tree.ImmutableTree)
if err != nil {
return nil, err
}
if balance > 1 {
lftBalance, err := node.leftNode.calcBalance(tree.ImmutableTree)
if err != nil {
return nil, err
}
if lftBalance >= 0 {
// Left Left Case
newNode, err := tree.rotateRight(node)
if err != nil {
return nil, err
}
return newNode, nil
}
// Left Right Case
node.leftNodeKey = nil
node.leftNode, err = tree.rotateLeft(node.leftNode)
if err != nil {
return nil, err
}
newNode, err := tree.rotateRight(node)
if err != nil {
return nil, err
}
return newNode, nil
}
if balance < -1 {
rightNode, err := node.getRightNode(tree.ImmutableTree)
if err != nil {
return nil, err
}
rightBalance, err := rightNode.calcBalance(tree.ImmutableTree)
if err != nil {
return nil, err
}
if rightBalance <= 0 {
// Right Right Case
newNode, err := tree.rotateLeft(node)
if err != nil {
return nil, err
}
return newNode, nil
}
// Right Left Case
node.rightNodeKey = nil
node.rightNode, err = tree.rotateRight(rightNode)
if err != nil {
return nil, err
}
newNode, err := tree.rotateLeft(node)
if err != nil {
return nil, err
}
return newNode, nil
}
// Nothing changed
return node, nil
}
// saveNewNodes save new created nodes by the changes of the working tree.
// NOTE: This function clears leftNode/rigthNode recursively and
// calls _hash() on the given node.
func (tree *MutableTree) saveNewNodes(version int64) error {
nonce := uint32(0)
newNodes := make([]*Node, 0)
var recursiveAssignKey func(*Node) ([]byte, error)
recursiveAssignKey = func(node *Node) ([]byte, error) {
if node.nodeKey != nil {
return node.GetKey(), nil
}
nonce++
node.nodeKey = &NodeKey{
version: version,
nonce: nonce,
}
var err error
// the inner nodes should have two children.
if node.subtreeHeight > 0 {
node.leftNodeKey, err = recursiveAssignKey(node.leftNode)
if err != nil {
return nil, err
}
node.rightNodeKey, err = recursiveAssignKey(node.rightNode)
if err != nil {
return nil, err
}
}
node._hash(version)
newNodes = append(newNodes, node)
return node.nodeKey.GetKey(), nil
}
if _, err := recursiveAssignKey(tree.root); err != nil {
return err
}
for _, node := range newNodes {
if err := tree.ndb.SaveNode(node); err != nil {
return err
}
node.leftNode, node.rightNode = nil, nil
}
return nil
}
// SaveChangeSet saves a ChangeSet to the tree.
// It is used to replay a ChangeSet as a new version.
func (tree *MutableTree) SaveChangeSet(cs *ChangeSet) (int64, error) {
// if the tree has uncommitted changes, return error
if tree.root != nil && tree.root.nodeKey == nil {
return 0, fmt.Errorf("cannot save changeset with uncommitted changes")
}
for _, pair := range cs.Pairs {
if pair.Delete {
_, removed, err := tree.Remove(pair.Key)
if !removed {
return 0, fmt.Errorf("attempted to remove non-existent key %s", pair.Key)
}
if err != nil {
return 0, err
}
} else {
if _, err := tree.Set(pair.Key, pair.Value); err != nil {
return 0, err
}
}
}
_, version, err := tree.SaveVersion()
return version, err
}
// Close closes the tree.
func (tree *MutableTree) Close() error {
tree.mtx.Lock()
defer tree.mtx.Unlock()
tree.ImmutableTree = nil
tree.lastSaved = nil
return tree.ndb.Close()
}
package iavl
// NOTE: This file favors int64 as opposed to int for size/counts.
// The Tree on the other hand favors int. This is intentional.
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"github.com/cosmos/iavl/cache"
"github.com/cosmos/iavl/internal/color"
"github.com/cosmos/iavl/internal/encoding"
)
const (
// ModeLegacyLeftNode is the mode for legacy left child in the node encoding/decoding.
ModeLegacyLeftNode = 0x01
// ModeLegacyRightNode is the mode for legacy right child in the node encoding/decoding.
ModeLegacyRightNode = 0x02
)
// NodeKey represents a key of node in the DB.
type NodeKey struct {
version int64
nonce uint32
}
// GetKey returns a byte slice of the NodeKey.
func (nk *NodeKey) GetKey() []byte {
b := make([]byte, 12)
binary.BigEndian.PutUint64(b, uint64(nk.version))
binary.BigEndian.PutUint32(b[8:], nk.nonce)
return b
}
// GetNodeKey returns a NodeKey from a byte slice.
func GetNodeKey(key []byte) *NodeKey {
return &NodeKey{
version: int64(binary.BigEndian.Uint64(key)),
nonce: binary.BigEndian.Uint32(key[8:]),
}
}
// GetRootKey returns a byte slice of the root node key for the given version.
func GetRootKey(version int64) []byte {
b := make([]byte, 12)
binary.BigEndian.PutUint64(b, uint64(version))
binary.BigEndian.PutUint32(b[8:], 1)
return b
}
// Node represents a node in a Tree.
type Node struct {
key []byte
value []byte
hash []byte
nodeKey *NodeKey
// Legacy: LeftNodeHash
// v1: Left node ptr via Version/key
leftNodeKey []byte
// Legacy: RightNodeHash
// v1: Right node ptr via Version/key
rightNodeKey []byte
size int64
leftNode *Node
rightNode *Node
subtreeHeight int8
isLegacy bool
}
var _ cache.Node = (*Node)(nil)
// NewNode returns a new node from a key, value and version.
func NewNode(key []byte, value []byte) *Node {
return &Node{
key: key,
value: value,
subtreeHeight: 0,
size: 1,
}
}
// GetKey returns the key of the node.
func (node *Node) GetKey() []byte {
if node.isLegacy {
return node.hash
}
return node.nodeKey.GetKey()
}
// MakeNode constructs an *Node from an encoded byte slice.
func MakeNode(nk, buf []byte) (*Node, error) {
// Read node header (height, size, key).
height, n, err := encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.height, %w", err)
}
buf = buf[n:]
height8 := int8(height)
if height != int64(height8) {
return nil, errors.New("invalid height, out of int8 range")
}
size, n, err := encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.size, %w", err)
}
buf = buf[n:]
key, n, err := encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.key, %w", err)
}
buf = buf[n:]
node := &Node{
subtreeHeight: height8,
size: size,
nodeKey: GetNodeKey(nk),
key: key,
}
// Read node body.
if node.isLeaf() {
val, _, err := encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.value, %w", err)
}
node.value = val
// ensure take the hash for the leaf node
node._hash(node.nodeKey.version)
} else { // Read children.
node.hash, n, err = encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.hash, %w", err)
}
buf = buf[n:]
mode, n, err := encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding mode, %w", err)
}
buf = buf[n:]
if mode < 0 || mode > 3 {
return nil, errors.New("invalid mode")
}
if mode&ModeLegacyLeftNode != 0 { // legacy leftNodeKey
node.leftNodeKey, n, err = encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding legacy node.leftNodeKey, %w", err)
}
buf = buf[n:]
} else {
var (
leftNodeKey NodeKey
nonce int64
)
leftNodeKey.version, n, err = encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.leftNodeKey.version, %w", err)
}
buf = buf[n:]
nonce, n, err = encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.leftNodeKey.nonce, %w", err)
}
buf = buf[n:]
leftNodeKey.nonce = uint32(nonce)
if nonce != int64(leftNodeKey.nonce) {
return nil, errors.New("invalid leftNodeKey.nonce, out of int32 range")
}
node.leftNodeKey = leftNodeKey.GetKey()
}
if mode&ModeLegacyRightNode != 0 { // legacy rightNodeKey
node.rightNodeKey, _, err = encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding legacy node.rightNodeKey, %w", err)
}
} else {
var (
rightNodeKey NodeKey
nonce int64
)
rightNodeKey.version, n, err = encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.rightNodeKey.version, %w", err)
}
buf = buf[n:]
nonce, _, err = encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.rightNodeKey.nonce, %w", err)
}
rightNodeKey.nonce = uint32(nonce)
if nonce != int64(rightNodeKey.nonce) {
return nil, errors.New("invalid rightNodeKey.nonce, out of int32 range")
}
node.rightNodeKey = rightNodeKey.GetKey()
}
}
return node, nil
}
// MakeLegacyNode constructs a legacy *Node from an encoded byte slice.
func MakeLegacyNode(hash, buf []byte) (*Node, error) {
// Read node header (height, size, version, key).
height, n, err := encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.height, %w", err)
}
buf = buf[n:]
if height < int64(math.MinInt8) || height > int64(math.MaxInt8) {
return nil, errors.New("invalid height, must be int8")
}
size, n, err := encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.size, %w", err)
}
buf = buf[n:]
ver, n, err := encoding.DecodeVarint(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.version, %w", err)
}
buf = buf[n:]
key, n, err := encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.key, %w", err)
}
buf = buf[n:]
node := &Node{
subtreeHeight: int8(height),
size: size,
nodeKey: &NodeKey{version: ver},
key: key,
hash: hash,
isLegacy: true,
}
// Read node body.
if node.isLeaf() {
val, _, err := encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.value, %w", err)
}
node.value = val
} else { // Read children.
leftHash, n, err := encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.leftHash, %w", err)
}
buf = buf[n:]
rightHash, _, err := encoding.DecodeBytes(buf)
if err != nil {
return nil, fmt.Errorf("decoding node.rightHash, %w", err)
}
node.leftNodeKey = leftHash
node.rightNodeKey = rightHash
}
return node, nil
}
// String returns a string representation of the node key.
func (nk *NodeKey) String() string {
return fmt.Sprintf("(%d, %d)", nk.version, nk.nonce)
}
// String returns a string representation of the node.
func (node *Node) String() string {
child := ""
if node.leftNode != nil && node.leftNode.nodeKey != nil {
child += fmt.Sprintf("{left %v}", node.leftNode.nodeKey)
}
if node.rightNode != nil && node.rightNode.nodeKey != nil {
child += fmt.Sprintf("{right %v}", node.rightNode.nodeKey)
}
return fmt.Sprintf("Node{%s:%s@ %v:%x-%x %d-%d %x}#%s\n",
color.ColoredBytes(node.key, color.Green, color.Blue),
color.ColoredBytes(node.value, color.Cyan, color.Blue),
node.nodeKey, node.leftNodeKey, node.rightNodeKey,
node.size, node.subtreeHeight, node.hash, child)
}
// clone creates a shallow copy of a node with its hash set to nil.
func (node *Node) clone(tree *MutableTree) (*Node, error) {
if node.isLeaf() {
return nil, ErrCloneLeafNode
}
// ensure get children
var err error
leftNode := node.leftNode
rightNode := node.rightNode
if node.nodeKey != nil {
leftNode, err = node.getLeftNode(tree.ImmutableTree)
if err != nil {
return nil, err
}
rightNode, err = node.getRightNode(tree.ImmutableTree)
if err != nil {
return nil, err
}
node.leftNode = nil
node.rightNode = nil
}
return &Node{
key: node.key,
subtreeHeight: node.subtreeHeight,
size: node.size,
hash: nil,
nodeKey: nil,
leftNodeKey: node.leftNodeKey,
rightNodeKey: node.rightNodeKey,
leftNode: leftNode,
rightNode: rightNode,
}, nil
}
func (node *Node) isLeaf() bool {
return node.subtreeHeight == 0
}
// Check if the node has a descendant with the given key.
func (node *Node) has(t *ImmutableTree, key []byte) (has bool, err error) {
if bytes.Equal(node.key, key) {
return true, nil
}
if node.isLeaf() {
return false, nil
}
if bytes.Compare(key, node.key) < 0 {
leftNode, err := node.getLeftNode(t)
if err != nil {
return false, err
}
return leftNode.has(t, key)
}
rightNode, err := node.getRightNode(t)
if err != nil {
return false, err
}
return rightNode.has(t, key)
}
// Get a key under the node.
//
// The index is the index in the list of leaf nodes sorted lexicographically by key. The leftmost leaf has index 0.
// It's neighbor has index 1 and so on.
func (node *Node) get(t *ImmutableTree, key []byte) (index int64, value []byte, err error) {
if node.isLeaf() {
switch bytes.Compare(node.key, key) {
case -1:
return 1, nil, nil
case 1:
return 0, nil, nil
default:
return 0, node.value, nil
}
}
if bytes.Compare(key, node.key) < 0 {
leftNode, err := node.getLeftNode(t)
if err != nil {
return 0, nil, err
}
return leftNode.get(t, key)
}
rightNode, err := node.getRightNode(t)
if err != nil {
return 0, nil, err
}
index, value, err = rightNode.get(t, key)
if err != nil {
return 0, nil, err
}
index += node.size - rightNode.size
return index, value, nil
}
func (node *Node) getByIndex(t *ImmutableTree, index int64) (key []byte, value []byte, err error) {
if node.isLeaf() {
if index == 0 {
return node.key, node.value, nil
}
return nil, nil, nil
}
// TODO: could improve this by storing the
// sizes as well as left/right hash.
leftNode, err := node.getLeftNode(t)
if err != nil {
return nil, nil, err
}
if index < leftNode.size {
return leftNode.getByIndex(t, index)
}
rightNode, err := node.getRightNode(t)
if err != nil {
return nil, nil, err
}
return rightNode.getByIndex(t, index-leftNode.size)
}
// Computes the hash of the node without computing its descendants. Must be
// called on nodes which have descendant node hashes already computed.
func (node *Node) _hash(version int64) []byte {
if node.hash != nil {
return node.hash
}
h := sha256.New()
if err := node.writeHashBytes(h, version); err != nil {
return nil
}
node.hash = h.Sum(nil)
return node.hash
}
// Hash the node and its descendants recursively. This usually mutates all
// descendant nodes. Returns the node hash and number of nodes hashed.
// If the tree is empty (i.e. the node is nil), returns the hash of an empty input,
// to conform with RFC-6962.
func (node *Node) hashWithCount(version int64) []byte {
if node == nil {
return sha256.New().Sum(nil)
}
if node.hash != nil {
return node.hash
}
h := sha256.New()
if err := node.writeHashBytesRecursively(h, version); err != nil {
// writeHashBytesRecursively doesn't return an error unless h.Write does,
// and hash.Hash.Write doesn't.
panic(err)
}
node.hash = h.Sum(nil)
return node.hash
}
// validate validates the node contents
func (node *Node) validate() error {
if node == nil {
return errors.New("node cannot be nil")
}
if node.key == nil {
return errors.New("key cannot be nil")
}
if node.nodeKey == nil {
return errors.New("nodeKey cannot be nil")
}
if node.nodeKey.version <= 0 {
return errors.New("version must be greater than 0")
}
if node.subtreeHeight < 0 {
return errors.New("height cannot be less than 0")
}
if node.size < 1 {
return errors.New("size must be at least 1")
}
if node.subtreeHeight == 0 {
// Leaf nodes
if node.value == nil {
return errors.New("value cannot be nil for leaf node")
}
if node.leftNodeKey != nil || node.leftNode != nil || node.rightNodeKey != nil || node.rightNode != nil {
return errors.New("leaf node cannot have children")
}
if node.size != 1 {
return errors.New("leaf nodes must have size 1")
}
} else if node.value != nil {
return errors.New("value must be nil for non-leaf node")
}
return nil
}
// Writes the node's hash to the given io.Writer. This function expects
// child hashes to be already set.
func (node *Node) writeHashBytes(w io.Writer, version int64) error {
err := encoding.EncodeVarint(w, int64(node.subtreeHeight))
if err != nil {
return fmt.Errorf("writing height, %w", err)
}
err = encoding.EncodeVarint(w, node.size)
if err != nil {
return fmt.Errorf("writing size, %w", err)
}
err = encoding.EncodeVarint(w, version)
if err != nil {
return fmt.Errorf("writing version, %w", err)
}
// Key is not written for inner nodes, unlike writeBytes.
if node.isLeaf() {
err = encoding.EncodeBytes(w, node.key)
if err != nil {
return fmt.Errorf("writing key, %w", err)
}
// Indirection needed to provide proofs without values.
// (e.g. ProofLeafNode.ValueHash)
valueHash := sha256.Sum256(node.value)
err = encoding.Encode32BytesHash(w, valueHash[:])
if err != nil {
return fmt.Errorf("writing value, %w", err)
}
} else {
if node.leftNode == nil || node.rightNode == nil {
return ErrEmptyChild
}
if err := encoding.Encode32BytesHash(w, node.leftNode.hash); err != nil {
return fmt.Errorf("writing left hash, %w", err)
}
if err := encoding.Encode32BytesHash(w, node.rightNode.hash); err != nil {
return fmt.Errorf("writing right hash, %w", err)
}
}
return nil
}
// writeHashBytesRecursively writes the node's hash to the given io.Writer.
// This function has the side-effect of calling hashWithCount.
// It only returns an error if w.Write fails.
func (node *Node) writeHashBytesRecursively(w io.Writer, version int64) error {
node.leftNode.hashWithCount(version)
node.rightNode.hashWithCount(version)
return node.writeHashBytes(w, version)
}
func (node *Node) encodedSize() int {
n := 1 +
encoding.EncodeVarintSize(node.size) +
encoding.EncodeBytesSize(node.key)
if node.isLeaf() {
n += encoding.EncodeBytesSize(node.value)
} else {
n += encoding.EncodeBytesSize(node.hash)
if node.leftNodeKey != nil {
nk := GetNodeKey(node.leftNodeKey)
n += encoding.EncodeVarintSize(nk.version) +
encoding.EncodeVarintSize(int64(nk.nonce))
}
if node.rightNodeKey != nil {
nk := GetNodeKey(node.rightNodeKey)
n += encoding.EncodeVarintSize(nk.version) +
encoding.EncodeVarintSize(int64(nk.nonce))
}
}
return n
}
// Writes the node as a serialized byte slice to the supplied io.Writer.
func (node *Node) writeBytes(w io.Writer) error {
if node == nil {
return errors.New("cannot write nil node")
}
err := encoding.EncodeVarint(w, int64(node.subtreeHeight))
if err != nil {
return fmt.Errorf("writing height, %w", err)
}
err = encoding.EncodeVarint(w, node.size)
if err != nil {
return fmt.Errorf("writing size, %w", err)
}
// Unlike writeHashBytes, key is written for inner nodes.
err = encoding.EncodeBytes(w, node.key)
if err != nil {
return fmt.Errorf("writing key, %w", err)
}
if node.isLeaf() {
err = encoding.EncodeBytes(w, node.value)
if err != nil {
return fmt.Errorf("writing value, %w", err)
}
} else {
err = encoding.EncodeBytes(w, node.hash)
if err != nil {
return fmt.Errorf("writing hash, %w", err)
}
mode := 0
if node.leftNodeKey == nil {
return ErrLeftNodeKeyEmpty
}
// check if children NodeKeys are legacy mode
if len(node.leftNodeKey) == hashSize {
mode += ModeLegacyLeftNode
}
if len(node.rightNodeKey) == hashSize {
mode += ModeLegacyRightNode
}
err = encoding.EncodeVarint(w, int64(mode))
if err != nil {
return fmt.Errorf("writing mode, %w", err)
}
if mode&ModeLegacyLeftNode != 0 { // legacy leftNodeKey
err = encoding.EncodeBytes(w, node.leftNodeKey)
if err != nil {
return fmt.Errorf("writing the legacy left node key, %w", err)
}
} else {
leftNodeKey := GetNodeKey(node.leftNodeKey)
err = encoding.EncodeVarint(w, leftNodeKey.version)
if err != nil {
return fmt.Errorf("writing the version of left node key, %w", err)
}
err = encoding.EncodeVarint(w, int64(leftNodeKey.nonce))
if err != nil {
return fmt.Errorf("writing the nonce of left node key, %w", err)
}
}
if node.rightNodeKey == nil {
return ErrRightNodeKeyEmpty
}
if mode&ModeLegacyRightNode != 0 { // legacy rightNodeKey
err = encoding.EncodeBytes(w, node.rightNodeKey)
if err != nil {
return fmt.Errorf("writing the legacy right node key, %w", err)
}
} else {
rightNodeKey := GetNodeKey(node.rightNodeKey)
err = encoding.EncodeVarint(w, rightNodeKey.version)
if err != nil {
return fmt.Errorf("writing the version of right node key, %w", err)
}
err = encoding.EncodeVarint(w, int64(rightNodeKey.nonce))
if err != nil {
return fmt.Errorf("writing the nonce of right node key, %w", err)
}
}
}
return nil
}
func (node *Node) getLeftNode(t *ImmutableTree) (*Node, error) {
if node.leftNode != nil {
return node.leftNode, nil
}
leftNode, err := t.ndb.GetNode(node.leftNodeKey)
if err != nil {
return nil, err
}
return leftNode, nil
}
func (node *Node) getRightNode(t *ImmutableTree) (*Node, error) {
if node.rightNode != nil {
return node.rightNode, nil
}
rightNode, err := t.ndb.GetNode(node.rightNodeKey)
if err != nil {
return nil, err
}
return rightNode, nil
}
// NOTE: mutates height and size
func (node *Node) calcHeightAndSize(t *ImmutableTree) error {
leftNode, err := node.getLeftNode(t)
if err != nil {
return err
}
rightNode, err := node.getRightNode(t)
if err != nil {
return err
}
node.subtreeHeight = maxInt8(leftNode.subtreeHeight, rightNode.subtreeHeight) + 1
node.size = leftNode.size + rightNode.size
return nil
}
func (node *Node) calcBalance(t *ImmutableTree) (int, error) {
leftNode, err := node.getLeftNode(t)
if err != nil {
return 0, err
}
rightNode, err := node.getRightNode(t)
if err != nil {
return 0, err
}
return int(leftNode.subtreeHeight) - int(rightNode.subtreeHeight), nil
}
// traverse is a wrapper over traverseInRange when we want the whole tree
func (node *Node) traverse(t *ImmutableTree, ascending bool, cb func(*Node) bool) bool {
return node.traverseInRange(t, nil, nil, ascending, false, false, func(node *Node) bool {
return cb(node)
})
}
// traversePost is a wrapper over traverseInRange when we want the whole tree post-order
func (node *Node) traversePost(t *ImmutableTree, ascending bool, cb func(*Node) bool) bool {
return node.traverseInRange(t, nil, nil, ascending, false, true, func(node *Node) bool {
return cb(node)
})
}
func (node *Node) traverseInRange(tree *ImmutableTree, start, end []byte, ascending bool, inclusive bool, post bool, cb func(*Node) bool) bool {
stop := false
t := node.newTraversal(tree, start, end, ascending, inclusive, post)
// TODO: figure out how to handle these errors
for node2, err := t.next(); node2 != nil && err == nil; node2, err = t.next() {
stop = cb(node2)
if stop {
return stop
}
}
return stop
}
var (
ErrCloneLeafNode = fmt.Errorf("attempt to copy a leaf node")
ErrEmptyChild = fmt.Errorf("found an empty child")
ErrLeftNodeKeyEmpty = fmt.Errorf("node.leftNodeKey was empty in writeBytes")
ErrRightNodeKeyEmpty = fmt.Errorf("node.rightNodeKey was empty in writeBytes")
ErrLeftHashIsNil = fmt.Errorf("node.leftHash was nil in writeBytes")
ErrRightHashIsNil = fmt.Errorf("node.rightHash was nil in writeBytes")
)
package iavl
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync"
"time"
"cosmossdk.io/log"
"github.com/cosmos/iavl/cache"
dbm "github.com/cosmos/iavl/db"
"github.com/cosmos/iavl/fastnode"
ibytes "github.com/cosmos/iavl/internal/bytes"
"github.com/cosmos/iavl/keyformat"
)
const (
int32Size = 4
int64Size = 8
hashSize = sha256.Size
genesisVersion = 1
storageVersionKey = "storage_version"
// We store latest saved version together with storage version delimited by the constant below.
// This delimiter is valid only if fast storage is enabled (i.e. storageVersion >= fastStorageVersionValue).
// The latest saved version is needed for protection against downgrade and re-upgrade. In such a case, it would
// be possible to observe mismatch between the latest version state and the fast nodes on disk.
// Therefore, we would like to detect that and overwrite fast nodes on disk with the latest version state.
fastStorageVersionDelimiter = "-"
// Using semantic versioning: https://semver.org/
defaultStorageVersionValue = "1.0.0"
fastStorageVersionValue = "1.1.0"
fastNodeCacheSize = 100000
)
var (
// All new node keys are prefixed with the byte 's'. This ensures no collision is
// possible with the legacy nodes, and makes them easier to traverse. They are indexed by the version and the local nonce.
nodeKeyFormat = keyformat.NewFastPrefixFormatter('s', int64Size+int32Size) // s<version><nonce>
// This is only used for the iteration purpose.
nodeKeyPrefixFormat = keyformat.NewFastPrefixFormatter('s', int64Size) // s<version>
// Key Format for making reads and iterates go through a data-locality preserving db.
// The value at an entry will list what version it was written to.
// Then to query values, you first query state via this fast method.
// If its present, then check the tree version. If tree version >= result_version,
// return result_version. Else, go through old (slow) IAVL get method that walks through tree.
fastKeyFormat = keyformat.NewKeyFormat('f', 0) // f<keystring>
// Key Format for storing metadata about the chain such as the version number.
// The value at an entry will be in a variable format and up to the caller to
// decide how to parse.
metadataKeyFormat = keyformat.NewKeyFormat('m', 0) // m<keystring>
// All legacy node keys are prefixed with the byte 'n'.
legacyNodeKeyFormat = keyformat.NewFastPrefixFormatter('n', hashSize) // n<hash>
// All legacy orphan keys are prefixed with the byte 'o'.
legacyOrphanKeyFormat = keyformat.NewKeyFormat('o', int64Size, int64Size, hashSize) // o<last-version><first-version><hash>
// All legacy root keys are prefixed with the byte 'r'.
legacyRootKeyFormat = keyformat.NewKeyFormat('r', int64Size) // r<version>
)
var errInvalidFastStorageVersion = fmt.Errorf("fast storage version must be in the format <storage version>%s<latest fast cache version>", fastStorageVersionDelimiter)
type nodeDB struct {
logger log.Logger
mtx sync.Mutex // Read/write lock.
db dbm.DB // Persistent node storage.
batch dbm.Batch // Batched writing buffer.
opts Options // Options to customize for pruning/writing
versionReaders map[int64]uint32 // Number of active version readers
storageVersion string // Storage version
firstVersion int64 // First version of nodeDB.
latestVersion int64 // Latest version of nodeDB.
pruneVersion int64 // Version to prune up to.
legacyLatestVersion int64 // Latest version of nodeDB in legacy format.
nodeCache cache.Cache // Cache for nodes in the regular tree that consists of key-value pairs at any version.
fastNodeCache cache.Cache // Cache for nodes in the fast index that represents only key-value pairs at the latest version.
isCommitting bool // Flag to indicate that the nodeDB is committing.
chCommitting chan struct{} // Channel to signal that the committing is done.
}
func newNodeDB(db dbm.DB, cacheSize int, opts Options, lg log.Logger) *nodeDB {
storeVersion, err := db.Get(metadataKeyFormat.Key([]byte(storageVersionKey)))
if err != nil || storeVersion == nil {
storeVersion = []byte(defaultStorageVersionValue)
}
ndb := &nodeDB{
logger: lg,
db: db,
batch: NewBatchWithFlusher(db, opts.FlushThreshold),
opts: opts,
firstVersion: 0,
latestVersion: 0, // initially invalid
legacyLatestVersion: 0,
pruneVersion: 0,
nodeCache: cache.New(cacheSize),
fastNodeCache: cache.New(fastNodeCacheSize),
versionReaders: make(map[int64]uint32, 8),
storageVersion: string(storeVersion),
chCommitting: make(chan struct{}, 1),
}
if opts.AsyncPruning {
go ndb.startPruning()
}
return ndb
}
// GetNode gets a node from memory or disk. If it is an inner node, it does not
// load its children.
// It is used for both formats of nodes: legacy and new.
// `legacy`: nk is the hash of the node. `new`: <version><nonce>.
func (ndb *nodeDB) GetNode(nk []byte) (*Node, error) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if nk == nil {
return nil, ErrNodeMissingNodeKey
}
// Check the cache.
if cachedNode := ndb.nodeCache.Get(nk); cachedNode != nil {
ndb.opts.Stat.IncCacheHitCnt()
return cachedNode.(*Node), nil
}
ndb.opts.Stat.IncCacheMissCnt()
// Doesn't exist, load.
isLegcyNode := len(nk) == hashSize
var nodeKey []byte
if isLegcyNode {
nodeKey = ndb.legacyNodeKey(nk)
} else {
nodeKey = ndb.nodeKey(nk)
}
buf, err := ndb.db.Get(nodeKey)
if err != nil {
return nil, fmt.Errorf("can't get node %v: %v", nk, err)
}
if buf == nil {
return nil, fmt.Errorf("Value missing for key %v corresponding to nodeKey %x", nk, nodeKey)
}
var node *Node
if isLegcyNode {
node, err = MakeLegacyNode(nk, buf)
if err != nil {
return nil, fmt.Errorf("error reading Legacy Node. bytes: %x, error: %v", buf, err)
}
} else {
node, err = MakeNode(nk, buf)
if err != nil {
return nil, fmt.Errorf("error reading Node. bytes: %x, error: %v", buf, err)
}
}
ndb.nodeCache.Add(node)
return node, nil
}
func (ndb *nodeDB) GetFastNode(key []byte) (*fastnode.Node, error) {
if !ndb.hasUpgradedToFastStorage() {
return nil, errors.New("storage version is not fast")
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if len(key) == 0 {
return nil, fmt.Errorf("nodeDB.GetFastNode() requires key, len(key) equals 0")
}
if cachedFastNode := ndb.fastNodeCache.Get(key); cachedFastNode != nil {
ndb.opts.Stat.IncFastCacheHitCnt()
return cachedFastNode.(*fastnode.Node), nil
}
ndb.opts.Stat.IncFastCacheMissCnt()
// Doesn't exist, load.
buf, err := ndb.db.Get(ndb.fastNodeKey(key))
if err != nil {
return nil, fmt.Errorf("can't get FastNode %X: %w", key, err)
}
if buf == nil {
return nil, nil
}
fastNode, err := fastnode.DeserializeNode(key, buf)
if err != nil {
return nil, fmt.Errorf("error reading FastNode. bytes: %x, error: %w", buf, err)
}
ndb.fastNodeCache.Add(fastNode)
return fastNode, nil
}
// SaveNode saves a node to disk.
func (ndb *nodeDB) SaveNode(node *Node) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if node.nodeKey == nil {
return ErrNodeMissingNodeKey
}
// Save node bytes to db.
var buf bytes.Buffer
buf.Grow(node.encodedSize())
if err := node.writeBytes(&buf); err != nil {
return err
}
if err := ndb.batch.Set(ndb.nodeKey(node.GetKey()), buf.Bytes()); err != nil {
return err
}
ndb.logger.Debug("BATCH SAVE", "node", node)
ndb.nodeCache.Add(node)
return nil
}
// SaveFastNode saves a FastNode to disk and add to cache.
func (ndb *nodeDB) SaveFastNode(node *fastnode.Node) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.saveFastNodeUnlocked(node, true)
}
// SaveFastNodeNoCache saves a FastNode to disk without adding to cache.
func (ndb *nodeDB) SaveFastNodeNoCache(node *fastnode.Node) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.saveFastNodeUnlocked(node, false)
}
// SetCommitting sets the committing flag to true.
// This is used to let the pruning process know that the nodeDB is committing.
func (ndb *nodeDB) SetCommitting() {
for len(ndb.chCommitting) > 0 {
<-ndb.chCommitting
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.isCommitting = true
}
// UnsetCommitting sets the committing flag to false.
// This is used to let the pruning process know that the nodeDB is done committing.
func (ndb *nodeDB) UnsetCommitting() {
ndb.mtx.Lock()
ndb.isCommitting = false
ndb.mtx.Unlock()
ndb.chCommitting <- struct{}{}
}
// IsCommitting returns true if the nodeDB is committing, false otherwise.
func (ndb *nodeDB) IsCommitting() bool {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.isCommitting
}
// SetFastStorageVersionToBatch sets storage version to fast where the version is
// 1.1.0-<version of the current live state>. Returns error if storage version is incorrect or on
// db error, nil otherwise. Requires changes to be committed after to be persisted.
func (ndb *nodeDB) SetFastStorageVersionToBatch(latestVersion int64) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
var newVersion string
if ndb.storageVersion >= fastStorageVersionValue {
// Storage version should be at index 0 and latest fast cache version at index 1
versions := strings.Split(ndb.storageVersion, fastStorageVersionDelimiter)
if len(versions) > 2 {
return errInvalidFastStorageVersion
}
newVersion = versions[0]
} else {
newVersion = fastStorageVersionValue
}
newVersion += fastStorageVersionDelimiter + strconv.Itoa(int(latestVersion))
if err := ndb.batch.Set(metadataKeyFormat.Key([]byte(storageVersionKey)), []byte(newVersion)); err != nil {
return err
}
ndb.storageVersion = newVersion
return nil
}
func (ndb *nodeDB) getStorageVersion() string {
return ndb.storageVersion
}
// Returns true if the upgrade to latest storage version has been performed, false otherwise.
func (ndb *nodeDB) hasUpgradedToFastStorage() bool {
return ndb.getStorageVersion() >= fastStorageVersionValue
}
// Returns true if the upgrade to fast storage has occurred but it does not match the live state, false otherwise.
// When the live state is not matched, we must force reupgrade.
// We determine this by checking the version of the live state and the version of the live state when
// latest storage was updated on disk the last time.
func (ndb *nodeDB) shouldForceFastStorageUpgrade() (bool, error) {
versions := strings.Split(ndb.storageVersion, fastStorageVersionDelimiter)
if len(versions) == 2 {
latestVersion, err := ndb.getLatestVersion()
if err != nil {
// TODO: should be true or false as default? (removed panic here)
return false, err
}
if versions[1] != strconv.Itoa(int(latestVersion)) {
return true, nil
}
}
return false, nil
}
// saveFastNodeUnlocked saves a FastNode to disk.
func (ndb *nodeDB) saveFastNodeUnlocked(node *fastnode.Node, shouldAddToCache bool) error {
if node.GetKey() == nil {
return fmt.Errorf("cannot have FastNode with a nil value for key")
}
// Save node bytes to db.
var buf bytes.Buffer
buf.Grow(node.EncodedSize())
if err := node.WriteBytes(&buf); err != nil {
return fmt.Errorf("error while writing fastnode bytes. Err: %w", err)
}
if err := ndb.batch.Set(ndb.fastNodeKey(node.GetKey()), buf.Bytes()); err != nil {
return fmt.Errorf("error while writing key/val to nodedb batch. Err: %w", err)
}
if shouldAddToCache {
ndb.fastNodeCache.Add(node)
}
return nil
}
// Has checks if a node key exists in the database.
func (ndb *nodeDB) Has(nk []byte) (bool, error) {
return ndb.db.Has(ndb.nodeKey(nk))
}
// deleteFromPruning deletes the orphan nodes from the pruning process.
func (ndb *nodeDB) deleteFromPruning(key []byte) error {
if ndb.IsCommitting() {
// if the nodeDB is committing, the pruning process will be done after the committing.
<-ndb.chCommitting
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.batch.Delete(key)
}
// saveNodeFromPruning saves the orphan nodes to the pruning process.
func (ndb *nodeDB) saveNodeFromPruning(node *Node) error {
if ndb.IsCommitting() {
// if the nodeDB is committing, the pruning process will be done after the committing.
<-ndb.chCommitting
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
// Save node bytes to db.
var buf bytes.Buffer
buf.Grow(node.encodedSize())
if err := node.writeBytes(&buf); err != nil {
return err
}
return ndb.batch.Set(ndb.nodeKey(node.GetKey()), buf.Bytes())
}
// deleteVersion deletes a tree version from disk.
// deletes orphans
func (ndb *nodeDB) deleteVersion(version int64) error {
rootKey, err := ndb.GetRoot(version)
if err != nil {
return err
}
if err := ndb.traverseOrphans(version, version+1, func(orphan *Node) error {
if orphan.nodeKey.nonce == 0 && !orphan.isLegacy {
// if the orphan is a reformatted root, it can be a legacy root
// so it should be removed from the pruning process.
if err := ndb.deleteFromPruning(ndb.legacyNodeKey(orphan.hash)); err != nil {
return err
}
}
if orphan.nodeKey.nonce == 1 && orphan.nodeKey.version < version {
// if the orphan is referred to the previous root, it should be reformatted
// to (version, 0), because the root (version, 1) should be removed but not
// applied now due to the batch writing.
orphan.nodeKey.nonce = 0
}
nk := orphan.GetKey()
if orphan.isLegacy {
return ndb.deleteFromPruning(ndb.legacyNodeKey(nk))
}
return ndb.deleteFromPruning(ndb.nodeKey(nk))
}); err != nil {
return err
}
literalRootKey := GetRootKey(version)
if rootKey == nil || !bytes.Equal(rootKey, literalRootKey) {
// if the root key is not matched with the literal root key, it means the given root
// is a reference root to the previous version.
if err := ndb.deleteFromPruning(ndb.nodeKey(literalRootKey)); err != nil {
return err
}
}
// check if the version is referred by the next version
nextRootKey, err := ndb.GetRoot(version + 1)
if err != nil {
return err
}
if bytes.Equal(literalRootKey, nextRootKey) {
root, err := ndb.GetNode(nextRootKey)
if err != nil {
return err
}
// ensure that the given version is not included in the root search
if err := ndb.deleteFromPruning(ndb.nodeKey(literalRootKey)); err != nil {
return err
}
// instead, the root should be reformatted to (version, 0)
root.nodeKey.nonce = 0
if err := ndb.saveNodeFromPruning(root); err != nil {
return err
}
}
return nil
}
// deleteLegacyNodes deletes all legacy nodes with the given version from disk.
// NOTE: This is only used for DeleteVersionsFrom.
func (ndb *nodeDB) deleteLegacyNodes(version int64, nk []byte) error {
node, err := ndb.GetNode(nk)
if err != nil {
return err
}
if node.nodeKey.version < version {
// it will skip the whole subtree.
return nil
}
if node.leftNodeKey != nil {
if err := ndb.deleteLegacyNodes(version, node.leftNodeKey); err != nil {
return err
}
}
if node.rightNodeKey != nil {
if err := ndb.deleteLegacyNodes(version, node.rightNodeKey); err != nil {
return err
}
}
return ndb.batch.Delete(ndb.legacyNodeKey(nk))
}
// deleteLegacyVersions deletes all legacy versions from disk.
func (ndb *nodeDB) deleteLegacyVersions(legacyLatestVersion int64) error {
// Delete the last version for the legacyLastVersion
if err := ndb.traverseOrphans(legacyLatestVersion, legacyLatestVersion+1, func(orphan *Node) error {
return ndb.deleteFromPruning(ndb.legacyNodeKey(orphan.hash))
}); err != nil {
return err
}
// Delete orphans for all legacy versions
if err := ndb.traversePrefix(legacyOrphanKeyFormat.Key(), func(key, value []byte) error {
if err := ndb.deleteFromPruning(key); err != nil {
return err
}
var fromVersion, toVersion int64
legacyOrphanKeyFormat.Scan(key, &toVersion, &fromVersion)
if (fromVersion <= legacyLatestVersion && toVersion < legacyLatestVersion) || fromVersion > legacyLatestVersion {
return ndb.deleteFromPruning(ndb.legacyNodeKey(value))
}
return nil
}); err != nil {
return err
}
// Delete all legacy roots
if err := ndb.traversePrefix(legacyRootKeyFormat.Key(), func(key, value []byte) error {
return ndb.deleteFromPruning(key)
}); err != nil {
return err
}
return nil
}
// DeleteVersionsFrom permanently deletes all tree versions from the given version upwards.
func (ndb *nodeDB) DeleteVersionsFrom(fromVersion int64) error {
latest, err := ndb.getLatestVersion()
if err != nil {
return err
}
if latest < fromVersion {
return nil
}
ndb.mtx.Lock()
for v, r := range ndb.versionReaders {
if v >= fromVersion && r != 0 {
ndb.mtx.Unlock() // Unlock before exiting
return fmt.Errorf("unable to delete version %v with %v active readers", v, r)
}
}
ndb.mtx.Unlock()
// Delete the legacy versions
legacyLatestVersion, err := ndb.getLegacyLatestVersion()
if err != nil {
return err
}
dumpFromVersion := fromVersion
if legacyLatestVersion >= fromVersion {
if err := ndb.traverseRange(legacyRootKeyFormat.Key(fromVersion), legacyRootKeyFormat.Key(legacyLatestVersion+1), func(k, v []byte) error {
var version int64
legacyRootKeyFormat.Scan(k, &version)
// delete the legacy nodes
if err := ndb.deleteLegacyNodes(version, v); err != nil {
return err
}
// it will skip the orphans because orphans will be removed at once in `deleteLegacyVersions`
// delete the legacy root
return ndb.batch.Delete(k)
}); err != nil {
return err
}
// Update the legacy latest version forcibly
ndb.legacyLatestVersion = 0
fromVersion = legacyLatestVersion + 1
}
// Delete the nodes for new format
err = ndb.traverseRange(nodeKeyPrefixFormat.KeyInt64(fromVersion), nodeKeyPrefixFormat.KeyInt64(latest+1), func(k, v []byte) error {
return ndb.batch.Delete(k)
})
if err != nil {
return err
}
// NOTICE: we don't touch fast node indexes here, because it'll be rebuilt later because of version mismatch.
ndb.resetLatestVersion(dumpFromVersion - 1)
return nil
}
// startPruning starts the pruning process.
func (ndb *nodeDB) startPruning() {
for {
ndb.mtx.Lock()
toVersion := ndb.pruneVersion
ndb.mtx.Unlock()
if toVersion == 0 {
time.Sleep(100 * time.Millisecond)
continue
}
if err := ndb.deleteVersionsTo(toVersion); err != nil {
ndb.logger.Error("Error while pruning", "err", err)
time.Sleep(1 * time.Second)
continue
}
ndb.mtx.Lock()
if ndb.pruneVersion <= toVersion {
ndb.pruneVersion = 0
}
ndb.mtx.Unlock()
}
}
// DeleteVersionsTo deletes the oldest versions up to the given version from disk.
func (ndb *nodeDB) DeleteVersionsTo(toVersion int64) error {
if !ndb.opts.AsyncPruning {
return ndb.deleteVersionsTo(toVersion)
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.pruneVersion = toVersion
return nil
}
func (ndb *nodeDB) deleteVersionsTo(toVersion int64) error {
legacyLatestVersion, err := ndb.getLegacyLatestVersion()
if err != nil {
return err
}
// If the legacy version is greater than the toVersion, we don't need to delete anything.
// It will delete the legacy versions at once.
if legacyLatestVersion > toVersion {
return nil
}
first, err := ndb.getFirstVersion()
if err != nil {
return err
}
latest, err := ndb.getLatestVersion()
if err != nil {
return err
}
if latest <= toVersion {
return fmt.Errorf("latest version %d is less than or equal to toVersion %d", latest, toVersion)
}
ndb.mtx.Lock()
for v, r := range ndb.versionReaders {
if v >= first && v <= toVersion && r != 0 {
ndb.mtx.Unlock()
return fmt.Errorf("unable to delete version %d with %d active readers", v, r)
}
}
ndb.mtx.Unlock()
// Delete the legacy versions
if legacyLatestVersion >= first {
if err := ndb.deleteLegacyVersions(legacyLatestVersion); err != nil {
ndb.logger.Error("Error deleting legacy versions", "err", err)
}
first = legacyLatestVersion + 1
// reset the legacy latest version forcibly to avoid multiple calls
ndb.resetLegacyLatestVersion(-1)
}
for version := first; version <= toVersion; version++ {
if err := ndb.deleteVersion(version); err != nil {
return err
}
ndb.resetFirstVersion(version + 1)
}
return nil
}
func (ndb *nodeDB) DeleteFastNode(key []byte) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if err := ndb.batch.Delete(ndb.fastNodeKey(key)); err != nil {
return err
}
ndb.fastNodeCache.Remove(key)
return nil
}
func (ndb *nodeDB) nodeKey(nk []byte) []byte {
return nodeKeyFormat.Key(nk)
}
func (ndb *nodeDB) fastNodeKey(key []byte) []byte {
return fastKeyFormat.KeyBytes(key)
}
func (ndb *nodeDB) legacyNodeKey(nk []byte) []byte {
return legacyNodeKeyFormat.Key(nk)
}
func (ndb *nodeDB) legacyRootKey(version int64) []byte {
return legacyRootKeyFormat.Key(version)
}
func (ndb *nodeDB) getFirstVersion() (int64, error) {
ndb.mtx.Lock()
firstVersion := ndb.firstVersion
ndb.mtx.Unlock()
if firstVersion > 0 {
return firstVersion, nil
}
// Check if we have a legacy version
itr, err := ndb.getPrefixIterator(legacyRootKeyFormat.Key())
if err != nil {
return 0, err
}
defer itr.Close()
if itr.Valid() {
var version int64
legacyRootKeyFormat.Scan(itr.Key(), &version)
return version, nil
}
// Find the first version
latestVersion, err := ndb.getLatestVersion()
if err != nil {
return 0, err
}
for firstVersion < latestVersion {
version := (latestVersion + firstVersion) >> 1
has, err := ndb.hasVersion(version)
if err != nil {
return 0, err
}
if has {
latestVersion = version
} else {
firstVersion = version + 1
}
}
ndb.resetFirstVersion(latestVersion)
return latestVersion, nil
}
func (ndb *nodeDB) resetFirstVersion(version int64) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.firstVersion = version
}
func (ndb *nodeDB) getLegacyLatestVersion() (int64, error) {
ndb.mtx.Lock()
latestVersion := ndb.legacyLatestVersion
ndb.mtx.Unlock()
if latestVersion != 0 {
return latestVersion, nil
}
itr, err := ndb.db.ReverseIterator(
legacyRootKeyFormat.Key(int64(1)),
legacyRootKeyFormat.Key(int64(math.MaxInt64)),
)
if err != nil {
return 0, err
}
defer itr.Close()
if itr.Valid() {
k := itr.Key()
var version int64
legacyRootKeyFormat.Scan(k, &version)
ndb.resetLegacyLatestVersion(version)
return version, nil
}
if err := itr.Error(); err != nil {
return 0, err
}
// If there are no legacy versions, set -1
ndb.resetLegacyLatestVersion(-1)
return -1, nil
}
func (ndb *nodeDB) resetLegacyLatestVersion(version int64) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.legacyLatestVersion = version
}
func (ndb *nodeDB) getLatestVersion() (int64, error) {
ndb.mtx.Lock()
latestVersion := ndb.latestVersion
ndb.mtx.Unlock()
if latestVersion > 0 {
return latestVersion, nil
}
itr, err := ndb.db.ReverseIterator(
nodeKeyPrefixFormat.KeyInt64(int64(1)),
nodeKeyPrefixFormat.KeyInt64(int64(math.MaxInt64)),
)
if err != nil {
return 0, err
}
defer itr.Close()
if itr.Valid() {
k := itr.Key()
var nk []byte
nodeKeyFormat.Scan(k, &nk)
latestVersion = GetNodeKey(nk).version
ndb.resetLatestVersion(latestVersion)
return latestVersion, nil
}
if err := itr.Error(); err != nil {
return 0, err
}
// If there are no versions, try to get the latest version from the legacy format.
latestVersion, err = ndb.getLegacyLatestVersion()
if err != nil {
return 0, err
}
if latestVersion > 0 {
ndb.resetLatestVersion(latestVersion)
return latestVersion, nil
}
return 0, nil
}
func (ndb *nodeDB) resetLatestVersion(version int64) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.latestVersion = version
}
// hasVersion checks if the given version exists.
func (ndb *nodeDB) hasVersion(version int64) (bool, error) {
return ndb.db.Has(nodeKeyFormat.Key(GetRootKey(version)))
}
// hasLegacyVersion checks if the given version exists in the legacy format.
func (ndb *nodeDB) hasLegacyVersion(version int64) (bool, error) {
return ndb.db.Has(ndb.legacyRootKey(version))
}
// GetRoot gets the nodeKey of the root for the specific version.
func (ndb *nodeDB) GetRoot(version int64) ([]byte, error) {
rootKey := GetRootKey(version)
val, err := ndb.db.Get(nodeKeyFormat.Key(rootKey))
if err != nil {
return nil, err
}
if val == nil {
// try the legacy root key
val, err := ndb.db.Get(ndb.legacyRootKey(version))
if err != nil {
return nil, err
}
if val == nil {
return nil, ErrVersionDoesNotExist
}
if len(val) == 0 { // empty root
return nil, nil
}
return val, nil
}
if len(val) == 0 { // empty root
return nil, nil
}
isRef, n := isReferenceRoot(val)
if isRef { // point to the prev version
switch n {
case nodeKeyFormat.Length(): // (prefix, version, 1)
nk := GetNodeKey(val[1:])
val, err = ndb.db.Get(nodeKeyFormat.Key(val[1:]))
if err != nil {
return nil, err
}
if val == nil { // the prev version does not exist
// check if the prev version root is reformatted due to the pruning
rnk := &NodeKey{version: nk.version, nonce: 0}
val, err = ndb.db.Get(nodeKeyFormat.Key(rnk.GetKey()))
if err != nil {
return nil, err
}
if val == nil {
return nil, ErrVersionDoesNotExist
}
return rnk.GetKey(), nil
}
return nk.GetKey(), nil
case nodeKeyPrefixFormat.Length(): // (prefix, version) before the lazy pruning
return append(val[1:], 0, 0, 0, 1), nil
default:
return nil, fmt.Errorf("invalid reference root: %x", val)
}
}
return rootKey, nil
}
// SaveEmptyRoot saves the empty root.
func (ndb *nodeDB) SaveEmptyRoot(version int64) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.batch.Set(nodeKeyFormat.Key(GetRootKey(version)), []byte{})
}
// SaveRoot saves the root when no updates.
func (ndb *nodeDB) SaveRoot(version int64, nk *NodeKey) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.batch.Set(nodeKeyFormat.Key(GetRootKey(version)), nodeKeyFormat.Key(nk.GetKey()))
}
// Traverse fast nodes and return error if any, nil otherwise
func (ndb *nodeDB) traverseFastNodes(fn func(k, v []byte) error) error {
return ndb.traversePrefix(fastKeyFormat.Key(), fn)
}
// Traverse all keys and return error if any, nil otherwise
func (ndb *nodeDB) traverse(fn func(key, value []byte) error) error {
return ndb.traverseRange(nil, nil, fn)
}
// Traverse all keys between a given range (excluding end) and return error if any, nil otherwise
func (ndb *nodeDB) traverseRange(start []byte, end []byte, fn func(k, v []byte) error) error {
itr, err := ndb.db.Iterator(start, end)
if err != nil {
return err
}
defer itr.Close()
for ; itr.Valid(); itr.Next() {
if err := fn(itr.Key(), itr.Value()); err != nil {
return err
}
}
return itr.Error()
}
// Traverse all keys with a certain prefix. Return error if any, nil otherwise
func (ndb *nodeDB) traversePrefix(prefix []byte, fn func(k, v []byte) error) error {
itr, err := ndb.getPrefixIterator(prefix)
if err != nil {
return err
}
defer itr.Close()
for ; itr.Valid(); itr.Next() {
if err := fn(itr.Key(), itr.Value()); err != nil {
return err
}
}
return nil
}
// Get the iterator for a given prefix.
func (ndb *nodeDB) getPrefixIterator(prefix []byte) (dbm.Iterator, error) {
var start, end []byte
if len(prefix) == 0 {
start = nil
end = nil
} else {
start = ibytes.Cp(prefix)
end = ibytes.CpIncr(prefix)
}
return ndb.db.Iterator(start, end)
}
// Get iterator for fast prefix and error, if any
func (ndb *nodeDB) getFastIterator(start, end []byte, ascending bool) (dbm.Iterator, error) {
var startFormatted, endFormatted []byte
if start != nil {
startFormatted = fastKeyFormat.KeyBytes(start)
} else {
startFormatted = fastKeyFormat.Key()
}
if end != nil {
endFormatted = fastKeyFormat.KeyBytes(end)
} else {
endFormatted = fastKeyFormat.Key()
endFormatted[0]++
}
if ascending {
return ndb.db.Iterator(startFormatted, endFormatted)
}
return ndb.db.ReverseIterator(startFormatted, endFormatted)
}
// Write to disk.
func (ndb *nodeDB) Commit() error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
var err error
if ndb.opts.Sync {
err = ndb.batch.WriteSync()
} else {
err = ndb.batch.Write()
}
if err != nil {
return fmt.Errorf("failed to write batch, %w", err)
}
return nil
}
func (ndb *nodeDB) incrVersionReaders(version int64) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.versionReaders[version]++
}
func (ndb *nodeDB) decrVersionReaders(version int64) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if ndb.versionReaders[version] > 0 {
ndb.versionReaders[version]--
}
if ndb.versionReaders[version] == 0 {
delete(ndb.versionReaders, version)
}
}
func isReferenceRoot(bz []byte) (bool, int) {
if bz[0] == nodeKeyFormat.Prefix()[0] {
return true, len(bz)
}
return false, 0
}
// traverseOrphans traverses orphans which removed by the updates of the curVersion in the prevVersion.
// NOTE: it is used for both legacy and new nodes.
func (ndb *nodeDB) traverseOrphans(prevVersion, curVersion int64, fn func(*Node) error) error {
curKey, err := ndb.GetRoot(curVersion)
if err != nil {
return err
}
curIter, err := NewNodeIterator(curKey, ndb)
if err != nil {
return err
}
prevKey, err := ndb.GetRoot(prevVersion)
if err != nil {
return err
}
prevIter, err := NewNodeIterator(prevKey, ndb)
if err != nil {
return err
}
var orgNode *Node
for prevIter.Valid() {
for orgNode == nil && curIter.Valid() {
node := curIter.GetNode()
if node.nodeKey.version <= prevVersion {
curIter.Next(true)
orgNode = node
} else {
curIter.Next(false)
}
}
pNode := prevIter.GetNode()
if orgNode != nil && bytes.Equal(pNode.hash, orgNode.hash) {
prevIter.Next(true)
orgNode = nil
} else {
err = fn(pNode)
if err != nil {
return err
}
prevIter.Next(false)
}
}
return nil
}
// Close the nodeDB.
func (ndb *nodeDB) Close() error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if ndb.batch != nil {
if err := ndb.batch.Close(); err != nil {
return err
}
ndb.batch = nil
}
// skip the db.Close() since it can be used by other trees
return nil
}
// Utility and test functions
func (ndb *nodeDB) leafNodes() ([]*Node, error) {
leaves := []*Node{}
err := ndb.traverseNodes(func(node *Node) error {
if node.isLeaf() {
leaves = append(leaves, node)
}
return nil
})
if err != nil {
return nil, err
}
return leaves, nil
}
func (ndb *nodeDB) nodes() ([]*Node, error) {
nodes := []*Node{}
err := ndb.traverseNodes(func(node *Node) error {
nodes = append(nodes, node)
return nil
})
if err != nil {
return nil, err
}
return nodes, nil
}
func (ndb *nodeDB) legacyNodes() ([]*Node, error) {
nodes := []*Node{}
err := ndb.traversePrefix(legacyNodeKeyFormat.Prefix(), func(key, value []byte) error {
node, err := MakeLegacyNode(key[1:], value)
if err != nil {
return err
}
nodes = append(nodes, node)
return nil
})
if err != nil {
return nil, err
}
return nodes, nil
}
func (ndb *nodeDB) orphans() ([][]byte, error) {
orphans := [][]byte{}
for version := ndb.firstVersion; version < ndb.latestVersion; version++ {
err := ndb.traverseOrphans(version, version+1, func(orphan *Node) error {
orphans = append(orphans, orphan.hash)
return nil
})
if err != nil {
return nil, err
}
}
return orphans, nil
}
// Not efficient.
// NOTE: DB cannot implement Size() because
// mutations are not always synchronous.
//
func (ndb *nodeDB) size() int {
size := 0
err := ndb.traverse(func(k, v []byte) error {
size++
return nil
})
if err != nil {
return -1
}
return size
}
func (ndb *nodeDB) traverseNodes(fn func(node *Node) error) error {
nodes := []*Node{}
if err := ndb.traversePrefix(nodeKeyFormat.Prefix(), func(key, value []byte) error {
if isRef, _ := isReferenceRoot(value); isRef {
return nil
}
node, err := MakeNode(key[1:], value)
if err != nil {
return err
}
nodes = append(nodes, node)
return nil
}); err != nil {
return err
}
sort.Slice(nodes, func(i, j int) bool {
return bytes.Compare(nodes[i].key, nodes[j].key) < 0
})
for _, n := range nodes {
if err := fn(n); err != nil {
return err
}
}
return nil
}
// traverseStateChanges iterate the range of versions, compare each version to it's predecessor to extract the state changes of it.
// endVersion is exclusive, set to `math.MaxInt64` to cover the latest version.
func (ndb *nodeDB) traverseStateChanges(startVersion, endVersion int64, fn func(version int64, changeSet *ChangeSet) error) error {
firstVersion, err := ndb.getFirstVersion()
if err != nil {
return err
}
if startVersion < firstVersion {
startVersion = firstVersion
}
latestVersion, err := ndb.getLatestVersion()
if err != nil {
return err
}
if endVersion > latestVersion {
endVersion = latestVersion
}
prevVersion := startVersion - 1
prevRoot, err := ndb.GetRoot(prevVersion)
if err != nil && err != ErrVersionDoesNotExist {
return err
}
for version := startVersion; version <= endVersion; version++ {
root, err := ndb.GetRoot(version)
if err != nil {
return err
}
var changeSet ChangeSet
receiveKVPair := func(pair *KVPair) error {
changeSet.Pairs = append(changeSet.Pairs, pair)
return nil
}
if err := ndb.extractStateChanges(prevVersion, prevRoot, root, receiveKVPair); err != nil {
return err
}
if err := fn(version, &changeSet); err != nil {
return err
}
prevVersion = version
prevRoot = root
}
return nil
}
func (ndb *nodeDB) String() (string, error) {
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
buf.Reset()
index := 0
err := ndb.traversePrefix(nodeKeyFormat.Prefix(), func(key, value []byte) error {
fmt.Fprintf(buf, "%s: %x\n", key, value)
return nil
})
if err != nil {
return "", err
}
buf.WriteByte('\n')
err = ndb.traverseNodes(func(node *Node) error {
switch {
case node == nil:
fmt.Fprintf(buf, "%s: <nil>\n", nodeKeyFormat.Prefix())
case node.value == nil && node.subtreeHeight > 0:
fmt.Fprintf(buf, "%s: %s %-16s h=%d nodeKey=%v\n",
nodeKeyFormat.Prefix(), node.key, "", node.subtreeHeight, node.nodeKey)
default:
fmt.Fprintf(buf, "%s: %s = %-16s h=%d nodeKey=%v\n",
nodeKeyFormat.Prefix(), node.key, node.value, node.subtreeHeight, node.nodeKey)
}
index++
return nil
})
if err != nil {
return "", err
}
return "-" + "\n" + buf.String() + "-", nil
}
var ErrNodeMissingNodeKey = fmt.Errorf("node does not have a nodeKey")