package math
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"testing"
)
// LegacyDec NOTE: never use new(Dec) or else we will panic unmarshalling into the
// nil embedded big.Int
type LegacyDec struct {
i *big.Int
}
const (
// LegacyPrecision number of decimal places
LegacyPrecision = 18
// LegacyDecimalPrecisionBits bits required to represent the above precision
// Ceiling[Log2[10^Precision - 1]]
LegacyDecimalPrecisionBits = 60
// decimalTruncateBits is the minimum number of bits removed
// by a truncate operation. It is equal to
// Floor[Log2[10^Precision - 1]].
decimalTruncateBits = LegacyDecimalPrecisionBits - 1
maxDecBitLen = MaxBitLen + decimalTruncateBits
// maxApproxRootIterations max number of iterations in ApproxRoot function
maxApproxRootIterations = 300
)
var (
precisionReuse = new(big.Int).Exp(big.NewInt(10), big.NewInt(LegacyPrecision), nil)
fivePrecision = new(big.Int).Quo(precisionReuse, big.NewInt(2))
precisionMultipliers []*big.Int
zeroInt = big.NewInt(0)
oneInt = big.NewInt(1)
tenInt = big.NewInt(10)
smallestDec = LegacySmallestDec()
)
// Decimal errors
var (
ErrLegacyEmptyDecimalStr = errors.New("decimal string cannot be empty")
ErrLegacyInvalidDecimalLength = errors.New("invalid decimal length")
ErrLegacyInvalidDecimalStr = errors.New("invalid decimal string")
)
// Set precision multipliers
func init() {
precisionMultipliers = make([]*big.Int, LegacyPrecision+1)
for i := 0; i <= LegacyPrecision; i++ {
precisionMultipliers[i] = calcPrecisionMultiplier(int64(i))
}
}
func precisionInt() *big.Int {
return new(big.Int).Set(precisionReuse)
}
func LegacyZeroDec() LegacyDec { return LegacyDec{new(big.Int).Set(zeroInt)} }
func LegacyOneDec() LegacyDec { return LegacyDec{precisionInt()} }
func LegacySmallestDec() LegacyDec { return LegacyDec{new(big.Int).Set(oneInt)} }
// calculate the precision multiplier
func calcPrecisionMultiplier(prec int64) *big.Int {
if prec < 0 {
panic(fmt.Sprintf("negative precision %v", prec))
}
if prec > LegacyPrecision {
panic(fmt.Sprintf("too much precision, maximum %v, provided %v", LegacyPrecision, prec))
}
zerosToAdd := LegacyPrecision - prec
multiplier := new(big.Int).Exp(tenInt, big.NewInt(zerosToAdd), nil)
return multiplier
}
// get the precision multiplier, do not mutate result
func precisionMultiplier(prec int64) *big.Int {
if prec < 0 {
panic(fmt.Sprintf("negative precision %v", prec))
}
if prec > LegacyPrecision {
panic(fmt.Sprintf("too much precision, maximum %v, provided %v", LegacyPrecision, prec))
}
return precisionMultipliers[prec]
}
// LegacyNewDec create a new Dec from integer assuming whole number
func LegacyNewDec(i int64) LegacyDec {
return LegacyNewDecWithPrec(i, 0)
}
// LegacyNewDecWithPrec create a new Dec from integer with decimal place at prec
// CONTRACT: prec <= Precision
func LegacyNewDecWithPrec(i, prec int64) LegacyDec {
bi := big.NewInt(i)
return LegacyDec{
bi.Mul(bi, precisionMultiplier(prec)),
}
}
// LegacyNewDecFromBigInt create a new Dec from big integer assuming whole numbers
// CONTRACT: prec <= Precision
func LegacyNewDecFromBigInt(i *big.Int) LegacyDec {
return LegacyNewDecFromBigIntWithPrec(i, 0)
}
// LegacyNewDecFromBigIntWithPrec create a new Dec from big integer assuming whole numbers
// CONTRACT: prec <= Precision
func LegacyNewDecFromBigIntWithPrec(i *big.Int, prec int64) LegacyDec {
return LegacyDec{
new(big.Int).Mul(i, precisionMultiplier(prec)),
}
}
// LegacyNewDecFromInt create a new Dec from big integer assuming whole numbers
// CONTRACT: prec <= Precision
func LegacyNewDecFromInt(i Int) LegacyDec {
return LegacyNewDecFromIntWithPrec(i, 0)
}
// LegacyNewDecFromIntWithPrec create a new Dec from big integer with decimal place at prec
// CONTRACT: prec <= Precision
func LegacyNewDecFromIntWithPrec(i Int, prec int64) LegacyDec {
return LegacyDec{
new(big.Int).Mul(i.BigIntMut(), precisionMultiplier(prec)),
}
}
// LegacyNewDecFromStr create a decimal from an input decimal string.
// valid must come in the form:
//
// (-) whole integers (.) decimal integers
//
// examples of acceptable input include:
//
// -123.456
// 456.7890
// 345
// -456789
//
// NOTE - An error will return if more decimal places
// are provided in the string than the constant Precision.
//
// CONTRACT - This function does not mutate the input str.
func LegacyNewDecFromStr(str string) (LegacyDec, error) {
// first extract any negative symbol
neg := false
if len(str) > 0 && str[0] == '-' {
neg = true
str = str[1:]
}
if len(str) == 0 {
return LegacyDec{}, ErrLegacyEmptyDecimalStr
}
strs := strings.Split(str, ".")
lenDecs := 0
combinedStr := strs[0]
if len(strs) == 2 { // has a decimal place
lenDecs = len(strs[1])
if lenDecs == 0 || len(combinedStr) == 0 {
return LegacyDec{}, ErrLegacyInvalidDecimalLength
}
combinedStr += strs[1]
} else if len(strs) > 2 {
return LegacyDec{}, ErrLegacyInvalidDecimalStr
}
if lenDecs > LegacyPrecision {
return LegacyDec{}, fmt.Errorf("value '%s' exceeds max precision by %d decimal places: max precision %d", str, LegacyPrecision-lenDecs, LegacyPrecision)
}
// add some extra zero's to correct to the Precision factor
zerosToAdd := LegacyPrecision - lenDecs
zeros := strings.Repeat("0", zerosToAdd)
combinedStr += zeros
combined, ok := new(big.Int).SetString(combinedStr, 10) // base 10
if !ok {
return LegacyDec{}, fmt.Errorf("failed to set decimal string with base 10: %s", combinedStr)
}
if combined.BitLen() > maxDecBitLen {
return LegacyDec{}, fmt.Errorf("decimal '%s' out of range; bitLen: got %d, max %d", str, combined.BitLen(), maxDecBitLen)
}
if neg {
combined = new(big.Int).Neg(combined)
}
return LegacyDec{combined}, nil
}
// LegacyMustNewDecFromStr Decimal from string, panic on error
func LegacyMustNewDecFromStr(s string) LegacyDec {
dec, err := LegacyNewDecFromStr(s)
if err != nil {
panic(err)
}
return dec
}
func (d LegacyDec) IsNil() bool { return d.i == nil } // is decimal nil
func (d LegacyDec) IsZero() bool { return (d.i).Sign() == 0 } // is equal to zero
func (d LegacyDec) IsNegative() bool { return (d.i).Sign() == -1 } // is negative
func (d LegacyDec) IsPositive() bool { return (d.i).Sign() == 1 } // is positive
func (d LegacyDec) Equal(d2 LegacyDec) bool { return (d.i).Cmp(d2.i) == 0 } // equal decimals
func (d LegacyDec) GT(d2 LegacyDec) bool { return (d.i).Cmp(d2.i) > 0 } // greater than
func (d LegacyDec) GTE(d2 LegacyDec) bool { return (d.i).Cmp(d2.i) >= 0 } // greater than or equal
func (d LegacyDec) LT(d2 LegacyDec) bool { return (d.i).Cmp(d2.i) < 0 } // less than
func (d LegacyDec) LTE(d2 LegacyDec) bool { return (d.i).Cmp(d2.i) <= 0 } // less than or equal
func (d LegacyDec) Neg() LegacyDec { return LegacyDec{new(big.Int).Neg(d.i)} } // reverse the decimal sign
func (d LegacyDec) NegMut() LegacyDec { d.i.Neg(d.i); return d } // reverse the decimal sign, mutable
func (d LegacyDec) Abs() LegacyDec { return LegacyDec{new(big.Int).Abs(d.i)} } // absolute value
func (d LegacyDec) AbsMut() LegacyDec { d.i.Abs(d.i); return d } // absolute value, mutable
func (d LegacyDec) Set(d2 LegacyDec) LegacyDec { d.i.Set(d2.i); return d } // set to existing dec value
func (d LegacyDec) Clone() LegacyDec { return LegacyDec{new(big.Int).Set(d.i)} } // clone new dec
// BigInt returns a copy of the underlying big.Int.
func (d LegacyDec) BigInt() *big.Int {
if d.IsNil() {
return nil
}
cp := new(big.Int)
return cp.Set(d.i)
}
// BigIntMut converts LegacyDec to big.Int, mutative the input
func (d LegacyDec) BigIntMut() *big.Int {
if d.IsNil() {
return nil
}
return d.i
}
func (d LegacyDec) ImmutOp(op func(LegacyDec, LegacyDec) LegacyDec, d2 LegacyDec) LegacyDec {
return op(d.Clone(), d2)
}
func (d LegacyDec) ImmutOpInt(op func(LegacyDec, Int) LegacyDec, d2 Int) LegacyDec {
return op(d.Clone(), d2)
}
func (d LegacyDec) ImmutOpInt64(op func(LegacyDec, int64) LegacyDec, d2 int64) LegacyDec {
// TODO: use already allocated operand bigint to avoid
// newint each time, add mutex for race condition
// Issue: https://github.com/cosmos/cosmos-sdk/issues/11166
return op(d.Clone(), d2)
}
func (d LegacyDec) SetInt64(i int64) LegacyDec {
d.i.SetInt64(i)
d.i.Mul(d.i, precisionReuse)
return d
}
// Add addition
func (d LegacyDec) Add(d2 LegacyDec) LegacyDec {
return d.ImmutOp(LegacyDec.AddMut, d2)
}
// AddMut mutable addition
func (d LegacyDec) AddMut(d2 LegacyDec) LegacyDec {
d.i.Add(d.i, d2.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// Sub subtraction
func (d LegacyDec) Sub(d2 LegacyDec) LegacyDec {
return d.ImmutOp(LegacyDec.SubMut, d2)
}
// SubMut mutable subtraction
func (d LegacyDec) SubMut(d2 LegacyDec) LegacyDec {
d.i.Sub(d.i, d2.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// Mul multiplication
func (d LegacyDec) Mul(d2 LegacyDec) LegacyDec {
return d.ImmutOp(LegacyDec.MulMut, d2)
}
// MulMut mutable multiplication
func (d LegacyDec) MulMut(d2 LegacyDec) LegacyDec {
d.i.Mul(d.i, d2.i)
chopped := chopPrecisionAndRound(d.i)
if chopped.BitLen() > maxDecBitLen {
panic("Int overflow")
}
*d.i = *chopped
return d
}
// MulTruncate multiplication truncate
func (d LegacyDec) MulTruncate(d2 LegacyDec) LegacyDec {
return d.ImmutOp(LegacyDec.MulTruncateMut, d2)
}
// MulTruncateMut mutable multiplication truncate
func (d LegacyDec) MulTruncateMut(d2 LegacyDec) LegacyDec {
d.i.Mul(d.i, d2.i)
chopPrecisionAndTruncate(d.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// MulRoundUp multiplication round up at precision end.
func (d LegacyDec) MulRoundUp(d2 LegacyDec) LegacyDec {
return d.ImmutOp(LegacyDec.MulRoundUpMut, d2)
}
// MulRoundUpMut mutable multiplication with round up at precision end.
func (d LegacyDec) MulRoundUpMut(d2 LegacyDec) LegacyDec {
d.i.Mul(d.i, d2.i)
chopPrecisionAndRoundUp(d.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// MulInt multiplication
func (d LegacyDec) MulInt(i Int) LegacyDec {
return d.ImmutOpInt(LegacyDec.MulIntMut, i)
}
func (d LegacyDec) MulIntMut(i Int) LegacyDec {
d.i.Mul(d.i, i.BigIntMut())
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// MulInt64 multiplication with int64
func (d LegacyDec) MulInt64(i int64) LegacyDec {
return d.ImmutOpInt64(LegacyDec.MulInt64Mut, i)
}
func (d LegacyDec) MulInt64Mut(i int64) LegacyDec {
d.i.Mul(d.i, big.NewInt(i))
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// Quo quotient
func (d LegacyDec) Quo(d2 LegacyDec) LegacyDec {
return d.ImmutOp(LegacyDec.QuoMut, d2)
}
var squaredPrecisionReuse = new(big.Int).Mul(precisionReuse, precisionReuse)
// QuoMut mutable quotient
func (d LegacyDec) QuoMut(d2 LegacyDec) LegacyDec {
// multiply by precision twice
d.i.Mul(d.i, squaredPrecisionReuse)
d.i.Quo(d.i, d2.i)
chopPrecisionAndRound(d.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// QuoTruncate quotient truncate
func (d LegacyDec) QuoTruncate(d2 LegacyDec) LegacyDec {
return d.ImmutOp(LegacyDec.QuoTruncateMut, d2)
}
// QuoTruncateMut divides the current LegacyDec value by the provided LegacyDec value, truncating the result.
func (d LegacyDec) QuoTruncateMut(d2 LegacyDec) LegacyDec {
// multiply precision once before performing division
d.i.Mul(d.i, precisionReuse)
d.i.Quo(d.i, d2.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// QuoRoundUp quotient, round up
func (d LegacyDec) QuoRoundUp(d2 LegacyDec) LegacyDec {
return d.ImmutOp(LegacyDec.QuoRoundupMut, d2)
}
// QuoRoundupMut mutable quotient, round up
func (d LegacyDec) QuoRoundupMut(d2 LegacyDec) LegacyDec {
// multiply precision twice
d.i.Mul(d.i, precisionReuse)
_, rem := d.i.QuoRem(d.i, d2.i, big.NewInt(0))
if rem.Sign() > 0 && d.IsNegative() == d2.IsNegative() ||
rem.Sign() < 0 && d.IsNegative() != d2.IsNegative() {
d.i.Add(d.i, oneInt)
}
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// QuoInt quotient
func (d LegacyDec) QuoInt(i Int) LegacyDec {
return d.ImmutOpInt(LegacyDec.QuoIntMut, i)
}
func (d LegacyDec) QuoIntMut(i Int) LegacyDec {
d.i.Quo(d.i, i.BigIntMut())
return d
}
// QuoInt64 quotient with int64
func (d LegacyDec) QuoInt64(i int64) LegacyDec {
return d.ImmutOpInt64(LegacyDec.QuoInt64Mut, i)
}
func (d LegacyDec) QuoInt64Mut(i int64) LegacyDec {
d.i.Quo(d.i, big.NewInt(i))
return d
}
// ApproxRoot returns an approximate estimation of a Dec's positive real nth root
// using Newton's method (where n is positive). The algorithm starts with some guess and
// computes the sequence of improved guesses until an answer converges to an
// approximate answer. It returns `|d|.ApproxRoot() * -1` if input is negative.
// A maximum number of 100 iterations is used a backup boundary condition for
// cases where the answer never converges enough to satisfy the main condition.
func (d LegacyDec) ApproxRoot(root uint64) (guess LegacyDec, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = errors.New("out of bounds")
}
}
}()
if d.IsNegative() {
absRoot, err := d.Neg().ApproxRoot(root)
return absRoot.NegMut(), err
}
// One decimal, that we invalidate later. Helps us save a heap allocation.
scratchOneDec := LegacyOneDec()
if root == 1 || d.IsZero() || d.Equal(scratchOneDec) {
return d, nil
}
if root == 0 {
return scratchOneDec, nil
}
guess, delta := scratchOneDec, LegacyOneDec()
for iter := 0; iter < maxApproxRootIterations && delta.Abs().GT(smallestDec); iter++ {
prev := guess.Power(root - 1)
if prev.IsZero() {
prev = smallestDec
}
delta.Set(d).QuoMut(prev)
delta.SubMut(guess)
delta.QuoInt64Mut(int64(root))
guess.AddMut(delta)
}
return guess, nil
}
// Power returns the result of raising to a positive integer power
func (d LegacyDec) Power(power uint64) LegacyDec {
res := LegacyDec{new(big.Int).Set(d.i)}
return res.PowerMut(power)
}
func (d LegacyDec) PowerMut(power uint64) LegacyDec {
if power == 0 {
// Set to 1 with the correct precision.
d.i.Set(precisionReuse)
return d
}
tmp := LegacyOneDec()
for i := power; i > 1; {
if i%2 != 0 {
tmp.MulMut(d)
}
i /= 2
d.MulMut(d)
}
return d.MulMut(tmp)
}
// ApproxSqrt is a wrapper around ApproxRoot for the common special case
// of finding the square root of a number. It returns -(sqrt(abs(d)) if input is negative.
func (d LegacyDec) ApproxSqrt() (LegacyDec, error) {
return d.ApproxRoot(2)
}
// IsInteger is integer, e.g. decimals are zero
func (d LegacyDec) IsInteger() bool {
return new(big.Int).Rem(d.i, precisionReuse).Sign() == 0
}
// Format format decimal state
func (d LegacyDec) Format(s fmt.State, verb rune) {
_, err := s.Write([]byte(d.String()))
if err != nil {
panic(err)
}
}
func (d LegacyDec) String() string {
if d.i == nil {
return d.i.String()
}
isNeg := d.IsNegative()
if isNeg {
d = d.Neg()
}
bzInt, err := d.i.MarshalText()
if err != nil {
return ""
}
inputSize := len(bzInt)
var bzStr []byte
// TODO: Remove trailing zeros
// case 1, purely decimal
if inputSize <= LegacyPrecision {
bzStr = make([]byte, LegacyPrecision+2)
// 0. prefix
bzStr[0] = byte('0')
bzStr[1] = byte('.')
// set relevant digits to 0
for i := 0; i < LegacyPrecision-inputSize; i++ {
bzStr[i+2] = byte('0')
}
// set final digits
copy(bzStr[2+(LegacyPrecision-inputSize):], bzInt)
} else {
// inputSize + 1 to account for the decimal point that is being added
bzStr = make([]byte, inputSize+1)
decPointPlace := inputSize - LegacyPrecision
copy(bzStr, bzInt[:decPointPlace]) // pre-decimal digits
bzStr[decPointPlace] = byte('.') // decimal point
copy(bzStr[decPointPlace+1:], bzInt[decPointPlace:]) // post-decimal digits
}
if isNeg {
return "-" + string(bzStr)
}
return string(bzStr)
}
// Float64 returns the float64 representation of a Dec.
// Will return the error if the conversion failed.
func (d LegacyDec) Float64() (float64, error) {
return strconv.ParseFloat(d.String(), 64)
}
// MustFloat64 returns the float64 representation of a Dec.
// Would panic if the conversion failed.
func (d LegacyDec) MustFloat64() float64 {
if value, err := strconv.ParseFloat(d.String(), 64); err != nil {
panic(err)
} else {
return value
}
}
// ____
// __| |__ "chop 'em
// ` \ round!"
// ___|| ~ _ -bankers
// | | __
// | | | __|__|__
// |_____: / | $$$ |
// |________|
// Remove a Precision amount of rightmost digits and perform bankers rounding
// on the remainder (gaussian rounding) on the digits which have been removed.
//
// Mutates the input. Use the non-mutative version if that is undesired
func chopPrecisionAndRound(d *big.Int) *big.Int {
// remove the negative and add it back when returning
if d.Sign() == -1 {
// make d positive, compute chopped value, and then un-mutate d
d = d.Neg(d)
d = chopPrecisionAndRound(d)
d = d.Neg(d)
return d
}
// get the truncated quotient and remainder
quo, rem := d, big.NewInt(0)
quo, rem = quo.QuoRem(d, precisionReuse, rem)
if rem.Sign() == 0 { // remainder is zero
return quo
}
switch rem.Cmp(fivePrecision) {
case -1:
return quo
case 1:
return quo.Add(quo, oneInt)
default: // bankers rounding must take place
// always round to an even number
if quo.Bit(0) == 0 {
return quo
}
return quo.Add(quo, oneInt)
}
}
func chopPrecisionAndRoundUp(d *big.Int) *big.Int {
// remove the negative and add it back when returning
if d.Sign() == -1 {
// make d positive, compute chopped value, and then un-mutate d
d = d.Neg(d)
// truncate since d is negative...
chopPrecisionAndTruncate(d)
d = d.Neg(d)
return d
}
// get the truncated quotient and remainder
quo, rem := d, big.NewInt(0)
quo, rem = quo.QuoRem(d, precisionReuse, rem)
if rem.Sign() == 0 { // remainder is zero
return quo
}
return quo.Add(quo, oneInt)
}
func chopPrecisionAndRoundNonMutative(d *big.Int) *big.Int {
tmp := new(big.Int).Set(d)
return chopPrecisionAndRound(tmp)
}
// RoundInt64 rounds the decimal using bankers rounding
func (d LegacyDec) RoundInt64() int64 {
chopped := chopPrecisionAndRoundNonMutative(d.i)
if !chopped.IsInt64() {
panic("Int64() out of bound")
}
return chopped.Int64()
}
// RoundInt round the decimal using bankers rounding
func (d LegacyDec) RoundInt() Int {
return NewIntFromBigIntMut(chopPrecisionAndRoundNonMutative(d.i))
}
// chopPrecisionAndTruncate is similar to chopPrecisionAndRound,
// but always rounds down. It does not mutate the input.
func chopPrecisionAndTruncate(d *big.Int) {
d.Quo(d, precisionReuse)
}
func chopPrecisionAndTruncateNonMutative(d *big.Int) *big.Int {
tmp := new(big.Int).Set(d)
chopPrecisionAndTruncate(tmp)
return tmp
}
// TruncateInt64 truncates the decimals from the number and returns an int64
func (d LegacyDec) TruncateInt64() int64 {
chopped := chopPrecisionAndTruncateNonMutative(d.i)
if !chopped.IsInt64() {
panic("Int64() out of bound")
}
return chopped.Int64()
}
// TruncateInt truncates the decimals from the number and returns an Int
func (d LegacyDec) TruncateInt() Int {
return NewIntFromBigIntMut(chopPrecisionAndTruncateNonMutative(d.i))
}
// TruncateDec truncates the decimals from the number and returns a Dec
func (d LegacyDec) TruncateDec() LegacyDec {
return LegacyNewDecFromBigInt(chopPrecisionAndTruncateNonMutative(d.i))
}
// Ceil returns the smallest integer value (as a decimal) that is greater than
// or equal to the given decimal.
func (d LegacyDec) Ceil() LegacyDec {
tmp := new(big.Int).Set(d.i)
quo, rem := tmp, big.NewInt(0)
quo, rem = quo.QuoRem(tmp, precisionReuse, rem)
// no need to round with a zero remainder regardless of sign
if rem.Sign() == 0 {
return LegacyNewDecFromBigInt(quo)
} else if rem.Sign() == -1 {
return LegacyNewDecFromBigInt(quo)
}
if d.i.BitLen() >= maxDecBitLen {
panic("Int overflow")
}
return LegacyNewDecFromBigInt(quo.Add(quo, oneInt))
}
// LegacyMaxSortableDec is the largest Dec that can be passed into SortableDecBytes()
// Its negative form is the least Dec that can be passed in.
var LegacyMaxSortableDec LegacyDec
func init() {
LegacyMaxSortableDec = LegacyOneDec().Quo(LegacySmallestDec())
}
// LegacyValidSortableDec ensures that a Dec is within the sortable bounds,
// a Dec can't have a precision of less than 10^-18.
// Max sortable decimal was set to the reciprocal of SmallestDec.
func LegacyValidSortableDec(dec LegacyDec) bool {
return dec.Abs().LTE(LegacyMaxSortableDec)
}
// LegacySortableDecBytes returns a byte slice representation of a Dec that can be sorted.
// Left and right pads with 0s so there are 18 digits to left and right of the decimal point.
// For this reason, there is a maximum and minimum value for this, enforced by ValidSortableDec.
func LegacySortableDecBytes(dec LegacyDec) []byte {
if !LegacyValidSortableDec(dec) {
panic("dec must be within bounds")
}
// Instead of adding an extra byte to all sortable decs in order to handle max sortable, we just
// makes its bytes be "max" which comes after all numbers in ASCIIbetical order
if dec.Equal(LegacyMaxSortableDec) {
return []byte("max")
}
// For the same reason, we make the bytes of minimum sortable dec be --, which comes before all numbers.
if dec.Equal(LegacyMaxSortableDec.Neg()) {
return []byte("--")
}
// We move the negative sign to the front of all the left padded 0s, to make negative numbers come before positive numbers
if dec.IsNegative() {
return append([]byte("-"), []byte(fmt.Sprintf(fmt.Sprintf("%%0%ds", LegacyPrecision*2+1), dec.Abs().String()))...)
}
return []byte(fmt.Sprintf(fmt.Sprintf("%%0%ds", LegacyPrecision*2+1), dec.String()))
}
// reuse nil values
var nilJSON []byte
func init() {
empty := new(big.Int)
bz, _ := empty.MarshalText()
nilJSON, _ = json.Marshal(string(bz))
}
// MarshalJSON marshals the decimal
func (d LegacyDec) MarshalJSON() ([]byte, error) {
if d.i == nil {
return nilJSON, nil
}
return json.Marshal(d.String())
}
// UnmarshalJSON defines custom decoding scheme
func (d *LegacyDec) UnmarshalJSON(bz []byte) error {
if d.i == nil {
d.i = new(big.Int)
}
var text string
err := json.Unmarshal(bz, &text)
if err != nil {
return err
}
// TODO: Reuse dec allocation
newDec, err := LegacyNewDecFromStr(text)
if err != nil {
return err
}
d.i = newDec.i
return nil
}
// MarshalYAML returns the YAML representation.
func (d LegacyDec) MarshalYAML() (interface{}, error) {
return d.String(), nil
}
// Marshal implements the gogo proto custom type interface.
func (d LegacyDec) Marshal() ([]byte, error) {
i := d.i
if i == nil {
i = new(big.Int)
}
return i.MarshalText()
}
// MarshalTo implements the gogo proto custom type interface.
func (d *LegacyDec) MarshalTo(data []byte) (n int, err error) {
i := d.i
if i == nil {
i = new(big.Int)
}
if i.Sign() == 0 {
copy(data, []byte{0x30})
return 1, nil
}
bz, err := d.Marshal()
if err != nil {
return 0, err
}
copy(data, bz)
return len(bz), nil
}
// Unmarshal implements the gogo proto custom type interface.
func (d *LegacyDec) Unmarshal(data []byte) error {
if len(data) == 0 {
d = nil
return nil
}
if d.i == nil {
d.i = new(big.Int)
}
if err := d.i.UnmarshalText(data); err != nil {
return err
}
if d.i.BitLen() > maxDecBitLen {
return fmt.Errorf("decimal out of range; got: %d, max: %d", d.i.BitLen(), maxDecBitLen)
}
return nil
}
// Size implements the gogo proto custom type interface.
func (d *LegacyDec) Size() int {
bz, _ := d.Marshal()
return len(bz)
}
// MarshalAmino Override Amino binary serialization by proxying to protobuf.
func (d LegacyDec) MarshalAmino() ([]byte, error) { return d.Marshal() }
func (d *LegacyDec) UnmarshalAmino(bz []byte) error { return d.Unmarshal(bz) }
// helpers
// LegacyDecsEqual return true if two decimal arrays are equal.
func LegacyDecsEqual(d1s, d2s []LegacyDec) bool {
if len(d1s) != len(d2s) {
return false
}
for i, d1 := range d1s {
if !d1.Equal(d2s[i]) {
return false
}
}
return true
}
// LegacyMinDec minimum decimal between two
func LegacyMinDec(d1, d2 LegacyDec) LegacyDec {
if d1.LT(d2) {
return d1
}
return d2
}
// LegacyMaxDec maximum decimal between two
func LegacyMaxDec(d1, d2 LegacyDec) LegacyDec {
if d1.LT(d2) {
return d2
}
return d1
}
// LegacyDecEq intended to be used with require/assert: require.True(DecEq(...))
func LegacyDecEq(t *testing.T, exp, got LegacyDec) (*testing.T, bool, string, string, string) {
t.Helper()
return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp.String(), got.String()
}
func LegacyDecApproxEq(t *testing.T, d1, d2, tol LegacyDec) (*testing.T, bool, string, string, string) {
t.Helper()
diff := d1.Sub(d2).Abs()
return t, diff.LTE(tol), "expected |d1 - d2| <:\t%v\ngot |d1 - d2| = \t\t%v", tol.String(), diff.String()
}
// FormatDec formats a decimal (as encoded in protobuf) into a value-rendered
// string following ADR-050. This function operates with string manipulation
// (instead of manipulating the sdk.Dec object).
func FormatDec(v string) (string, error) {
parts := strings.Split(v, ".")
if len(parts) > 2 {
return "", fmt.Errorf("invalid decimal: too many points in %s", v)
}
intPart, err := FormatInt(parts[0])
if err != nil {
return "", err
}
if len(parts) == 1 {
return intPart, nil
}
decPart := strings.TrimRight(parts[1], "0")
if len(decPart) == 0 {
return intPart, nil
}
// Ensure that the decimal part has only digits.
// https://github.com/cosmos/cosmos-sdk/issues/12811
if !hasOnlyDigits(decPart) {
return "", fmt.Errorf("non-digits detected after decimal point in: %q", decPart)
}
return intPart + "." + decPart, nil
}
package math
import (
"encoding"
"encoding/json"
"errors"
"fmt"
"math/big"
"math/bits"
"strings"
"sync"
"testing"
)
// MaxBitLen defines the maximum bit length supported bit Int and Uint types.
const MaxBitLen = 256
// maxWordLen defines the maximum word length supported by Int and Uint types.
// We check overflow, by first doing a fast check if the word length is below maxWordLen
// and if not then do the slower full bitlen check.
// NOTE: If MaxBitLen is not a multiple of bits.UintSize, then we need to edit the used logic slightly.
const maxWordLen = MaxBitLen / bits.UintSize
// Integer errors
var (
// ErrIntOverflow is the error returned when an integer overflow occurs
ErrIntOverflow = errors.New("integer overflow")
// ErrDivideByZero is the error returned when a divide by zero occurs
ErrDivideByZero = errors.New("divide by zero")
)
func newIntegerFromString(s string) (*big.Int, bool) {
return new(big.Int).SetString(s, 0)
}
func equal(i, i2 *big.Int) bool { return i.Cmp(i2) == 0 }
func gt(i, i2 *big.Int) bool { return i.Cmp(i2) == 1 }
func gte(i, i2 *big.Int) bool { return i.Cmp(i2) >= 0 }
func lt(i, i2 *big.Int) bool { return i.Cmp(i2) == -1 }
func lte(i, i2 *big.Int) bool { return i.Cmp(i2) <= 0 }
func add(i, i2 *big.Int) *big.Int { return new(big.Int).Add(i, i2) }
func sub(i, i2 *big.Int) *big.Int { return new(big.Int).Sub(i, i2) }
func mul(i, i2 *big.Int) *big.Int { return new(big.Int).Mul(i, i2) }
func div(i, i2 *big.Int) *big.Int { return new(big.Int).Quo(i, i2) }
func mod(i, i2 *big.Int) *big.Int { return new(big.Int).Mod(i, i2) }
func neg(i *big.Int) *big.Int { return new(big.Int).Neg(i) }
func abs(i *big.Int) *big.Int { return new(big.Int).Abs(i) }
func min(i, i2 *big.Int) *big.Int {
if i.Cmp(i2) == 1 {
return new(big.Int).Set(i2)
}
return new(big.Int).Set(i)
}
func max(i, i2 *big.Int) *big.Int {
if i.Cmp(i2) == -1 {
return new(big.Int).Set(i2)
}
return new(big.Int).Set(i)
}
func unmarshalText(i *big.Int, text string) error {
if err := i.UnmarshalText([]byte(text)); err != nil {
return err
}
if bigIntOverflows(i) {
return fmt.Errorf("integer out of range: %s", text)
}
return nil
}
var _ customProtobufType = (*Int)(nil)
// Int wraps big.Int with a 256 bit range bound
// Checks overflow, underflow and division by zero
// Exists in range from -(2^256 - 1) to 2^256 - 1
type Int struct {
i *big.Int
}
// BigInt converts Int to big.Int
func (i Int) BigInt() *big.Int {
if i.IsNil() {
return nil
}
return new(big.Int).Set(i.i)
}
// BigIntMut converts Int to big.Int, mutative the input
func (i Int) BigIntMut() *big.Int {
if i.IsNil() {
return nil
}
return i.i
}
// IsNil returns true if Int is uninitialized
func (i Int) IsNil() bool {
return i.i == nil
}
// NewInt constructs Int from int64
func NewInt(n int64) Int {
return Int{big.NewInt(n)}
}
// NewIntFromUint64 constructs an Int from a uint64.
func NewIntFromUint64(n uint64) Int {
b := big.NewInt(0)
b.SetUint64(n)
return Int{b}
}
// NewIntFromBigInt constructs Int from big.Int. If the provided big.Int is nil,
// it returns an empty instance. This function panics if the bit length is > 256.
// Note, the caller can safely mutate the argument after this function returns.
func NewIntFromBigInt(i *big.Int) Int {
if i == nil {
return Int{}
}
if bigIntOverflows(i) {
panic("NewIntFromBigInt() out of bound")
}
return Int{new(big.Int).Set(i)}
}
// NewIntFromBigIntMut constructs Int from big.Int. If the provided big.Int is nil,
// it returns an empty instance. This function panics if the bit length is > 256.
// Note, this function mutate the argument.
func NewIntFromBigIntMut(i *big.Int) Int {
if i == nil {
return Int{}
}
if bigIntOverflows(i) {
panic("NewIntFromBigInt() out of bound")
}
return Int{i}
}
// NewIntFromString constructs Int from string
func NewIntFromString(s string) (res Int, ok bool) {
i, ok := newIntegerFromString(s)
if !ok {
return
}
// Check overflow
if bigIntOverflows(i) {
ok = false
return
}
return Int{i}, true
}
// NewIntWithDecimal constructs Int with decimal
// Result value is n*10^dec
func NewIntWithDecimal(n int64, dec int) Int {
if dec < 0 {
panic("NewIntWithDecimal() decimal is negative")
}
exp := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(dec)), nil)
i := new(big.Int)
i.Mul(big.NewInt(n), exp)
// Check overflow
if bigIntOverflows(i) {
panic("NewIntWithDecimal() out of bound")
}
return Int{i}
}
// ZeroInt returns Int value with zero
func ZeroInt() Int { return Int{big.NewInt(0)} }
// OneInt returns Int value with one
func OneInt() Int { return Int{big.NewInt(1)} }
// ToLegacyDec converts Int to LegacyDec
func (i Int) ToLegacyDec() LegacyDec {
return LegacyNewDecFromInt(i)
}
// Int64 converts Int to int64
// Panics if the value is out of range
func (i Int) Int64() int64 {
if !i.i.IsInt64() {
panic("Int64() out of bound")
}
return i.i.Int64()
}
// IsInt64 returns true if Int64() not panics
func (i Int) IsInt64() bool {
return i.i.IsInt64()
}
// Uint64 converts Int to uint64
// Panics if the value is out of range
func (i Int) Uint64() uint64 {
if !i.i.IsUint64() {
panic("Uint64() out of bounds")
}
return i.i.Uint64()
}
// IsUint64 returns true if Uint64() not panics
func (i Int) IsUint64() bool {
return i.i.IsUint64()
}
// IsZero returns true if Int is zero
func (i Int) IsZero() bool {
return i.i.Sign() == 0
}
// IsNegative returns true if Int is negative
func (i Int) IsNegative() bool {
return i.i.Sign() == -1
}
// IsPositive returns true if Int is positive
func (i Int) IsPositive() bool {
return i.i.Sign() == 1
}
// Sign returns sign of Int
func (i Int) Sign() int {
return i.i.Sign()
}
// Equal compares two Ints
func (i Int) Equal(i2 Int) bool {
return equal(i.i, i2.i)
}
// GT returns true if first Int is greater than second
func (i Int) GT(i2 Int) bool {
return gt(i.i, i2.i)
}
// GTE returns true if receiver Int is greater than or equal to the parameter
// Int.
func (i Int) GTE(i2 Int) bool {
return gte(i.i, i2.i)
}
// LT returns true if first Int is lesser than second
func (i Int) LT(i2 Int) bool {
return lt(i.i, i2.i)
}
// LTE returns true if first Int is less than or equal to second
func (i Int) LTE(i2 Int) bool {
return lte(i.i, i2.i)
}
// Add adds Int from another
func (i Int) Add(i2 Int) (res Int) {
// Check overflow
x, err := i.SafeAdd(i2)
if err != nil {
panic(err)
}
return x
}
// AddRaw adds int64 to Int
func (i Int) AddRaw(i2 int64) Int {
return i.Add(NewInt(i2))
}
// SafeAdd adds Int from another and returns an error if overflow
func (i Int) SafeAdd(i2 Int) (res Int, err error) {
res = Int{add(i.i, i2.i)}
// Check overflow
if bigIntOverflows(res.i) {
return Int{}, ErrIntOverflow
}
return res, nil
}
// Sub subtracts Int from another
func (i Int) Sub(i2 Int) (res Int) {
// Check overflow
x, err := i.SafeSub(i2)
if err != nil {
panic(err)
}
return x
}
// SubRaw subtracts int64 from Int
func (i Int) SubRaw(i2 int64) Int {
return i.Sub(NewInt(i2))
}
// SafeSub subtracts Int from another and returns an error if overflow or underflow
func (i Int) SafeSub(i2 Int) (res Int, err error) {
res = Int{sub(i.i, i2.i)}
// Check overflow/underflow
if bigIntOverflows(res.i) {
return Int{}, ErrIntOverflow
}
return res, nil
}
// Mul multiples two Ints
func (i Int) Mul(i2 Int) (res Int) {
// Check overflow
x, err := i.SafeMul(i2)
if err != nil {
panic(err)
}
return x
}
// MulRaw multiplies Int and int64
func (i Int) MulRaw(i2 int64) Int {
return i.Mul(NewInt(i2))
}
// SafeMul multiples Int from another and returns an error if overflow
func (i Int) SafeMul(i2 Int) (res Int, err error) {
res = Int{mul(i.i, i2.i)}
// Check overflow
if bigIntOverflows(res.i) {
return Int{}, ErrIntOverflow
}
return res, nil
}
// Quo divides Int with Int
func (i Int) Quo(i2 Int) (res Int) {
// Check division-by-zero
x, err := i.SafeQuo(i2)
if err != nil {
panic("Division by zero")
}
return x
}
// QuoRaw divides Int with int64
func (i Int) QuoRaw(i2 int64) Int {
return i.Quo(NewInt(i2))
}
// SafeQuo divides Int with Int and returns an error if division by zero
func (i Int) SafeQuo(i2 Int) (res Int, err error) {
// Check division-by-zero
if i2.i.Sign() == 0 {
return Int{}, ErrDivideByZero
}
return Int{div(i.i, i2.i)}, nil
}
// Mod returns remainder after dividing with Int
func (i Int) Mod(i2 Int) Int {
x, err := i.SafeMod(i2)
if err != nil {
panic(err)
}
return x
}
// ModRaw returns remainder after dividing with int64
func (i Int) ModRaw(i2 int64) Int {
return i.Mod(NewInt(i2))
}
// SafeMod returns remainder after dividing with Int and returns an error if division by zero
func (i Int) SafeMod(i2 Int) (res Int, err error) {
if i2.Sign() == 0 {
return Int{}, ErrDivideByZero
}
return Int{mod(i.i, i2.i)}, nil
}
// Neg negates Int
func (i Int) Neg() (res Int) {
return Int{neg(i.i)}
}
// Abs returns the absolute value of Int.
func (i Int) Abs() Int {
return Int{abs(i.i)}
}
// MinInt return the minimum of the ints
func MinInt(i1, i2 Int) Int {
return Int{min(i1.BigInt(), i2.BigInt())}
}
// MaxInt returns the maximum between two integers.
func MaxInt(i, i2 Int) Int {
return Int{max(i.BigInt(), i2.BigInt())}
}
// String returns human-readable string
func (i Int) String() string {
return i.i.String()
}
// MarshalJSON defines custom encoding scheme
func (i Int) MarshalJSON() ([]byte, error) {
if i.i == nil { // Necessary since default Uint initialization has i.i as nil
i.i = new(big.Int)
}
return marshalJSON(i.i)
}
// UnmarshalJSON defines custom decoding scheme
func (i *Int) UnmarshalJSON(bz []byte) error {
if i.i == nil { // Necessary since default Int initialization has i.i as nil
i.i = new(big.Int)
}
return unmarshalJSON(i.i, bz)
}
// MarshalJSON for custom encoding scheme
// Must be encoded as a string for JSON precision
func marshalJSON(i encoding.TextMarshaler) ([]byte, error) {
text, err := i.MarshalText()
if err != nil {
return nil, err
}
return json.Marshal(string(text))
}
// UnmarshalJSON for custom decoding scheme
// Must be encoded as a string for JSON precision
func unmarshalJSON(i *big.Int, bz []byte) error {
var text string
if err := json.Unmarshal(bz, &text); err != nil {
return err
}
return unmarshalText(i, text)
}
// MarshalYAML returns the YAML representation.
func (i Int) MarshalYAML() (interface{}, error) {
return i.String(), nil
}
// Marshal implements the gogo proto custom type interface.
func (i Int) Marshal() ([]byte, error) {
if i.i == nil {
i.i = new(big.Int)
}
return i.i.MarshalText()
}
// MarshalTo implements the gogo proto custom type interface.
func (i *Int) MarshalTo(data []byte) (n int, err error) {
if i.i == nil {
i.i = new(big.Int)
}
if i.i.BitLen() == 0 { // The value 0
n = copy(data, []byte{0x30})
return n, nil
}
bz, err := i.Marshal()
if err != nil {
return 0, err
}
n = copy(data, bz)
return n, nil
}
// Unmarshal implements the gogo proto custom type interface.
func (i *Int) Unmarshal(data []byte) error {
if len(data) == 0 {
i = nil
return nil
}
if i.i == nil {
i.i = new(big.Int)
}
if err := i.i.UnmarshalText(data); err != nil {
return err
}
if bigIntOverflows(i.i) {
return fmt.Errorf("integer out of range; got: %d, max: %d", i.i.BitLen(), MaxBitLen)
}
return nil
}
// Size implements the gogo proto custom type interface.
func (i *Int) Size() int {
bz, _ := i.Marshal()
return len(bz)
}
// MarshalAmino Override Amino binary serialization by proxying to protobuf.
func (i Int) MarshalAmino() ([]byte, error) { return i.Marshal() }
func (i *Int) UnmarshalAmino(bz []byte) error { return i.Unmarshal(bz) }
// IntEq intended to be used with require/assert: require.True(IntEq(...))
func IntEq(t *testing.T, exp, got Int) (*testing.T, bool, string, string, string) {
t.Helper()
return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp.String(), got.String()
}
func hasOnlyDigits(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
const thousandSeparator string = "'"
var stringsBuilderPool = &sync.Pool{
New: func() any { return new(strings.Builder) },
}
// FormatInt formats an integer (encoded as in protobuf) into a value-rendered
// string following ADR-050. This function operates with string manipulation
// (instead of manipulating the int or math.Int object).
func FormatInt(v string) (string, error) {
if len(v) == 0 {
return "", errors.New("cannot format empty string")
}
sign := ""
if v[0] == '-' {
sign = "-"
v = v[1:]
}
if len(v) > 1 {
v = strings.TrimLeft(v, "0")
}
// Ensure that the string contains only digits at this point.
if !hasOnlyDigits(v) {
return "", fmt.Errorf("expecting only digits 0-9, but got non-digits in %q", v)
}
// 1. Less than 4 digits don't need any formatting.
if len(v) <= 3 {
return sign + v, nil
}
sb := stringsBuilderPool.Get().(*strings.Builder)
defer stringsBuilderPool.Put(sb)
sb.Reset()
sb.Grow(len(v) + len(v)/3) // Exactly v + numberOfThousandSeparatorsIn(v)
// 2. If the length of v is not a multiple of 3 e.g. 1234 or 12345, to achieve 1'234 or 12'345,
// we can simply slide to the first mod3 values of v that aren't the multiples of 3 then insert in
// the thousands separator so in this case: write(12'); then the remaining v will be entirely multiple
// of 3 hence v = 34*
if mod3 := len(v) % 3; mod3 != 0 {
sb.WriteString(v[:mod3])
v = v[mod3:]
sb.WriteString(thousandSeparator)
}
// 3. By this point v is entirely multiples of 3 hence we just insert the separator at every 3 digit.
for i := 0; i < len(v); i += 3 {
end := i + 3
sb.WriteString(v[i:end])
if end < len(v) {
sb.WriteString(thousandSeparator)
}
}
return sign + sb.String(), nil
}
// check if the big int overflows.
func bigIntOverflows(i *big.Int) bool {
// overflow is defined as i.BitLen() > MaxBitLen
// however this check can be expensive when doing many operations.
// So we first check if the word length is greater than maxWordLen.
// However the most significant word could be zero, hence we still do the bitlen check.
if len(i.Bits()) > maxWordLen {
return i.BitLen() > MaxBitLen
}
return false
}
package math
import "golang.org/x/exp/constraints"
func Max[T constraints.Ordered](a, b T, rest ...T) T {
max := a
if b > a {
max = b
}
for _, val := range rest {
if val > max {
max = val
}
}
return max
}
func Min[T constraints.Ordered](a, b T, rest ...T) T {
min := a
if b < a {
min = b
}
for _, val := range rest {
if val < min {
min = val
}
}
return min
}
package math
import (
"errors"
"fmt"
"math/big"
)
// Uint wraps integer with 256 bit range bound
// Checks overflow, underflow and division by zero
// Exists in range from 0 to 2^256-1
type Uint struct {
i *big.Int
}
// BigInt converts Uint to big.Int
func (u Uint) BigInt() *big.Int {
if u.IsNil() {
return nil
}
return new(big.Int).Set(u.i)
}
// BigIntMut converts Uint to big.Int, mutative the input
func (u Uint) BigIntMut() *big.Int {
if u.IsNil() {
return nil
}
return u.i
}
// IsNil returns true if Uint is uninitialized
func (u Uint) IsNil() bool {
return u.i == nil
}
// NewUintFromBigInt constructs Uint from big.Int
// Panics if i is negative or wider than 256 bits
func NewUintFromBigInt(i *big.Int) Uint {
u, err := checkNewUint(i)
if err != nil {
panic(fmt.Errorf("overflow: %w", err))
}
return u
}
// NewUint constructs Uint from uint64
func NewUint(n uint64) Uint {
i := new(big.Int)
i.SetUint64(n)
return NewUintFromBigInt(i)
}
// NewUintFromString constructs Uint from string
// Panics if parsed s is negative or wider than 256 bits
func NewUintFromString(s string) Uint {
u, err := ParseUint(s)
if err != nil {
panic(err)
}
return u
}
// ZeroUint returns unsigned zero.
func ZeroUint() Uint { return Uint{big.NewInt(0)} }
// OneUint returns Uint value with one.
func OneUint() Uint { return Uint{big.NewInt(1)} }
var _ customProtobufType = (*Uint)(nil)
// Uint64 converts Uint to uint64
// Panics if the value is out of range
func (u Uint) Uint64() uint64 {
if !u.i.IsUint64() {
panic("Uint64() out of bound")
}
return u.i.Uint64()
}
// IsZero returns 1 if the uint equals to 0.
func (u Uint) IsZero() bool { return u.Equal(ZeroUint()) }
// Equal compares two Uints
func (u Uint) Equal(u2 Uint) bool { return equal(u.i, u2.i) }
// GT returns true if first Uint is greater than second
func (u Uint) GT(u2 Uint) bool { return gt(u.i, u2.i) }
// GTE returns true if first Uint is greater than second
func (u Uint) GTE(u2 Uint) bool { return u.GT(u2) || u.Equal(u2) }
// LT returns true if first Uint is lesser than second
func (u Uint) LT(u2 Uint) bool { return lt(u.i, u2.i) }
// LTE returns true if first Uint is lesser than or equal to the second
func (u Uint) LTE(u2 Uint) bool { return !u.GT(u2) }
// Add adds Uint from another
func (u Uint) Add(u2 Uint) Uint { return NewUintFromBigInt(new(big.Int).Add(u.i, u2.i)) }
// AddUint64 convert uint64 and add it to Uint
func (u Uint) AddUint64(u2 uint64) Uint { return u.Add(NewUint(u2)) }
// Sub adds Uint from another
func (u Uint) Sub(u2 Uint) Uint { return NewUintFromBigInt(new(big.Int).Sub(u.i, u2.i)) }
// SubUint64 adds Uint from another
func (u Uint) SubUint64(u2 uint64) Uint { return u.Sub(NewUint(u2)) }
// Mul multiplies two Uints
func (u Uint) Mul(u2 Uint) (res Uint) {
return NewUintFromBigInt(new(big.Int).Mul(u.i, u2.i))
}
// MulUint64 multiplies two Uints
func (u Uint) MulUint64(u2 uint64) (res Uint) { return u.Mul(NewUint(u2)) }
// Quo divides Uint with Uint
func (u Uint) Quo(u2 Uint) (res Uint) { return NewUintFromBigInt(div(u.i, u2.i)) }
// Mod returns remainder after dividing with Uint
// Panics if u2 is zero
func (u Uint) Mod(u2 Uint) Uint {
if u2.IsZero() {
panic("division-by-zero")
}
return Uint{mod(u.i, u2.i)}
}
// Incr increments the Uint by one.
func (u Uint) Incr() Uint {
return u.Add(OneUint())
}
// Decr decrements the Uint by one.
// Decr will panic if the Uint is zero.
func (u Uint) Decr() Uint {
return u.Sub(OneUint())
}
// QuoUint64 divides Uint with uint64
func (u Uint) QuoUint64(u2 uint64) Uint { return u.Quo(NewUint(u2)) }
// MinUint returns the minimum of the Uints
func MinUint(u1, u2 Uint) Uint { return NewUintFromBigInt(min(u1.i, u2.i)) }
// MaxUint returns the maximum of the Uints
func MaxUint(u1, u2 Uint) Uint { return NewUintFromBigInt(max(u1.i, u2.i)) }
// String returns human-readable string
func (u Uint) String() string { return u.i.String() }
// MarshalJSON defines custom encoding scheme
func (u Uint) MarshalJSON() ([]byte, error) {
if u.i == nil { // Necessary since default Uint initialization has i.i as nil
u.i = new(big.Int)
}
return marshalJSON(u.i)
}
// UnmarshalJSON defines custom decoding scheme
func (u *Uint) UnmarshalJSON(bz []byte) error {
if u.i == nil { // Necessary since default Uint initialization has i.i as nil
u.i = new(big.Int)
}
return unmarshalJSON(u.i, bz)
}
// Marshal implements the gogo proto custom type interface.
func (u Uint) Marshal() ([]byte, error) {
if u.i == nil {
u.i = new(big.Int)
}
return u.i.MarshalText()
}
// MarshalTo implements the gogo proto custom type interface.
func (u *Uint) MarshalTo(data []byte) (n int, err error) {
if u.i == nil {
u.i = new(big.Int)
}
if u.i.BitLen() == 0 { // The value 0
n = copy(data, []byte{0x30})
return n, nil
}
bz, err := u.Marshal()
if err != nil {
return 0, err
}
n = copy(data, bz)
return n, nil
}
// Unmarshal implements the gogo proto custom type interface.
func (u *Uint) Unmarshal(data []byte) error {
if len(data) == 0 {
u = nil
return nil
}
if u.i == nil {
u.i = new(big.Int)
}
if err := u.i.UnmarshalText(data); err != nil {
return err
}
// Finally check for overflow.
return UintOverflow(u.i)
}
// Size implements the gogo proto custom type interface.
func (u *Uint) Size() int {
bz, _ := u.Marshal()
return len(bz)
}
// MarshalAmino override Amino binary serialization by proxying to protobuf.
func (u Uint) MarshalAmino() ([]byte, error) { return u.Marshal() }
func (u *Uint) UnmarshalAmino(bz []byte) error { return u.Unmarshal(bz) }
// UintOverflow returns true if a given unsigned integer overflows and false
// otherwise.
func UintOverflow(i *big.Int) error {
if i.Sign() < 0 {
return errors.New("non-positive integer")
}
if g, w := i.BitLen(), MaxBitLen; g > w {
return fmt.Errorf("integer out of range; got: %d, max: %d", g, w)
}
return nil
}
// ParseUint reads a string-encoded Uint value and return a Uint.
func ParseUint(s string) (Uint, error) {
i, ok := new(big.Int).SetString(s, 0)
if !ok {
return Uint{}, fmt.Errorf("cannot convert %q to big.Int", s)
}
return checkNewUint(i)
}
func checkNewUint(i *big.Int) (Uint, error) {
if err := UintOverflow(i); err != nil {
return Uint{}, err
}
return Uint{new(big.Int).Set(i)}, nil
}
// RelativePow raises x to the power of n, where x (and the result, z) are scaled by factor b
// for example, RelativePow(210, 2, 100) = 441 (2.1^2 = 4.41)
func RelativePow(x, n, b Uint) (z Uint) {
if x.IsZero() {
if n.IsZero() {
z = OneUint() // 0^0 = 1
return z
}
z = ZeroUint() // otherwise 0^a = 0
return z
}
z = x
if n.Mod(NewUint(2)).Equal(ZeroUint()) {
z = b
}
halfOfB := b.Quo(NewUint(2))
n = n.Quo(NewUint(2))
for n.GT(ZeroUint()) {
xSquared := x.Mul(x)
xSquaredRounded := xSquared.Add(halfOfB)
x = xSquaredRounded.Quo(b)
if n.Mod(NewUint(2)).Equal(OneUint()) {
zx := z.Mul(x)
zxRounded := zx.Add(halfOfB)
z = zxRounded.Quo(b)
}
n = n.Quo(NewUint(2))
}
return z
}
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/base/abci/v1beta1/abci.proto
package types
import (
fmt "fmt"
v1 "github.com/cometbft/cometbft/api/cometbft/abci/v1"
v11 "github.com/cometbft/cometbft/api/cometbft/types/v1"
_ "github.com/cosmos/cosmos-proto"
_ "github.com/cosmos/gogoproto/gogoproto"
proto "github.com/cosmos/gogoproto/proto"
any "github.com/cosmos/gogoproto/types/any"
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 *any.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.
Events []v1.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 []v1.Event `protobuf:"bytes,3,rep,name=events,proto3" json:"events"`
// msg_responses contains the Msg handler responses type packed in Anys.
MsgResponses []*any.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.
MsgResponses []*any.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() []*any.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 []*v11.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() []*v11.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{
// 1006 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0xbf, 0x6f, 0x5b, 0x37,
0x17, 0xd5, 0xd3, 0x53, 0x9e, 0x2c, 0xca, 0xfe, 0xfc, 0x81, 0x35, 0xe2, 0xe7, 0x20, 0x91, 0x54,
0x25, 0x05, 0x84, 0x02, 0x79, 0x8a, 0x9d, 0x26, 0x68, 0x33, 0x25, 0x72, 0x7f, 0xc4, 0x40, 0x92,
0x81, 0x56, 0x50, 0xa0, 0x8b, 0x40, 0x49, 0x34, 0xf5, 0x60, 0xbd, 0x47, 0x41, 0xa4, 0x6c, 0x79,
0xeb, 0xd8, 0xb1, 0x53, 0xa7, 0x0e, 0x5d, 0xdb, 0xb9, 0x7b, 0xd7, 0x8c, 0x1e, 0xd3, 0x22, 0x70,
0x53, 0x7b, 0xeb, 0x5f, 0x51, 0xdc, 0x4b, 0x3e, 0x49, 0xa9, 0x2b, 0x77, 0xe8, 0x46, 0x9e, 0x7b,
0x49, 0xde, 0x73, 0xee, 0x21, 0x49, 0x6e, 0xf7, 0x94, 0x4e, 0x94, 0x6e, 0x76, 0xb9, 0x16, 0x4d,
0xde, 0xed, 0xc5, 0xcd, 0xa3, 0xed, 0xae, 0x30, 0x7c, 0x1b, 0x27, 0xd1, 0x68, 0xac, 0x8c, 0xa2,
0xa1, 0x4d, 0x8a, 0x20, 0x29, 0x42, 0xdc, 0x25, 0xdd, 0xd8, 0x90, 0x4a, 0x2a, 0x4c, 0x6a, 0xc2,
0xc8, 0xe6, 0xdf, 0xb8, 0xd9, 0x53, 0x89, 0x30, 0xdd, 0x03, 0x93, 0xed, 0xd8, 0x34, 0x27, 0x23,
0xa1, 0x5d, 0xf4, 0xd6, 0x2c, 0x8a, 0x28, 0x84, 0xbb, 0x43, 0xd5, 0x3b, 0x74, 0xe1, 0x2d, 0xa9,
0x94, 0x1c, 0x8a, 0x26, 0xce, 0xba, 0x93, 0x83, 0x26, 0x4f, 0x4f, 0xb2, 0x90, 0xad, 0xa3, 0x63,
0x0f, 0x74, 0x45, 0xe1, 0xa4, 0xfe, 0xd6, 0x27, 0xa4, 0x3d, 0x65, 0x42, 0x8f, 0x54, 0xaa, 0x05,
0xbd, 0x4e, 0x82, 0x81, 0x88, 0xe5, 0xc0, 0x84, 0x5e, 0xcd, 0x6b, 0xf8, 0xcc, 0xcd, 0x68, 0x9d,
0x04, 0x66, 0x3a, 0xe0, 0x7a, 0x10, 0xe6, 0x6b, 0x5e, 0xa3, 0xd4, 0x22, 0xe7, 0x67, 0xd5, 0xa0,
0x3d, 0x7d, 0xca, 0xf5, 0x80, 0xb9, 0x08, 0xbd, 0x49, 0x4a, 0x3d, 0xd5, 0x17, 0x7a, 0xc4, 0x7b,
0x22, 0xf4, 0x21, 0x8d, 0xcd, 0x01, 0x4a, 0x49, 0x01, 0x26, 0x61, 0xa1, 0xe6, 0x35, 0xd6, 0x18,
0x8e, 0x01, 0xeb, 0x73, 0xc3, 0xc3, 0x6b, 0x98, 0x8c, 0x63, 0xba, 0x49, 0x8a, 0x63, 0x7e, 0xdc,
0x19, 0x2a, 0x19, 0x06, 0x08, 0x07, 0x63, 0x7e, 0xfc, 0x4c, 0x49, 0xfa, 0x92, 0x14, 0x86, 0x4a,
0xea, 0xb0, 0x58, 0xf3, 0x1b, 0xe5, 0x9d, 0x46, 0xb4, 0x4c, 0xdb, 0xe8, 0x49, 0x6b, 0x77, 0xef,
0xb9, 0xd0, 0x9a, 0x4b, 0xf1, 0x4c, 0xc9, 0xd6, 0xe6, 0xab, 0xb3, 0x6a, 0xee, 0xa7, 0xdf, 0xab,
0xeb, 0xef, 0xe2, 0x9a, 0xe1, 0x76, 0x50, 0x43, 0x9c, 0x1e, 0xa8, 0x70, 0xc5, 0xd6, 0x00, 0x63,
0x7a, 0x8b, 0x10, 0xc9, 0x75, 0xe7, 0x98, 0xa7, 0x46, 0xf4, 0xc3, 0x12, 0x2a, 0x51, 0x92, 0x5c,
0x7f, 0x89, 0x00, 0xdd, 0x22, 0x2b, 0x10, 0x9e, 0x68, 0xd1, 0x0f, 0x09, 0x06, 0x8b, 0x92, 0xeb,
0x97, 0x5a, 0xf4, 0xe9, 0x1d, 0x92, 0x37, 0xd3, 0xb0, 0x5c, 0xf3, 0x1a, 0xe5, 0x9d, 0x8d, 0xc8,
0x76, 0x24, 0xca, 0x3a, 0x12, 0x3d, 0x49, 0x4f, 0x58, 0xde, 0x4c, 0x41, 0x29, 0x13, 0x27, 0x42,
0x1b, 0x9e, 0x8c, 0xc2, 0x55, 0xab, 0xd4, 0x0c, 0xa0, 0x4f, 0x49, 0x20, 0x8e, 0x44, 0x6a, 0x74,
0xb8, 0x86, 0x54, 0x37, 0xa3, 0xac, 0xf1, 0x19, 0xcf, 0xe8, 0x33, 0x88, 0x5b, 0x66, 0xbf, 0xfd,
0x7c, 0x77, 0xdd, 0x4a, 0x71, 0x57, 0xf7, 0x0f, 0x6b, 0xf7, 0xa2, 0x8f, 0x1e, 0x30, 0xb7, 0xfe,
0x51, 0xe1, 0x9b, 0x1f, 0xaa, 0xb9, 0xfa, 0x8f, 0x1e, 0xf9, 0xdf, 0xbb, 0xdc, 0xe9, 0x87, 0xa4,
0x94, 0x68, 0xd9, 0x89, 0xd3, 0xbe, 0x98, 0x62, 0xa7, 0xd7, 0x5a, 0x6b, 0x7f, 0x9e, 0x55, 0xe7,
0x20, 0x5b, 0x49, 0xb4, 0xdc, 0x83, 0x11, 0xfd, 0x3f, 0xf1, 0xa1, 0x19, 0xd8, 0x77, 0x06, 0x43,
0xba, 0x3f, 0x2b, 0xd0, 0xc7, 0x02, 0x3f, 0x58, 0xde, 0x8b, 0x7d, 0x33, 0x8e, 0x53, 0x69, 0xcb,
0xdd, 0x70, 0x8d, 0x58, 0x5d, 0x00, 0xf5, 0xbc, 0xd6, 0xaf, 0xdf, 0xd4, 0xbc, 0xfa, 0x98, 0x94,
0x17, 0xa2, 0xd0, 0x1c, 0xf0, 0x3a, 0x96, 0x58, 0x62, 0x38, 0xa6, 0x7b, 0x84, 0x70, 0x63, 0xc6,
0x71, 0x77, 0x62, 0x84, 0x0e, 0xf3, 0x58, 0xc1, 0xed, 0x2b, 0xdc, 0x90, 0xe5, 0xb6, 0x0a, 0x70,
0x3e, 0x5b, 0x58, 0xec, 0xce, 0xbc, 0x4f, 0x4a, 0xb3, 0x24, 0x60, 0x7b, 0x28, 0x4e, 0xdc, 0x81,
0x30, 0xa4, 0x1b, 0xe4, 0xda, 0x11, 0x1f, 0x4e, 0x84, 0x53, 0xc0, 0x4e, 0xea, 0xbb, 0xa4, 0xf8,
0x05, 0xd7, 0x7b, 0x97, 0xdd, 0x02, 0x2b, 0x0b, 0xcb, 0xdc, 0x92, 0xc7, 0x60, 0xe6, 0x96, 0xfa,
0x2f, 0x1e, 0x09, 0x98, 0xd0, 0x93, 0xa1, 0xa1, 0xd7, 0xdd, 0x55, 0x80, 0xe5, 0xab, 0xad, 0x7c,
0xe8, 0xb9, 0xeb, 0x70, 0x59, 0xfd, 0x07, 0x7f, 0x53, 0x7f, 0xa9, 0x3d, 0x2c, 0x5f, 0x97, 0x4c,
0x5f, 0x90, 0x35, 0xe8, 0xee, 0xd8, 0xdd, 0x74, 0x1d, 0x16, 0x70, 0xf5, 0x3f, 0x9a, 0xb4, 0xf5,
0xde, 0x65, 0x57, 0x3d, 0x64, 0xab, 0x89, 0x96, 0xd9, 0x43, 0x91, 0x79, 0xeb, 0x3b, 0x8f, 0xd0,
0xfd, 0x38, 0x99, 0x0c, 0xb9, 0x89, 0x55, 0x3a, 0x7b, 0x46, 0x3e, 0xb7, 0x9c, 0xf1, 0x62, 0x79,
0x78, 0x19, 0xde, 0x5f, 0xde, 0x21, 0xa7, 0x63, 0x6b, 0x05, 0xea, 0x3d, 0x3d, 0xab, 0x7a, 0x28,
0x10, 0x4a, 0xfb, 0x31, 0x09, 0xc6, 0xa8, 0x0f, 0x0a, 0x50, 0xde, 0xa9, 0x2d, 0xdf, 0xc5, 0xea,
0xc8, 0x5c, 0x7e, 0xfd, 0x31, 0x29, 0x3e, 0xd7, 0xf2, 0x53, 0x90, 0x70, 0x8b, 0x80, 0x99, 0x3b,
0x0b, 0x46, 0x2a, 0x26, 0x5a, 0xb6, 0xc1, 0x4b, 0xd9, 0x03, 0x04, 0xbb, 0xaf, 0x5a, 0xc5, 0x1f,
0x05, 0x60, 0x8a, 0xd0, 0xab, 0x7f, 0xef, 0x91, 0x52, 0x7b, 0x9a, 0x6d, 0xf2, 0xc9, 0xac, 0x3f,
0xfe, 0xd5, 0x6c, 0xdc, 0x82, 0x85, 0x16, 0x5e, 0x52, 0x3e, 0xff, 0x1f, 0x95, 0x47, 0xd7, 0xbe,
0xf1, 0xc8, 0xfa, 0xbe, 0xe0, 0xe3, 0xde, 0xa0, 0x3d, 0xd5, 0xce, 0x44, 0x55, 0x52, 0x36, 0xca,
0xf0, 0x61, 0xa7, 0xa7, 0x26, 0xa9, 0x71, 0x56, 0x24, 0x08, 0xed, 0x02, 0x02, 0x5e, 0xb6, 0x21,
0x6b, 0x44, 0x3b, 0x81, 0x65, 0x23, 0x2e, 0x45, 0x27, 0x9d, 0x24, 0x5d, 0x31, 0xc6, 0xa7, 0xbb,
0xc0, 0x08, 0x40, 0x2f, 0x10, 0x01, 0x87, 0x63, 0x02, 0xee, 0x84, 0x2f, 0x78, 0x81, 0x95, 0x00,
0x69, 0x03, 0x00, 0xbb, 0x0e, 0xe3, 0x24, 0x36, 0xf8, 0x8e, 0x17, 0x98, 0x9d, 0xd0, 0x87, 0xc4,
0x37, 0x53, 0x1d, 0x06, 0x48, 0xf6, 0xce, 0x72, 0xc1, 0xe6, 0xbf, 0x0f, 0x83, 0x05, 0x8e, 0xde,
0xaf, 0x60, 0x2c, 0xa4, 0xd7, 0x82, 0x3f, 0xee, 0x0a, 0x86, 0xfe, 0x72, 0x86, 0xfe, 0x15, 0x0c,
0xfd, 0x7f, 0x61, 0xe8, 0x2f, 0x65, 0xe8, 0x67, 0x0c, 0xef, 0x91, 0x00, 0x3f, 0xe0, 0x8c, 0x64,
0x38, 0xbf, 0x89, 0xf6, 0xdf, 0x3e, 0xda, 0x8e, 0xb0, 0x7a, 0xe6, 0xf2, 0x2c, 0xb7, 0xd6, 0xe3,
0xd7, 0x7f, 0x54, 0x72, 0xaf, 0xce, 0x2b, 0xde, 0xe9, 0x79, 0xc5, 0x7b, 0x7b, 0x5e, 0xf1, 0xbe,
0xbd, 0xa8, 0xe4, 0x4e, 0x2f, 0x2a, 0xb9, 0xd7, 0x17, 0x95, 0xdc, 0x57, 0x75, 0x19, 0x9b, 0xc1,
0xa4, 0x0b, 0x7b, 0xb9, 0xaf, 0xba, 0x39, 0xf7, 0x83, 0xfd, 0xfa, 0xbb, 0x01, 0x7a, 0xe6, 0xfe,
0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x29, 0x1b, 0x28, 0xcc, 0x86, 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", "any.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", "v11.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 = &any.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, v1.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, v1.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, &any.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, &any.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, &v11.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 types
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sync"
"sync/atomic"
"github.com/hashicorp/golang-lru/simplelru"
"sigs.k8s.io/yaml"
addresscodec "github.com/cosmos/cosmos-sdk/codec/address"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/internal/conv"
"github.com/cosmos/cosmos-sdk/types/bech32"
)
const (
// Constants defined here are the defaults value for address.
// You can use the specific values for your project.
// Add the follow lines to the `main()` of your server.
//
// config := sdk.GetConfig()
// config.SetBech32PrefixForAccount(yourBech32PrefixAccAddr, yourBech32PrefixAccPub)
// config.SetBech32PrefixForValidator(yourBech32PrefixValAddr, yourBech32PrefixValPub)
// config.SetBech32PrefixForConsensusNode(yourBech32PrefixConsAddr, yourBech32PrefixConsPub)
// config.SetPurpose(yourPurpose)
// config.Seal()
// Bech32MainPrefix defines the main SDK Bech32 prefix of an account's address
Bech32MainPrefix = "cosmos"
// Purpose is the ATOM purpose as defined in SLIP44 (https://github.com/satoshilabs/slips/blob/master/slip-0044.md)
Purpose = 44
// CoinType is the ATOM coin type as defined in SLIP44 (https://github.com/satoshilabs/slips/blob/master/slip-0044.md)
CoinType = 118
// FullFundraiserPath is the parts of the BIP44 HD path that are fixed by
// what we used during the ATOM fundraiser.
FullFundraiserPath = "m/44'/118'/0'/0/0"
// PrefixAccount is the prefix for account keys
PrefixAccount = "acc"
// PrefixValidator is the prefix for validator keys
PrefixValidator = "val"
// PrefixConsensus is the prefix for consensus keys
PrefixConsensus = "cons"
// PrefixPublic is the prefix for public keys
PrefixPublic = "pub"
// PrefixOperator is the prefix for operator keys
PrefixOperator = "oper"
// PrefixAddress is the prefix for addresses
PrefixAddress = "addr"
// Bech32PrefixAccAddr defines the Bech32 prefix of an account's address
Bech32PrefixAccAddr = Bech32MainPrefix
// Bech32PrefixAccPub defines the Bech32 prefix of an account's public key
Bech32PrefixAccPub = Bech32MainPrefix + PrefixPublic
// Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address
Bech32PrefixValAddr = Bech32MainPrefix + PrefixValidator + PrefixOperator
// Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key
Bech32PrefixValPub = Bech32MainPrefix + PrefixValidator + PrefixOperator + PrefixPublic
// Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address
Bech32PrefixConsAddr = Bech32MainPrefix + PrefixValidator + PrefixConsensus
// Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key
Bech32PrefixConsPub = Bech32MainPrefix + PrefixValidator + PrefixConsensus + PrefixPublic
)
// GetBech32PrefixAccPub returns the Bech32 prefix of an account's public key.
func GetBech32PrefixAccPub(mainPrefix string) string {
return mainPrefix + PrefixPublic
}
// GetBech32PrefixValAddr returns the Bech32 prefix of a validator's operator address.
func GetBech32PrefixValAddr(mainPrefix string) string {
return mainPrefix + PrefixValidator + PrefixOperator
}
// GetBech32PrefixValPub returns the Bech32 prefix of a validator's operator public key.
func GetBech32PrefixValPub(mainPrefix string) string {
return mainPrefix + PrefixValidator + PrefixOperator + PrefixPublic
}
// GetBech32PrefixConsAddr returns the Bech32 prefix of a consensus node address.
func GetBech32PrefixConsAddr(mainPrefix string) string {
return mainPrefix + PrefixValidator + PrefixConsensus
}
// GetBech32PrefixConsPub returns the Bech32 prefix of a consensus node public key.
func GetBech32PrefixConsPub(mainPrefix string) string {
return mainPrefix + PrefixValidator + PrefixConsensus + PrefixPublic
}
// cache variables
var (
// AccAddress.String() is expensive and if unoptimized dominantly showed up in profiles,
// yet has no mechanisms to trivially cache the result given that AccAddress is a []byte type.
accAddrMu sync.Mutex
accAddrCache *simplelru.LRU
consAddrMu sync.Mutex
consAddrCache *simplelru.LRU
valAddrMu sync.Mutex
valAddrCache *simplelru.LRU
isCachingEnabled atomic.Bool
)
// sentinel errors
var (
ErrEmptyHexAddress = errors.New("decoding address from hex string failed: empty address")
)
func init() {
var err error
SetAddrCacheEnabled(true)
// in total the cache size is 61k entries. Key is 32 bytes and value is around 50-70 bytes.
// That will make around 92 * 61k * 2 (LRU) bytes ~ 11 MB
if accAddrCache, err = simplelru.NewLRU(60000, nil); err != nil {
panic(err)
}
if consAddrCache, err = simplelru.NewLRU(500, nil); err != nil {
panic(err)
}
if valAddrCache, err = simplelru.NewLRU(500, nil); err != nil {
panic(err)
}
}
// SetAddrCacheEnabled enables or disables accAddrCache, consAddrCache, and valAddrCache. By default, caches are enabled.
func SetAddrCacheEnabled(enabled bool) {
isCachingEnabled.Store(enabled)
}
// IsAddrCacheEnabled returns if the address caches are enabled.
func IsAddrCacheEnabled() bool {
return isCachingEnabled.Load()
}
// Address is a common interface for different types of addresses used by the SDK
type Address interface {
Equals(Address) bool
Empty() bool
Marshal() ([]byte, error)
MarshalJSON() ([]byte, error)
Bytes() []byte
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
String() string
Format(s fmt.State, verb rune)
}
// Ensure that different address types implement the interface
var (
_ Address = AccAddress{}
_ Address = ValAddress{}
_ Address = ConsAddress{}
)
// ----------------------------------------------------------------------------
// account
// ----------------------------------------------------------------------------
// AccAddress a wrapper around bytes meant to represent an account address.
// When marshaled to a string or JSON, it uses Bech32.
type AccAddress []byte
// AccAddressFromHexUnsafe creates an AccAddress from a HEX-encoded string.
//
// Note, this function is considered unsafe as it may produce an AccAddress from
// otherwise invalid input, such as a transaction hash. Please use
// AccAddressFromBech32.
func AccAddressFromHexUnsafe(address string) (addr AccAddress, err error) {
bz, err := addressBytesFromHexString(address)
return AccAddress(bz), err
}
// MustAccAddressFromBech32 calls AccAddressFromBech32 and panics on error.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func MustAccAddressFromBech32(address string) AccAddress {
addr, err := AccAddressFromBech32(address)
if err != nil {
panic(err)
}
return addr
}
// AccAddressFromBech32 creates an AccAddress from a Bech32 string.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func AccAddressFromBech32(address string) (addr AccAddress, err error) {
bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix()
addrCdc := addresscodec.NewBech32Codec(bech32PrefixAccAddr)
return addrCdc.StringToBytes(address)
}
// Returns boolean for whether two AccAddresses are Equal
func (aa AccAddress) Equals(aa2 Address) bool {
if aa.Empty() && aa2.Empty() {
return true
}
return bytes.Equal(aa.Bytes(), aa2.Bytes())
}
// Returns boolean for whether an AccAddress is empty
func (aa AccAddress) Empty() bool {
return len(aa) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (aa AccAddress) Marshal() ([]byte, error) {
return aa, nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (aa *AccAddress) Unmarshal(data []byte) error {
*aa = data
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (aa AccAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(aa.String())
}
// MarshalYAML marshals to YAML using Bech32.
func (aa AccAddress) MarshalYAML() (interface{}, error) {
return aa.String(), nil
}
// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding.
func (aa *AccAddress) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*aa = AccAddress{}
return nil
}
aa2, err := AccAddressFromBech32(s)
if err != nil {
return err
}
*aa = aa2
return nil
}
// UnmarshalYAML unmarshals from JSON assuming Bech32 encoding.
func (aa *AccAddress) UnmarshalYAML(data []byte) error {
var s string
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*aa = AccAddress{}
return nil
}
aa2, err := AccAddressFromBech32(s)
if err != nil {
return err
}
*aa = aa2
return nil
}
// Bytes returns the raw address bytes.
func (aa AccAddress) Bytes() []byte {
return aa
}
// String implements the Stringer interface.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func (aa AccAddress) String() string {
if aa.Empty() {
return ""
}
key := conv.UnsafeBytesToStr(aa)
if IsAddrCacheEnabled() {
accAddrMu.Lock()
defer accAddrMu.Unlock()
addr, ok := accAddrCache.Get(key)
if ok {
return addr.(string)
}
}
return cacheBech32Addr(GetConfig().GetBech32AccountAddrPrefix(), aa, accAddrCache, key)
}
// Format implements the fmt.Formatter interface.
func (aa AccAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
_, _ = s.Write([]byte(aa.String()))
case 'p':
_, _ = s.Write([]byte(fmt.Sprintf("%p", aa)))
default:
_, _ = s.Write([]byte(fmt.Sprintf("%X", []byte(aa))))
}
}
// ----------------------------------------------------------------------------
// validator operator
// ----------------------------------------------------------------------------
// ValAddress defines a wrapper around bytes meant to present a validator's
// operator. When marshaled to a string or JSON, it uses Bech32.
type ValAddress []byte
// ValAddressFromHex creates a ValAddress from a hex string.
func ValAddressFromHex(address string) (addr ValAddress, err error) {
bz, err := addressBytesFromHexString(address)
return ValAddress(bz), err
}
// ValAddressFromBech32 creates a ValAddress from a Bech32 string.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func ValAddressFromBech32(address string) (addr ValAddress, err error) {
bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix()
addrCdc := addresscodec.NewBech32Codec(bech32PrefixValAddr)
return addrCdc.StringToBytes(address)
}
// MustValAddressFromBech32 calls ValAddressFromBech32 and panics on error.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func MustValAddressFromBech32(address string) ValAddress {
addr, err := ValAddressFromBech32(address)
if err != nil {
panic(err)
}
return addr
}
// Returns boolean for whether two ValAddresses are Equal
func (va ValAddress) Equals(va2 Address) bool {
if va.Empty() && va2.Empty() {
return true
}
return bytes.Equal(va.Bytes(), va2.Bytes())
}
// Returns boolean for whether an ValAddress is empty
func (va ValAddress) Empty() bool {
return len(va) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (va ValAddress) Marshal() ([]byte, error) {
return va, nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (va *ValAddress) Unmarshal(data []byte) error {
*va = data
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (va ValAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(va.String())
}
// MarshalYAML marshals to YAML using Bech32.
func (va ValAddress) MarshalYAML() (interface{}, error) {
return va.String(), nil
}
// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding.
func (va *ValAddress) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*va = ValAddress{}
return nil
}
va2, err := ValAddressFromBech32(s)
if err != nil {
return err
}
*va = va2
return nil
}
// UnmarshalYAML unmarshals from YAML assuming Bech32 encoding.
func (va *ValAddress) UnmarshalYAML(data []byte) error {
var s string
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*va = ValAddress{}
return nil
}
va2, err := ValAddressFromBech32(s)
if err != nil {
return err
}
*va = va2
return nil
}
// Bytes returns the raw address bytes.
func (va ValAddress) Bytes() []byte {
return va
}
// String implements the Stringer interface.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func (va ValAddress) String() string {
if va.Empty() {
return ""
}
key := conv.UnsafeBytesToStr(va)
if IsAddrCacheEnabled() {
valAddrMu.Lock()
defer valAddrMu.Unlock()
addr, ok := valAddrCache.Get(key)
if ok {
return addr.(string)
}
}
return cacheBech32Addr(GetConfig().GetBech32ValidatorAddrPrefix(), va, valAddrCache, key)
}
// Format implements the fmt.Formatter interface.
func (va ValAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
_, _ = s.Write([]byte(va.String()))
case 'p':
_, _ = s.Write([]byte(fmt.Sprintf("%p", va)))
default:
_, _ = s.Write([]byte(fmt.Sprintf("%X", []byte(va))))
}
}
// ----------------------------------------------------------------------------
// consensus node
// ----------------------------------------------------------------------------
// ConsAddress defines a wrapper around bytes meant to present a consensus node.
// When marshaled to a string or JSON, it uses Bech32.
type ConsAddress []byte
// ConsAddressFromHex creates a ConsAddress from a hex string.
// Deprecated: use ConsensusAddressCodec from Staking keeper
func ConsAddressFromHex(address string) (addr ConsAddress, err error) {
bz, err := addressBytesFromHexString(address)
return ConsAddress(bz), err
}
// ConsAddressFromBech32 creates a ConsAddress from a Bech32 string.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func ConsAddressFromBech32(address string) (addr ConsAddress, err error) {
bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix()
addrCdc := addresscodec.NewBech32Codec(bech32PrefixConsAddr)
return addrCdc.StringToBytes(address)
}
// get ConsAddress from pubkey
func GetConsAddress(pubkey cryptotypes.PubKey) ConsAddress {
return ConsAddress(pubkey.Address())
}
// Returns boolean for whether two ConsAddress are Equal
func (ca ConsAddress) Equals(ca2 Address) bool {
if ca.Empty() && ca2.Empty() {
return true
}
return bytes.Equal(ca.Bytes(), ca2.Bytes())
}
// Returns boolean for whether an ConsAddress is empty
func (ca ConsAddress) Empty() bool {
return len(ca) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (ca ConsAddress) Marshal() ([]byte, error) {
return ca, nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (ca *ConsAddress) Unmarshal(data []byte) error {
*ca = data
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (ca ConsAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(ca.String())
}
// MarshalYAML marshals to YAML using Bech32.
func (ca ConsAddress) MarshalYAML() (interface{}, error) {
return ca.String(), nil
}
// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding.
func (ca *ConsAddress) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*ca = ConsAddress{}
return nil
}
ca2, err := ConsAddressFromBech32(s)
if err != nil {
return err
}
*ca = ca2
return nil
}
// UnmarshalYAML unmarshals from YAML assuming Bech32 encoding.
func (ca *ConsAddress) UnmarshalYAML(data []byte) error {
var s string
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*ca = ConsAddress{}
return nil
}
ca2, err := ConsAddressFromBech32(s)
if err != nil {
return err
}
*ca = ca2
return nil
}
// Bytes returns the raw address bytes.
func (ca ConsAddress) Bytes() []byte {
return ca
}
// String implements the Stringer interface.
// Deprecated: Use an address.Codec to convert addresses from and to string/bytes.
func (ca ConsAddress) String() string {
if ca.Empty() {
return ""
}
key := conv.UnsafeBytesToStr(ca)
if IsAddrCacheEnabled() {
consAddrMu.Lock()
defer consAddrMu.Unlock()
addr, ok := consAddrCache.Get(key)
if ok {
return addr.(string)
}
}
return cacheBech32Addr(GetConfig().GetBech32ConsensusAddrPrefix(), ca, consAddrCache, key)
}
// Bech32ifyAddressBytes returns a bech32 representation of address bytes.
// Returns an empty string if the byte slice is 0-length. Returns an error if the bech32 conversion
// fails or the prefix is empty.
func Bech32ifyAddressBytes(prefix string, bs []byte) (string, error) {
if len(bs) == 0 {
return "", nil
}
if len(prefix) == 0 {
return "", errors.New("prefix cannot be empty")
}
return bech32.ConvertAndEncode(prefix, bs)
}
// MustBech32ifyAddressBytes returns a bech32 representation of address bytes.
// Returns an empty string if the byte slice is 0-length. It panics if the bech32 conversion
// fails or the prefix is empty.
func MustBech32ifyAddressBytes(prefix string, bs []byte) string {
s, err := Bech32ifyAddressBytes(prefix, bs)
if err != nil {
panic(err)
}
return s
}
// Format implements the fmt.Formatter interface.
func (ca ConsAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
_, _ = s.Write([]byte(ca.String()))
case 'p':
_, _ = s.Write([]byte(fmt.Sprintf("%p", ca)))
default:
_, _ = s.Write([]byte(fmt.Sprintf("%X", []byte(ca))))
}
}
// ----------------------------------------------------------------------------
// auxiliary
// ----------------------------------------------------------------------------
var errBech32EmptyAddress = errors.New("decoding Bech32 address failed: must provide a non empty address")
// GetFromBech32 decodes a bytestring from a Bech32 encoded string.
func GetFromBech32(bech32str, prefix string) ([]byte, error) {
if len(bech32str) == 0 {
return nil, errBech32EmptyAddress
}
hrp, bz, err := bech32.DecodeAndConvert(bech32str)
if err != nil {
return nil, err
}
if hrp != prefix {
return nil, fmt.Errorf("invalid Bech32 prefix; expected %s, got %s", prefix, hrp)
}
return bz, nil
}
func addressBytesFromHexString(address string) ([]byte, error) {
if len(address) == 0 {
return nil, ErrEmptyHexAddress
}
return hex.DecodeString(address)
}
// cacheBech32Addr is not concurrency safe. Concurrent access to cache causes race condition.
func cacheBech32Addr(prefix string, addr []byte, cache *simplelru.LRU, cacheKey string) string {
bech32Addr, err := bech32.ConvertAndEncode(prefix, addr)
if err != nil {
panic(err)
}
if IsAddrCacheEnabled() {
cache.Add(cacheKey, bech32Addr)
}
return bech32Addr
}
// GetFullBIP44Path returns the BIP44Prefix.
func GetFullBIP44Path() string {
return fmt.Sprintf("m/%d'/%d'/0'/0/0", Purpose, CoinType)
}
package types
import (
"cosmossdk.io/core/registry"
"cosmossdk.io/core/transaction"
)
const (
// MsgInterfaceProtoName defines the protobuf name of the cosmos Msg interface
MsgInterfaceProtoName = "cosmos.base.v1beta1.Msg"
)
// RegisterLegacyAminoCodec registers the sdk message type.
func RegisterLegacyAminoCodec(registrar registry.AminoRegistrar) {
registrar.RegisterInterface((*transaction.Msg)(nil), nil)
registrar.RegisterInterface((*Tx)(nil), nil)
}
// RegisterInterfaces registers the sdk message type.
func RegisterInterfaces(registry registry.InterfaceRegistrar) {
registry.RegisterInterface(MsgInterfaceProtoName, (*Msg)(nil))
}
package types
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
"strings"
"unicode"
"cosmossdk.io/math"
)
//-----------------------------------------------------------------------------
// Coin
// NewCoin returns a new coin with a denomination and amount. It will panic if
// the amount is negative or if the denomination is invalid.
func NewCoin(denom string, amount math.Int) Coin {
coin := Coin{
Denom: denom,
Amount: amount,
}
if err := coin.Validate(); err != nil {
panic(err)
}
return coin
}
// NewInt64Coin returns a new coin with a denomination and amount. It will panic
// if the amount is negative.
func NewInt64Coin(denom string, amount int64) Coin {
return NewCoin(denom, math.NewInt(amount))
}
// String provides a human-readable representation of a coin
func (coin Coin) String() string {
return fmt.Sprintf("%v%s", coin.Amount, coin.Denom)
}
// Validate returns an error if the Coin has a negative amount or if
// the denom is invalid.
func (coin Coin) Validate() error {
if err := ValidateDenom(coin.Denom); err != nil {
return err
}
if coin.Amount.IsNil() {
return errors.New("amount is nil")
}
if coin.Amount.IsNegative() {
return fmt.Errorf("negative coin amount: %v", coin.Amount)
}
return nil
}
// IsValid returns true if the Coin has a non-negative amount and the denom is valid.
func (coin Coin) IsValid() bool {
return coin.Validate() == nil
}
// IsZero returns if this represents no money
func (coin Coin) IsZero() bool {
return coin.Amount.IsZero()
}
// IsGT returns true if they are the same type and the receiver is
// a greater value
func (coin Coin) IsGT(other Coin) bool {
if coin.Denom != other.Denom {
panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom))
}
return coin.Amount.GT(other.Amount)
}
// IsGTE returns true if they are the same type and the receiver is
// an equal or greater value
func (coin Coin) IsGTE(other Coin) bool {
if coin.Denom != other.Denom {
panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom))
}
return !coin.Amount.LT(other.Amount)
}
// IsLT returns true if they are the same type and the receiver is
// a smaller value
func (coin Coin) IsLT(other Coin) bool {
if coin.Denom != other.Denom {
panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom))
}
return coin.Amount.LT(other.Amount)
}
// IsLTE returns true if they are the same type and the receiver is
// an equal or smaller value
func (coin Coin) IsLTE(other Coin) bool {
if coin.Denom != other.Denom {
panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom))
}
return !coin.Amount.GT(other.Amount)
}
// IsEqual returns true if the two sets of Coins have the same value
// Deprecated: Use Coin.Equal instead.
func (coin Coin) IsEqual(other Coin) bool {
return coin.Equal(other)
}
// Add adds amounts of two coins with same denom. If the coins differ in denom then
// it panics.
func (coin Coin) Add(coinB Coin) Coin {
if coin.Denom != coinB.Denom {
panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, coinB.Denom))
}
return Coin{coin.Denom, coin.Amount.Add(coinB.Amount)}
}
// AddAmount adds an amount to the Coin.
func (coin Coin) AddAmount(amount math.Int) Coin {
return Coin{coin.Denom, coin.Amount.Add(amount)}
}
// Sub subtracts amounts of two coins with same denom and panics on error.
func (coin Coin) Sub(coinB Coin) Coin {
res, err := coin.SafeSub(coinB)
if err != nil {
panic(err)
}
return res
}
// SafeSub safely subtracts the amounts of two coins. It returns an error if the coins differ
// in denom or subtraction results in negative coin denom.
func (coin Coin) SafeSub(coinB Coin) (Coin, error) {
if coin.Denom != coinB.Denom {
return Coin{}, fmt.Errorf("invalid coin denoms: %s, %s", coin.Denom, coinB.Denom)
}
res := Coin{coin.Denom, coin.Amount.Sub(coinB.Amount)}
if res.IsNegative() {
return Coin{}, fmt.Errorf("negative coin amount: %s", res)
}
return res, nil
}
// SubAmount subtracts an amount from the Coin.
func (coin Coin) SubAmount(amount math.Int) Coin {
res := Coin{coin.Denom, coin.Amount.Sub(amount)}
if res.IsNegative() {
panic("negative coin amount")
}
return res
}
// IsPositive returns true if coin amount is positive.
//
// TODO: Remove once unsigned integers are used.
func (coin Coin) IsPositive() bool {
return coin.Amount.Sign() == 1
}
// IsNegative returns true if the coin amount is negative and false otherwise.
//
// TODO: Remove once unsigned integers are used.
func (coin Coin) IsNegative() bool {
return coin.Amount.Sign() == -1
}
// IsNil returns true if the coin amount is nil and false otherwise.
func (coin Coin) IsNil() bool {
return coin.Amount.BigInt() == nil
}
//-----------------------------------------------------------------------------
// Coins
// Coins is a set of Coin, one per currency
type Coins []Coin
// NewCoins constructs a new coin set. The provided coins will be sanitized by removing
// zero coins and sorting the coin set. A panic will occur if the coin set is not valid.
func NewCoins(coins ...Coin) Coins {
newCoins := sanitizeCoins(coins)
if err := newCoins.Validate(); err != nil {
panic(fmt.Errorf("invalid coin set %s: %w", newCoins, err))
}
return newCoins
}
func sanitizeCoins(coins []Coin) Coins {
newCoins := removeZeroCoins(coins)
if len(newCoins) == 0 {
return Coins{}
}
return newCoins.Sort()
}
type coinsJSON Coins
// MarshalJSON implements a custom JSON marshaller for the Coins type to allow
// nil Coins to be encoded as an empty array.
func (coins Coins) MarshalJSON() ([]byte, error) {
if coins == nil {
return json.Marshal(coinsJSON(Coins{}))
}
return json.Marshal(coinsJSON(coins))
}
func (coins Coins) String() string {
if len(coins) == 0 {
return ""
} else if len(coins) == 1 {
return coins[0].String()
}
// Build the string with a string builder
var out strings.Builder
for _, coin := range coins[:len(coins)-1] {
out.WriteString(coin.String())
out.WriteByte(',')
}
out.WriteString(coins[len(coins)-1].String())
return out.String()
}
// Validate checks that the Coins are sorted, have positive amount, with a valid and unique
// denomination (i.e no duplicates). Otherwise, it returns an error.
func (coins Coins) Validate() error {
switch len(coins) {
case 0:
return nil
case 1:
if err := ValidateDenom(coins[0].Denom); err != nil {
return err
}
if !coins[0].IsPositive() {
return fmt.Errorf("coin %s amount is not positive", coins[0])
}
return nil
default:
// check single coin case
if err := (Coins{coins[0]}).Validate(); err != nil {
return err
}
lowDenom := coins[0].Denom
for _, coin := range coins[1:] {
if err := ValidateDenom(coin.Denom); err != nil {
return err
}
if coin.Denom < lowDenom {
return fmt.Errorf("denomination %s is not sorted", coin.Denom)
}
if coin.Denom == lowDenom {
return fmt.Errorf("duplicate denomination %s", coin.Denom)
}
if !coin.IsPositive() {
return fmt.Errorf("coin %s amount is not positive", coin.Denom)
}
// we compare each coin against the last denom
lowDenom = coin.Denom
}
return nil
}
}
// IsSorted returns true when coins are sorted in ASC order by denoms.
func (coins Coins) IsSorted() bool {
for i := 1; i < len(coins); i++ {
if coins[i-1].Denom > coins[i].Denom {
return false
}
}
return true
}
// IsValid calls Validate and returns true when the Coins are sorted, have positive amount, with a
// valid and unique denomination (i.e no duplicates).
func (coins Coins) IsValid() bool {
return coins.Validate() == nil
}
// Denoms returns all denoms associated with a Coins object
func (coins Coins) Denoms() []string {
res := make([]string, len(coins))
for i, coin := range coins {
res[i] = coin.Denom
}
return res
}
// Add adds two sets of coins.
//
// e.g.
// {2A} + {A, 2B} = {3A, 2B}
// {2A} + {0B} = {2A}
//
// NOTE: Add operates under the invariant that coins are sorted by
// denominations.
//
// CONTRACT: Add will never return Coins where one Coin has a non-positive
// amount. In otherwords, IsValid will always return true.
// The function panics if `coins` or `coinsB` are not sorted (ascending).
func (coins Coins) Add(coinsB ...Coin) Coins {
return coins.safeAdd(coinsB)
}
// safeAdd will perform addition of two coins sets. If both coin sets are
// empty, then an empty set is returned. If only a single set is empty, the
// other set is returned. Otherwise, the coins are compared in order of their
// denomination and addition only occurs when the denominations match, otherwise
// the coin is simply added to the sum assuming it's not zero.
// The function panics if `coins` or `coinsB` are not sorted (ascending).
func (coins Coins) safeAdd(coinsB Coins) (coalesced Coins) {
// probably the best way will be to make Coins and interface and hide the structure
// definition (type alias)
if !coins.IsSorted() {
panic("Coins (self) must be sorted")
}
if !coinsB.IsSorted() {
panic("Wrong argument: coins must be sorted")
}
uniqCoins := make(map[string]Coin, len(coins)+len(coinsB))
// Traverse all the coins for each of the coins and coinsB.
for _, cL := range []Coins{coins, coinsB} {
for _, c := range cL {
if uc, ok := uniqCoins[c.Denom]; ok {
uniqCoins[c.Denom] = uc.Add(c)
} else {
uniqCoins[c.Denom] = c
}
}
}
coalesced = make(Coins, 0, len(uniqCoins))
for denom, c := range uniqCoins { //#nosec
if c.IsZero() {
continue
}
c.Denom = denom
coalesced = append(coalesced, c)
}
return coalesced.Sort()
}
// DenomsSubsetOf returns true if receiver's denom set
// is subset of coinsB's denoms.
func (coins Coins) DenomsSubsetOf(coinsB Coins) bool {
// more denoms in B than in receiver
if len(coins) > len(coinsB) {
return false
}
for _, coin := range coins {
if coinsB.AmountOf(coin.Denom).IsZero() {
return false
}
}
return true
}
// Sub subtracts a set of coins from another.
//
// e.g.
// {2A, 3B} - {A} = {A, 3B}
// {2A} - {0B} = {2A}
// {A, B} - {A} = {B}
//
// CONTRACT: Sub will never return Coins where one Coin has a non-positive
// amount. In otherwords, IsValid will always return true.
func (coins Coins) Sub(coinsB ...Coin) Coins {
diff, hasNeg := coins.SafeSub(coinsB...)
if hasNeg {
panic("negative coin amount")
}
return diff
}
// SafeSub performs the same arithmetic as Sub but returns a boolean if any
// negative coin amount was returned.
// The function panics if `coins` or `coinsB` are not sorted (ascending).
func (coins Coins) SafeSub(coinsB ...Coin) (Coins, bool) {
diff := coins.safeAdd(NewCoins(coinsB...).negative())
return diff, diff.IsAnyNegative()
}
// MulInt performs the scalar multiplication of coins with a `multiplier`
// All coins are multiplied by x
// e.g.
// {2A, 3B} * 2 = {4A, 6B}
// {2A} * 0 panics
// Note, if IsValid was true on Coins, IsValid stays true.
func (coins Coins) MulInt(x math.Int) Coins {
coins, ok := coins.SafeMulInt(x)
if !ok {
panic("multiplying by zero is an invalid operation on coins")
}
return coins
}
// SafeMulInt performs the same arithmetic as MulInt but returns false
// if the `multiplier` is zero because it makes IsValid return false.
func (coins Coins) SafeMulInt(x math.Int) (Coins, bool) {
if x.IsZero() {
return nil, false
}
res := make(Coins, len(coins))
for i, coin := range coins {
res[i] = NewCoin(coin.Denom, coin.Amount.Mul(x))
}
return res, true
}
// QuoInt performs the scalar division of coins with a `divisor`
// All coins are divided by x and truncated.
// e.g.
// {2A, 30B} / 2 = {1A, 15B}
// {2A} / 2 = {1A}
// {4A} / {8A} = {0A}
// {2A} / 0 = panics
// Note, if IsValid was true on Coins, IsValid stays true,
// unless the `divisor` is greater than the smallest coin amount.
func (coins Coins) QuoInt(x math.Int) Coins {
coins, ok := coins.SafeQuoInt(x)
if !ok {
panic("dividing by zero is an invalid operation on coins")
}
return coins
}
// SafeQuoInt performs the same arithmetic as QuoInt but returns an error
// if the division cannot be done.
func (coins Coins) SafeQuoInt(x math.Int) (Coins, bool) {
if x.IsZero() {
return nil, false
}
var res Coins
for _, coin := range coins {
res = append(res, NewCoin(coin.Denom, coin.Amount.Quo(x)))
}
return res, true
}
// Max takes two valid Coins inputs and returns a valid Coins result
// where for every denom D, AmountOf(D) of the result is the maximum
// of AmountOf(D) of the inputs. Note that the result might be not
// be equal to either input. For any valid Coins a, b, and c, the
// following are always true:
//
// a.IsAllLTE(a.Max(b))
// b.IsAllLTE(a.Max(b))
// a.IsAllLTE(c) && b.IsAllLTE(c) == a.Max(b).IsAllLTE(c)
// a.Add(b...).Equal(a.Min(b).Add(a.Max(b)...))
//
// E.g.
// {1A, 3B, 2C}.Max({4A, 2B, 2C}) == {4A, 3B, 2C}
// {2A, 3B}.Max({1B, 4C}) == {2A, 3B, 4C}
// {1A, 2B}.Max({}) == {1A, 2B}
func (coins Coins) Max(coinsB Coins) Coins {
max := make([]Coin, 0)
indexA, indexB := 0, 0
for indexA < len(coins) && indexB < len(coinsB) {
coinA, coinB := coins[indexA], coinsB[indexB]
switch strings.Compare(coinA.Denom, coinB.Denom) {
case -1: // denom missing from coinsB
max = append(max, coinA)
indexA++
case 0: // same denom in both
maxCoin := coinA
if coinB.Amount.GT(maxCoin.Amount) {
maxCoin = coinB
}
max = append(max, maxCoin)
indexA++
indexB++
case 1: // denom missing from coinsA
max = append(max, coinB)
indexB++
}
}
for ; indexA < len(coins); indexA++ {
max = append(max, coins[indexA])
}
for ; indexB < len(coinsB); indexB++ {
max = append(max, coinsB[indexB])
}
return NewCoins(max...)
}
// Min takes two valid Coins inputs and returns a valid Coins result
// where for every denom D, AmountOf(D) of the result is the minimum
// of AmountOf(D) of the inputs. Note that the result might be not
// be equal to either input. For any valid Coins a, b, and c, the
// following are always true:
//
// a.Min(b).IsAllLTE(a)
// a.Min(b).IsAllLTE(b)
// c.IsAllLTE(a) && c.IsAllLTE(b) == c.IsAllLTE(a.Min(b))
// a.Add(b...).Equal(a.Min(b).Add(a.Max(b)...))
//
// E.g.
// {1A, 3B, 2C}.Min({4A, 2B, 2C}) == {1A, 2B, 2C}
// {2A, 3B}.Min({1B, 4C}) == {1B}
// {1A, 2B}.Min({3C}) == empty
//
// See also DecCoins.Intersect().
func (coins Coins) Min(coinsB Coins) Coins {
min := make([]Coin, 0)
for indexA, indexB := 0, 0; indexA < len(coins) && indexB < len(coinsB); {
coinA, coinB := coins[indexA], coinsB[indexB]
switch strings.Compare(coinA.Denom, coinB.Denom) {
case -1: // denom missing from coinsB
indexA++
case 0: // same denom in both
minCoin := coinA
if coinB.Amount.LT(minCoin.Amount) {
minCoin = coinB
}
if !minCoin.IsZero() {
min = append(min, minCoin)
}
indexA++
indexB++
case 1: // denom missing from coins
indexB++
}
}
return NewCoins(min...)
}
// IsAllGT returns true if for every denom in coinsB,
// the denom is present at a greater amount in coins.
func (coins Coins) IsAllGT(coinsB Coins) bool {
if len(coins) == 0 {
return false
}
if len(coinsB) == 0 {
return true
}
if !coinsB.DenomsSubsetOf(coins) {
return false
}
for _, coinB := range coinsB {
amountA, amountB := coins.AmountOf(coinB.Denom), coinB.Amount
if !amountA.GT(amountB) {
return false
}
}
return true
}
// IsAllGTE returns false if for any denom in coinsB,
// the denom is present at a smaller amount in coins;
// else returns true.
func (coins Coins) IsAllGTE(coinsB Coins) bool {
if len(coinsB) == 0 {
return true
}
if len(coins) == 0 {
return false
}
for _, coinB := range coinsB {
if coinB.Amount.GT(coins.AmountOf(coinB.Denom)) {
return false
}
}
return true
}
// IsAllLT returns True iff for every denom in coins, the denom is present at
// a smaller amount in coinsB.
func (coins Coins) IsAllLT(coinsB Coins) bool {
return coinsB.IsAllGT(coins)
}
// IsAllLTE returns true iff for every denom in coins, the denom is present at
// a smaller or equal amount in coinsB.
func (coins Coins) IsAllLTE(coinsB Coins) bool {
return coinsB.IsAllGTE(coins)
}
// IsAnyGT returns true iff for any denom in coins, the denom is present at a
// greater amount in coinsB.
//
// e.g.
// {2A, 3B}.IsAnyGT{A} = true
// {2A, 3B}.IsAnyGT{5C} = false
// {}.IsAnyGT{5C} = false
// {2A, 3B}.IsAnyGT{} = false
func (coins Coins) IsAnyGT(coinsB Coins) bool {
if len(coinsB) == 0 {
return false
}
for _, coin := range coins {
amt := coinsB.AmountOf(coin.Denom)
if coin.Amount.GT(amt) && !amt.IsZero() {
return true
}
}
return false
}
// IsAnyGTE returns true iff coins contains at least one denom that is present
// at a greater or equal amount in coinsB; it returns false otherwise.
//
// NOTE: IsAnyGTE operates under the invariant that both coin sets are sorted
// by denominations and there exists no zero coins.
func (coins Coins) IsAnyGTE(coinsB Coins) bool {
if len(coinsB) == 0 {
return false
}
for _, coin := range coins {
amt := coinsB.AmountOf(coin.Denom)
if coin.Amount.GTE(amt) && !amt.IsZero() {
return true
}
}
return false
}
// IsZero returns true if there are no coins or all coins are zero.
func (coins Coins) IsZero() bool {
for _, coin := range coins {
if !coin.IsZero() {
return false
}
}
return true
}
// Equal returns true if the two sets of Coins have the same value
func (coins Coins) Equal(coinsB Coins) bool {
if len(coins) != len(coinsB) {
return false
}
coins = coins.Sort()
coinsB = coinsB.Sort()
for i := 0; i < len(coins); i++ {
if !coins[i].Equal(coinsB[i]) {
return false
}
}
return true
}
// Empty returns true if there are no coins and false otherwise.
func (coins Coins) Empty() bool {
return len(coins) == 0
}
// AmountOf returns the amount of a denom from coins
// CONTRACT: coins must be valid (sorted).
func (coins Coins) AmountOf(denom string) math.Int {
mustValidateDenom(denom)
return coins.AmountOfNoDenomValidation(denom)
}
// AmountOfNoDenomValidation returns the amount of a denom from coins
// without validating the denomination.
// CONTRACT: coins must be valid (sorted).
func (coins Coins) AmountOfNoDenomValidation(denom string) math.Int {
if ok, c := coins.Find(denom); ok {
return c.Amount
}
return math.ZeroInt()
}
// Find returns true and coin if the denom exists in coins. Otherwise it returns false
// and a zero coin. Uses binary search.
// CONTRACT: coins must be valid (sorted).
func (coins Coins) Find(denom string) (bool, Coin) {
switch len(coins) {
case 0:
return false, Coin{}
case 1:
coin := coins[0]
if coin.Denom == denom {
return true, coin
}
return false, Coin{}
default:
midIdx := len(coins) / 2 // 2:1, 3:1, 4:2
coin := coins[midIdx]
switch {
case denom < coin.Denom:
return coins[:midIdx].Find(denom)
case denom == coin.Denom:
return true, coin
default:
return coins[midIdx+1:].Find(denom)
}
}
}
// GetDenomByIndex returns the Denom of the certain coin to make the findDup generic
func (coins Coins) GetDenomByIndex(i int) string {
return coins[i].Denom
}
// IsAllPositive returns true if there is at least one coin and all currencies
// have a positive value.
func (coins Coins) IsAllPositive() bool {
if len(coins) == 0 {
return false
}
for _, coin := range coins {
if !coin.IsPositive() {
return false
}
}
return true
}
// IsAnyNegative returns true if there is at least one coin whose amount
// is negative; returns false otherwise. It returns false if the coin set
// is empty too.
//
// TODO: Remove once unsigned integers are used.
func (coins Coins) IsAnyNegative() bool {
for _, coin := range coins {
if coin.IsNegative() {
return true
}
}
return false
}
// IsAnyNil returns true if there is at least one coin whose amount
// is nil; returns false otherwise. It returns false if the coin set
// is empty too.
func (coins Coins) IsAnyNil() bool {
for _, coin := range coins {
if coin.IsNil() {
return true
}
}
return false
}
// negative returns a set of coins with all amount negative.
//
// TODO: Remove once unsigned integers are used.
func (coins Coins) negative() Coins {
res := make([]Coin, 0, len(coins))
for _, coin := range coins {
res = append(res, Coin{
Denom: coin.Denom,
Amount: coin.Amount.Neg(),
})
}
return res
}
// removeZeroCoins removes all zero coins from the given coin set in-place.
func removeZeroCoins(coins Coins) Coins {
nonZeros := make([]Coin, 0, len(coins))
for _, coin := range coins {
if !coin.IsZero() {
nonZeros = append(nonZeros, coin)
}
}
return nonZeros
}
//-----------------------------------------------------------------------------
// Sort interface
// Len implements sort.Interface for Coins
func (coins Coins) Len() int { return len(coins) }
// Less implements sort.Interface for Coins
func (coins Coins) Less(i, j int) bool { return coins[i].Denom < coins[j].Denom }
// Swap implements sort.Interface for Coins
func (coins Coins) Swap(i, j int) { coins[i], coins[j] = coins[j], coins[i] }
var _ sort.Interface = Coins{}
// Sort is a helper function to sort the set of coins in-place
func (coins Coins) Sort() Coins {
// sort.Sort(coins) does a costly runtime copy as part of `runtime.convTSlice`
// So we avoid this heap allocation if len(coins) <= 1. In the future, we should hopefully find
// a strategy to always avoid this.
if len(coins) > 1 {
sort.Sort(coins)
}
return coins
}
var (
reDecAmt = `[[:digit:]]+(?:\.[[:digit:]]+)?|\.[[:digit:]]+`
reSpc = `[[:space:]]*`
coinDenomRegex func() string
reDnm *regexp.Regexp
reDecCoin *regexp.Regexp
)
// SetCoinDenomRegex allows for coin's custom validation by overriding the regular
// expression string used for denom validation.
func SetCoinDenomRegex(reFn func() string) {
coinDenomRegex = reFn
reDnm = regexp.MustCompile(fmt.Sprintf(`^%s$`, coinDenomRegex()))
reDecCoin = regexp.MustCompile(fmt.Sprintf(`^(%s)%s(%s)$`, reDecAmt, reSpc, coinDenomRegex()))
}
// ValidateDenom is the default validation function for Coin.Denom.
func ValidateDenom(denom string) error {
if reDnm == nil || reDecCoin == nil {
// Call the Ragel-generated function.
if !MatchDenom(denom) {
return fmt.Errorf("invalid denom: %s", denom)
}
} else if !reDnm.MatchString(denom) { // If reDnm has been initialized, use it for matching.
return fmt.Errorf("invalid denom: %s", denom)
}
return nil
}
// isValidRune checks if a given rune is a valid character for a rune.
// It returns true if the rune is a letter, digit, '/', ':', '.', '_', or '-'.
func isValidRune(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '/' || r == ':' || r == '.' || r == '_' || r == '-'
}
// MatchDenom checks if the given string is a valid denomination.
// A valid denomination must have a length between 3 and 128 characters,
// start with a letter, and only contain valid runes.
func MatchDenom(s string) bool {
length := len(s)
if length < 3 || length > 128 {
return false
}
firstRune := rune(s[0])
if !unicode.IsLetter(firstRune) {
return false
}
for _, r := range s[1:] {
if !isValidRune(r) {
return false
}
}
return true
}
func mustValidateDenom(denom string) {
if err := ValidateDenom(denom); err != nil {
panic(err)
}
}
// ParseCoinNormalized parses and normalize a cli input for one coin type, returning errors if invalid or on an empty string
// as well.
// Expected format: "{amount}{denomination}"
func ParseCoinNormalized(coinStr string) (coin Coin, err error) {
decCoin, err := ParseDecCoin(coinStr)
if err != nil {
return Coin{}, err
}
coin, _ = NewDecCoinFromDec(decCoin.Denom, decCoin.Amount).TruncateDecimal()
return coin, nil
}
// ParseCoinsNormalized will parse out a list of coins separated by commas, and normalize them by converting to the smallest
// unit. If the parsing is successful, the provided coins will be sanitized by removing zero coins and sorting the coin
// set. Lastly a validation of the coin set is executed. If the check passes, ParseCoinsNormalized will return the
// sanitized coins.
// Otherwise, it will return an error.
// If an empty string is provided to ParseCoinsNormalized, it returns nil Coins.
// ParseCoinsNormalized supports decimal coins as inputs, and truncate them to int after converted to the smallest unit.
// Expected format: "{amount0}{denomination},...,{amountN}{denominationN}"
func ParseCoinsNormalized(coinStr string) (Coins, error) {
coins, err := ParseDecCoins(coinStr)
if err != nil {
return Coins{}, err
}
return NormalizeCoins(coins), nil
}
// ----------------------------------------------------------------------------
// NormalizeCoins normalize and truncate a list of decimal coins
func NormalizeCoins(coins []DecCoin) Coins {
if coins == nil {
return nil
}
result := make([]Coin, 0, len(coins))
for _, coin := range coins {
newCoin, _ := NewDecCoinFromDec(coin.Denom, coin.Amount).TruncateDecimal()
result = append(result, newCoin)
}
return result
}
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/base/v1beta1/coin.proto
package types
import (
cosmossdk_io_math "cosmossdk.io/math"
fmt "fmt"
_ "github.com/cosmos/cosmos-proto"
_ "github.com/cosmos/cosmos-sdk/types/tx/amino"
_ "github.com/cosmos/gogoproto/gogoproto"
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
// Coin defines a token with a denomination and an amount.
//
// NOTE: The amount field is an Int which implements the custom method
// signatures required by gogoproto.
type Coin struct {
Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"`
Amount cosmossdk_io_math.Int `protobuf:"bytes,2,opt,name=amount,proto3,customtype=cosmossdk.io/math.Int" json:"amount"`
}
func (m *Coin) Reset() { *m = Coin{} }
func (*Coin) ProtoMessage() {}
func (*Coin) Descriptor() ([]byte, []int) {
return fileDescriptor_189a96714eafc2df, []int{0}
}
func (m *Coin) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Coin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Coin.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 *Coin) XXX_Merge(src proto.Message) {
xxx_messageInfo_Coin.Merge(m, src)
}
func (m *Coin) XXX_Size() int {
return m.Size()
}
func (m *Coin) XXX_DiscardUnknown() {
xxx_messageInfo_Coin.DiscardUnknown(m)
}
var xxx_messageInfo_Coin proto.InternalMessageInfo
func (m *Coin) GetDenom() string {
if m != nil {
return m.Denom
}
return ""
}
// DecCoin defines a token with a denomination and a decimal amount.
//
// NOTE: The amount field is an Dec which implements the custom method
// signatures required by gogoproto.
type DecCoin struct {
Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"`
Amount cosmossdk_io_math.LegacyDec `protobuf:"bytes,2,opt,name=amount,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"amount"`
}
func (m *DecCoin) Reset() { *m = DecCoin{} }
func (*DecCoin) ProtoMessage() {}
func (*DecCoin) Descriptor() ([]byte, []int) {
return fileDescriptor_189a96714eafc2df, []int{1}
}
func (m *DecCoin) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *DecCoin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_DecCoin.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 *DecCoin) XXX_Merge(src proto.Message) {
xxx_messageInfo_DecCoin.Merge(m, src)
}
func (m *DecCoin) XXX_Size() int {
return m.Size()
}
func (m *DecCoin) XXX_DiscardUnknown() {
xxx_messageInfo_DecCoin.DiscardUnknown(m)
}
var xxx_messageInfo_DecCoin proto.InternalMessageInfo
func (m *DecCoin) GetDenom() string {
if m != nil {
return m.Denom
}
return ""
}
func init() {
proto.RegisterType((*Coin)(nil), "cosmos.base.v1beta1.Coin")
proto.RegisterType((*DecCoin)(nil), "cosmos.base.v1beta1.DecCoin")
}
func init() { proto.RegisterFile("cosmos/base/v1beta1/coin.proto", fileDescriptor_189a96714eafc2df) }
var fileDescriptor_189a96714eafc2df = []byte{
// 294 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xce, 0x2f, 0xce,
0xcd, 0x2f, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4,
0x4f, 0xce, 0xcf, 0xcc, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x86, 0xc8, 0xeb, 0x81,
0xe4, 0xf5, 0xa0, 0xf2, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x79, 0x7d, 0x10, 0x0b, 0xa2,
0x54, 0x4a, 0x12, 0xa2, 0x34, 0x1e, 0x22, 0x01, 0xd5, 0x07, 0x91, 0x12, 0x4c, 0xcc, 0xcd, 0xcc,
0xcb, 0xd7, 0x07, 0x93, 0x10, 0x21, 0xa5, 0x1c, 0x2e, 0x16, 0xe7, 0xfc, 0xcc, 0x3c, 0x21, 0x11,
0x2e, 0xd6, 0x94, 0xd4, 0xbc, 0xfc, 0x5c, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x08, 0x47,
0xc8, 0x83, 0x8b, 0x2d, 0x31, 0x37, 0xbf, 0x34, 0xaf, 0x44, 0x82, 0x09, 0x24, 0xec, 0x64, 0x70,
0xe2, 0x9e, 0x3c, 0xc3, 0xad, 0x7b, 0xf2, 0xa2, 0x10, 0x63, 0x8b, 0x53, 0xb2, 0xf5, 0x32, 0xf3,
0xf5, 0x73, 0x13, 0x4b, 0x32, 0xf4, 0x3c, 0xf3, 0x4a, 0x2e, 0x6d, 0xd1, 0xe5, 0x82, 0xda, 0xe7,
0x99, 0x57, 0xb2, 0xe2, 0xf9, 0x06, 0x2d, 0xc6, 0x20, 0xa8, 0x7e, 0x2b, 0x96, 0x17, 0x0b, 0xe4,
0x19, 0x95, 0x0a, 0xb8, 0xd8, 0x5d, 0x52, 0x93, 0xf1, 0x58, 0xe8, 0x89, 0x66, 0xa1, 0x21, 0xd4,
0x42, 0x69, 0x4c, 0x0b, 0x7d, 0x52, 0xd3, 0x13, 0x93, 0x2b, 0x5d, 0x52, 0x93, 0x91, 0xac, 0x75,
0x49, 0x4d, 0x46, 0xb5, 0xd1, 0xc9, 0xe5, 0xc6, 0x43, 0x39, 0x86, 0x86, 0x47, 0x72, 0x0c, 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, 0xa5, 0x94, 0x9e, 0x59, 0x92, 0x51, 0x9a,
0xa4, 0x97, 0x9c, 0x9f, 0x0b, 0x0d, 0x2d, 0x28, 0xa5, 0x5b, 0x9c, 0x92, 0xad, 0x5f, 0x52, 0x59,
0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x0e, 0x2c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3a, 0xd8,
0xb7, 0xd2, 0xa7, 0x01, 0x00, 0x00,
}
func (this *Coin) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*Coin)
if !ok {
that2, ok := that.(Coin)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.Denom != that1.Denom {
return false
}
if !this.Amount.Equal(that1.Amount) {
return false
}
return true
}
func (this *DecCoin) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*DecCoin)
if !ok {
that2, ok := that.(DecCoin)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.Denom != that1.Denom {
return false
}
if !this.Amount.Equal(that1.Amount) {
return false
}
return true
}
func (m *Coin) 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 *Coin) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Coin) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size := m.Amount.Size()
i -= size
if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
i = encodeVarintCoin(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
if len(m.Denom) > 0 {
i -= len(m.Denom)
copy(dAtA[i:], m.Denom)
i = encodeVarintCoin(dAtA, i, uint64(len(m.Denom)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *DecCoin) 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 *DecCoin) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *DecCoin) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size := m.Amount.Size()
i -= size
if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
i = encodeVarintCoin(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
if len(m.Denom) > 0 {
i -= len(m.Denom)
copy(dAtA[i:], m.Denom)
i = encodeVarintCoin(dAtA, i, uint64(len(m.Denom)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintCoin(dAtA []byte, offset int, v uint64) int {
offset -= sovCoin(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *Coin) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Denom)
if l > 0 {
n += 1 + l + sovCoin(uint64(l))
}
l = m.Amount.Size()
n += 1 + l + sovCoin(uint64(l))
return n
}
func (m *DecCoin) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Denom)
if l > 0 {
n += 1 + l + sovCoin(uint64(l))
}
l = m.Amount.Size()
n += 1 + l + sovCoin(uint64(l))
return n
}
func sovCoin(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozCoin(x uint64) (n int) {
return sovCoin(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *Coin) 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 ErrIntOverflowCoin
}
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: Coin: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Coin: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowCoin
}
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 ErrInvalidLengthCoin
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthCoin
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Denom = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowCoin
}
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 ErrInvalidLengthCoin
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthCoin
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipCoin(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthCoin
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *DecCoin) 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 ErrIntOverflowCoin
}
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: DecCoin: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: DecCoin: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowCoin
}
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 ErrInvalidLengthCoin
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthCoin
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Denom = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowCoin
}
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 ErrInvalidLengthCoin
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthCoin
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipCoin(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthCoin
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipCoin(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, ErrIntOverflowCoin
}
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, ErrIntOverflowCoin
}
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, ErrIntOverflowCoin
}
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, ErrInvalidLengthCoin
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupCoin
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthCoin
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthCoin = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowCoin = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupCoin = fmt.Errorf("proto: unexpected end of group")
)
package types
import (
"encoding/binary"
"errors"
"fmt"
"time"
"cosmossdk.io/collections"
collcodec "cosmossdk.io/collections/codec"
"cosmossdk.io/math"
)
var (
// AccAddressKey follows the same semantics of collections.BytesKey.
// It just uses humanized format for the String() and EncodeJSON().
AccAddressKey collcodec.KeyCodec[AccAddress] = genericAddressKey[AccAddress]{
stringDecoder: AccAddressFromBech32,
keyType: "sdk.AccAddress",
}
// ValAddressKey follows the same semantics as AccAddressKey.
ValAddressKey collcodec.KeyCodec[ValAddress] = genericAddressKey[ValAddress]{
stringDecoder: ValAddressFromBech32,
keyType: "sdk.ValAddress",
}
// ConsAddressKey follows the same semantics as ConsAddressKey.
ConsAddressKey collcodec.KeyCodec[ConsAddress] = genericAddressKey[ConsAddress]{
stringDecoder: ConsAddressFromBech32,
keyType: "sdk.ConsAddress",
}
// IntValue represents a collections.ValueCodec to work with Int.
IntValue collcodec.ValueCodec[math.Int] = intValueCodec{}
// UintValue represents a collections.ValueCodec to work with Uint.
UintValue collcodec.ValueCodec[math.Uint] = uintValueCodec{}
// LegacyDecValue represents a collections.ValueCodec to work with LegacyDec.
LegacyDecValue collcodec.ValueCodec[math.LegacyDec] = legacyDecValueCodec{}
// TimeKey represents a collections.KeyCodec to work with time.Time
// Deprecated: exists only for state compatibility reasons, should not
// be used for new storage keys using time. Please use the time KeyCodec
// provided in the collections package.
TimeKey collcodec.KeyCodec[time.Time] = timeKeyCodec{}
// LEUint64Key is a collections KeyCodec that encodes uint64 using little endian.
// NOTE: it MUST NOT be used by other modules, distribution relies on this only for
// state backwards compatibility.
// Deprecated: use collections.Uint64Key instead.
LEUint64Key collcodec.KeyCodec[uint64] = leUint64Key{}
// LengthPrefixedBytesKey is a collections KeyCodec to work with []byte.
// Deprecated: exists only for state compatibility reasons, should not be
// used for new storage keys using []byte. Please use the BytesKey provided
// in the collections package.
LengthPrefixedBytesKey collcodec.KeyCodec[[]byte] = lengthPrefixedBytesKey{collections.BytesKey}
)
const (
Int string = "math.Int"
Uint string = "math.Uint"
LegacyDec string = "math.LegacyDec"
)
type addressUnion interface {
AccAddress | ValAddress | ConsAddress
String() string
}
type genericAddressKey[T addressUnion] struct {
stringDecoder func(string) (T, error)
keyType string
}
func (a genericAddressKey[T]) Encode(buffer []byte, key T) (int, error) {
return collections.BytesKey.Encode(buffer, key)
}
func (a genericAddressKey[T]) Decode(buffer []byte) (int, T, error) {
return collections.BytesKey.Decode(buffer)
}
func (a genericAddressKey[T]) Size(key T) int {
return collections.BytesKey.Size(key)
}
func (a genericAddressKey[T]) EncodeJSON(value T) ([]byte, error) {
return collections.StringKey.EncodeJSON(value.String())
}
func (a genericAddressKey[T]) DecodeJSON(b []byte) (v T, err error) {
s, err := collections.StringKey.DecodeJSON(b)
if err != nil {
return
}
v, err = a.stringDecoder(s)
return
}
func (a genericAddressKey[T]) Stringify(key T) string {
return key.String()
}
func (a genericAddressKey[T]) KeyType() string {
return a.keyType
}
func (a genericAddressKey[T]) EncodeNonTerminal(buffer []byte, key T) (int, error) {
return collections.BytesKey.EncodeNonTerminal(buffer, key)
}
func (a genericAddressKey[T]) DecodeNonTerminal(buffer []byte) (int, T, error) {
return collections.BytesKey.DecodeNonTerminal(buffer)
}
func (a genericAddressKey[T]) SizeNonTerminal(key T) int {
return collections.BytesKey.SizeNonTerminal(key)
}
// Deprecated: lengthPrefixedAddressKey is a special key codec used to retain state backwards compatibility
// when a generic address key (be: AccAddress, ValAddress, ConsAddress), is used as an index key.
// More docs can be found in the LengthPrefixedAddressKey function.
type lengthPrefixedAddressKey[T addressUnion] struct {
collcodec.KeyCodec[T]
}
func (g lengthPrefixedAddressKey[T]) Encode(buffer []byte, key T) (int, error) {
return g.EncodeNonTerminal(buffer, key)
}
func (g lengthPrefixedAddressKey[T]) Decode(buffer []byte) (int, T, error) {
return g.DecodeNonTerminal(buffer)
}
func (g lengthPrefixedAddressKey[T]) Size(key T) int { return g.SizeNonTerminal(key) }
func (g lengthPrefixedAddressKey[T]) KeyType() string { return "index_key/" + g.KeyCodec.KeyType() }
// Deprecated: LengthPrefixedAddressKey implements an SDK backwards compatible indexing key encoder
// for addresses.
// The status quo in the SDK is that address keys are length prefixed even when they're the
// last part of a composite key. This should never be used unless to retain state compatibility.
// For example, a composite key composed of `[string, address]` in theory would need you only to
// define a way to understand when the string part finishes, we usually do this by appending a null
// byte to the string, then when you know when the string part finishes, it's logical that the
// part which remains is the address key. In the SDK instead we prepend to the address key its
// length too.
func LengthPrefixedAddressKey[T addressUnion](keyCodec collcodec.KeyCodec[T]) collcodec.KeyCodec[T] {
return lengthPrefixedAddressKey[T]{
keyCodec,
}
}
// Deprecated: lengthPrefixedBytesKey is a special key codec used to retain state backwards compatibility
// when a bytes key is used as an index key.
type lengthPrefixedBytesKey struct {
collcodec.KeyCodec[[]byte]
}
func (g lengthPrefixedBytesKey) Encode(buffer, key []byte) (int, error) {
return g.EncodeNonTerminal(buffer, key)
}
func (g lengthPrefixedBytesKey) Decode(buffer []byte) (int, []byte, error) {
return g.DecodeNonTerminal(buffer)
}
func (g lengthPrefixedBytesKey) Size(key []byte) int {
return g.SizeNonTerminal(key)
}
func (g lengthPrefixedBytesKey) KeyType() string {
return "index_key/" + g.KeyCodec.KeyType()
}
// Collection Codecs
type intValueCodec struct{}
func (i intValueCodec) Encode(value math.Int) ([]byte, error) {
return value.Marshal()
}
func (i intValueCodec) Decode(b []byte) (math.Int, error) {
v := new(math.Int)
err := v.Unmarshal(b)
if err != nil {
return math.Int{}, err
}
return *v, nil
}
func (i intValueCodec) EncodeJSON(value math.Int) ([]byte, error) {
return value.MarshalJSON()
}
func (i intValueCodec) DecodeJSON(b []byte) (math.Int, error) {
v := new(math.Int)
err := v.UnmarshalJSON(b)
if err != nil {
return math.Int{}, err
}
return *v, nil
}
func (i intValueCodec) Stringify(value math.Int) string {
return value.String()
}
func (i intValueCodec) ValueType() string {
return Int
}
type uintValueCodec struct{}
func (i uintValueCodec) Encode(value math.Uint) ([]byte, error) {
return value.Marshal()
}
func (i uintValueCodec) Decode(b []byte) (math.Uint, error) {
v := new(math.Uint)
err := v.Unmarshal(b)
if err != nil {
return math.Uint{}, err
}
return *v, nil
}
func (i uintValueCodec) EncodeJSON(value math.Uint) ([]byte, error) {
return value.MarshalJSON()
}
func (i uintValueCodec) DecodeJSON(b []byte) (math.Uint, error) {
v := new(math.Uint)
err := v.UnmarshalJSON(b)
if err != nil {
return math.Uint{}, err
}
return *v, nil
}
func (i uintValueCodec) Stringify(value math.Uint) string {
return value.String()
}
func (i uintValueCodec) ValueType() string {
return Uint
}
type legacyDecValueCodec struct{}
func (i legacyDecValueCodec) Encode(value math.LegacyDec) ([]byte, error) {
return value.Marshal()
}
func (i legacyDecValueCodec) Decode(b []byte) (math.LegacyDec, error) {
v := new(math.LegacyDec)
err := v.Unmarshal(b)
if err != nil {
return math.LegacyDec{}, err
}
return *v, nil
}
func (i legacyDecValueCodec) EncodeJSON(value math.LegacyDec) ([]byte, error) {
return value.MarshalJSON()
}
func (i legacyDecValueCodec) DecodeJSON(b []byte) (math.LegacyDec, error) {
v := new(math.LegacyDec)
err := v.UnmarshalJSON(b)
if err != nil {
return math.LegacyDec{}, err
}
return *v, nil
}
func (i legacyDecValueCodec) Stringify(value math.LegacyDec) string {
return value.String()
}
func (i legacyDecValueCodec) ValueType() string {
return LegacyDec
}
type timeKeyCodec struct{}
func (timeKeyCodec) Encode(buffer []byte, key time.Time) (int, error) {
return copy(buffer, FormatTimeBytes(key)), nil
}
var timeSize = len(FormatTimeBytes(time.Time{}))
func (timeKeyCodec) Decode(buffer []byte) (int, time.Time, error) {
if len(buffer) != timeSize {
return 0, time.Time{}, errors.New("invalid time buffer size")
}
t, err := ParseTimeBytes(buffer)
if err != nil {
return 0, time.Time{}, err
}
return timeSize, t, nil
}
func (timeKeyCodec) Size(key time.Time) int { return timeSize }
func (timeKeyCodec) EncodeJSON(value time.Time) ([]byte, error) { return value.MarshalJSON() }
func (timeKeyCodec) DecodeJSON(b []byte) (time.Time, error) {
t := time.Time{}
err := t.UnmarshalJSON(b)
return t, err
}
func (timeKeyCodec) Stringify(key time.Time) string { return key.String() }
func (timeKeyCodec) KeyType() string { return "sdk/time.Time" }
func (t timeKeyCodec) EncodeNonTerminal(buffer []byte, key time.Time) (int, error) {
return t.Encode(buffer, key)
}
func (t timeKeyCodec) DecodeNonTerminal(buffer []byte) (int, time.Time, error) {
if len(buffer) < timeSize {
return 0, time.Time{}, fmt.Errorf("invalid time buffer size, wanted: %d at least, got: %d", timeSize, len(buffer))
}
return t.Decode(buffer[:timeSize])
}
func (t timeKeyCodec) SizeNonTerminal(key time.Time) int { return t.Size(key) }
type leUint64Key struct{}
func (l leUint64Key) Encode(buffer []byte, key uint64) (int, error) {
binary.LittleEndian.PutUint64(buffer, key)
return 8, nil
}
func (l leUint64Key) Decode(buffer []byte) (int, uint64, error) {
if size := len(buffer); size < 8 {
return 0, 0, fmt.Errorf("invalid buffer size, wanted 8 at least got %d", size)
}
return 8, binary.LittleEndian.Uint64(buffer), nil
}
func (l leUint64Key) Size(_ uint64) int { return 8 }
func (l leUint64Key) EncodeJSON(value uint64) ([]byte, error) {
return collections.Uint64Key.EncodeJSON(value)
}
func (l leUint64Key) DecodeJSON(b []byte) (uint64, error) { return collections.Uint64Key.DecodeJSON(b) }
func (l leUint64Key) Stringify(key uint64) string { return collections.Uint64Key.Stringify(key) }
func (l leUint64Key) KeyType() string { return "little-endian-uint64" }
func (l leUint64Key) EncodeNonTerminal(buffer []byte, key uint64) (int, error) {
return l.Encode(buffer, key)
}
func (l leUint64Key) DecodeNonTerminal(buffer []byte) (int, uint64, error) { return l.Decode(buffer) }
func (l leUint64Key) SizeNonTerminal(_ uint64) int { return 8 }
package types
import (
"context"
"sync"
"github.com/cosmos/cosmos-sdk/version"
)
// DefaultKeyringServiceName defines a default service name for the keyring.
const DefaultKeyringServiceName = "cosmos"
func KeyringServiceName() string {
if len(version.Name) == 0 {
return DefaultKeyringServiceName
}
return version.Name
}
// Config is the structure that holds the SDK configuration parameters.
// Deprecated: The global SDK config is deprecated and users should prefer using an address codec.
// Users must still set the global config until the Stringer interface on `AccAddress`, `ValAddress`, and `ConsAddress` is removed.
type Config struct {
bech32AddressPrefix map[string]string
mtx sync.RWMutex
sealed bool
sealedch chan struct{}
}
// cosmos-sdk wide global singleton
var (
sdkConfig *Config
initConfig sync.Once
)
// New returns a new Config with default values.
func NewConfig() *Config {
return &Config{
sealedch: make(chan struct{}),
bech32AddressPrefix: map[string]string{
"account_addr": Bech32PrefixAccAddr,
"validator_addr": Bech32PrefixValAddr,
"consensus_addr": Bech32PrefixConsAddr,
"account_pub": Bech32PrefixAccPub,
"validator_pub": Bech32PrefixValPub,
"consensus_pub": Bech32PrefixConsPub,
},
}
}
// GetConfig returns the config instance for the SDK.
func GetConfig() *Config {
initConfig.Do(func() {
sdkConfig = NewConfig()
})
return sdkConfig
}
// GetSealedConfig returns the config instance for the SDK if/once it is sealed.
func GetSealedConfig(ctx context.Context) (*Config, error) {
config := GetConfig()
select {
case <-config.sealedch:
return config, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (config *Config) assertNotSealed() {
config.mtx.RLock()
defer config.mtx.RUnlock()
if config.sealed {
panic("Config is sealed")
}
}
// SetBech32PrefixForAccount builds the Config with Bech32 addressPrefix and publKeyPrefix for accounts
// and returns the config instance
func (config *Config) SetBech32PrefixForAccount(addressPrefix, pubKeyPrefix string) {
config.assertNotSealed()
config.bech32AddressPrefix["account_addr"] = addressPrefix
config.bech32AddressPrefix["account_pub"] = pubKeyPrefix
}
// SetBech32PrefixForValidator builds the Config with Bech32 addressPrefix and publKeyPrefix for validators
//
// and returns the config instance
func (config *Config) SetBech32PrefixForValidator(addressPrefix, pubKeyPrefix string) {
config.assertNotSealed()
config.bech32AddressPrefix["validator_addr"] = addressPrefix
config.bech32AddressPrefix["validator_pub"] = pubKeyPrefix
}
// SetBech32PrefixForConsensusNode builds the Config with Bech32 addressPrefix and publKeyPrefix for consensus nodes
// and returns the config instance
func (config *Config) SetBech32PrefixForConsensusNode(addressPrefix, pubKeyPrefix string) {
config.assertNotSealed()
config.bech32AddressPrefix["consensus_addr"] = addressPrefix
config.bech32AddressPrefix["consensus_pub"] = pubKeyPrefix
}
// Seal seals the config such that the config state could not be modified further
func (config *Config) Seal() *Config {
config.mtx.Lock()
if config.sealed {
config.mtx.Unlock()
return config
}
// signal sealed after state exposed/unlocked
config.sealed = true
config.mtx.Unlock()
close(config.sealedch)
return config
}
// GetBech32AccountAddrPrefix returns the Bech32 prefix for account address
func (config *Config) GetBech32AccountAddrPrefix() string {
return config.bech32AddressPrefix["account_addr"]
}
// GetBech32ValidatorAddrPrefix returns the Bech32 prefix for validator address
func (config *Config) GetBech32ValidatorAddrPrefix() string {
return config.bech32AddressPrefix["validator_addr"]
}
// GetBech32ConsensusAddrPrefix returns the Bech32 prefix for consensus node address
func (config *Config) GetBech32ConsensusAddrPrefix() string {
return config.bech32AddressPrefix["consensus_addr"]
}
// GetBech32AccountPubPrefix returns the Bech32 prefix for account public key
func (config *Config) GetBech32AccountPubPrefix() string {
return config.bech32AddressPrefix["account_pub"]
}
// GetBech32ValidatorPubPrefix returns the Bech32 prefix for validator public key
func (config *Config) GetBech32ValidatorPubPrefix() string {
return config.bech32AddressPrefix["validator_pub"]
}
// GetBech32ConsensusPubPrefix returns the Bech32 prefix for consensus node public key
func (config *Config) GetBech32ConsensusPubPrefix() string {
return config.bech32AddressPrefix["consensus_pub"]
}
package types
import (
"context"
"time"
abci "github.com/cometbft/cometbft/api/cometbft/abci/v1"
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
"cosmossdk.io/core/comet"
"cosmossdk.io/core/header"
"cosmossdk.io/log"
"cosmossdk.io/store/gaskv"
storetypes "cosmossdk.io/store/types"
)
// ExecMode defines the execution mode which can be set on a Context.
type ExecMode uint8
// All possible execution modes.
const (
ExecModeCheck ExecMode = iota
ExecModeReCheck
ExecModeSimulate
ExecModePrepareProposal
ExecModeProcessProposal
ExecModeVoteExtension
ExecModeVerifyVoteExtension
ExecModeFinalize
)
/*
Context is an immutable object contains all information needed to
process a request.
It contains a context.Context object inside if you want to use that,
but please do not over-use it. We try to keep all data structured
and standard additions here would be better just to add to the Context struct
*/
type Context struct {
baseCtx context.Context
ms storetypes.MultiStore
header cmtproto.Header // Deprecated: Use HeaderService for height, time, and chainID and CometService for the rest
headerHash []byte // Deprecated: Use HeaderService for hash
chainID string // Deprecated: Use HeaderService for chainID and CometService for the rest
txBytes []byte
logger log.Logger
voteInfo []abci.VoteInfo // Deprecated: use Cometinfo.LastCommit.Votes instead, will be removed after 0.52
gasMeter storetypes.GasMeter
blockGasMeter storetypes.GasMeter
checkTx bool // Deprecated: use execMode instead, will be removed after 0.52
recheckTx bool // if recheckTx == true, then checkTx must also be true // Deprecated: use execMode instead, will be removed after 0.52
sigverifyTx bool // when run simulation, because the private key corresponding to the account in the genesis.json randomly generated, we must skip the sigverify.
execMode ExecMode
minGasPrice DecCoins
consParams cmtproto.ConsensusParams
eventManager EventManagerI
priority int64 // The tx priority, only relevant in CheckTx
kvGasConfig storetypes.GasConfig
transientKVGasConfig storetypes.GasConfig
streamingManager storetypes.StreamingManager
cometInfo comet.Info
headerInfo header.Info
}
// Proposed rename, not done to avoid API breakage
type Request = Context
// Read-only accessors
func (c Context) Context() context.Context { return c.baseCtx }
func (c Context) MultiStore() storetypes.MultiStore { return c.ms }
func (c Context) BlockHeight() int64 { return c.header.Height }
func (c Context) BlockTime() time.Time { return c.headerInfo.Time } // Deprecated: use HeaderInfo().Time
func (c Context) ChainID() string { return c.chainID }
func (c Context) TxBytes() []byte { return c.txBytes }
func (c Context) Logger() log.Logger { return c.logger }
func (c Context) VoteInfos() []abci.VoteInfo { return c.voteInfo }
func (c Context) GasMeter() storetypes.GasMeter { return c.gasMeter }
func (c Context) BlockGasMeter() storetypes.GasMeter { return c.blockGasMeter }
func (c Context) IsCheckTx() bool { return c.checkTx } // Deprecated: use core/transaction service instead
func (c Context) IsReCheckTx() bool { return c.recheckTx } // Deprecated: use core/transaction service instead
func (c Context) IsSigverifyTx() bool { return c.sigverifyTx }
func (c Context) ExecMode() ExecMode { return c.execMode } // Deprecated: use core/transaction service instead
func (c Context) MinGasPrices() DecCoins { return c.minGasPrice }
func (c Context) EventManager() EventManagerI { return c.eventManager }
func (c Context) Priority() int64 { return c.priority }
func (c Context) KVGasConfig() storetypes.GasConfig { return c.kvGasConfig }
func (c Context) TransientKVGasConfig() storetypes.GasConfig { return c.transientKVGasConfig }
func (c Context) StreamingManager() storetypes.StreamingManager { return c.streamingManager }
func (c Context) CometInfo() comet.Info { return c.cometInfo }
func (c Context) HeaderInfo() header.Info { return c.headerInfo }
// BlockHeader returns the header by value.
func (c Context) BlockHeader() cmtproto.Header {
return c.header
}
// HeaderHash returns a copy of the header hash obtained during abci.RequestBeginBlock
func (c Context) HeaderHash() []byte {
hash := make([]byte, len(c.headerHash))
copy(hash, c.headerHash)
return hash
}
// Deprecated: getting consensus params from the context is deprecated and will be removed after 0.52
// Querying the consensus module for the parameters is required in server/v2
func (c Context) ConsensusParams() cmtproto.ConsensusParams {
return c.consParams
}
func (c Context) Deadline() (deadline time.Time, ok bool) {
return c.baseCtx.Deadline()
}
func (c Context) Done() <-chan struct{} {
return c.baseCtx.Done()
}
func (c Context) Err() error {
return c.baseCtx.Err()
}
// create a new context
func NewContext(ms storetypes.MultiStore, isCheckTx bool, logger log.Logger) Context {
h := cmtproto.Header{}
h.Time = h.Time.UTC()
return Context{
baseCtx: context.Background(),
ms: ms,
header: h,
chainID: h.ChainID,
checkTx: isCheckTx,
sigverifyTx: true,
logger: logger,
gasMeter: storetypes.NewInfiniteGasMeter(),
minGasPrice: DecCoins{},
eventManager: NewEventManager(),
kvGasConfig: storetypes.KVGasConfig(),
transientKVGasConfig: storetypes.TransientGasConfig(),
headerInfo: header.Info{
Time: h.Time,
},
}
}
// WithContext returns a Context with an updated context.Context.
func (c Context) WithContext(ctx context.Context) Context {
c.baseCtx = ctx
return c
}
// WithMultiStore returns a Context with an updated MultiStore.
func (c Context) WithMultiStore(ms storetypes.MultiStore) Context {
c.ms = ms
return c
}
// WithBlockHeader returns a Context with an updated CometBFT block header in UTC time.
func (c Context) WithBlockHeader(header cmtproto.Header) Context {
// https://github.com/gogo/protobuf/issues/519
header.Time = header.Time.UTC()
c.header = header
// when calling withBlockheader on a new context, chainID in the struct will be empty
c.chainID = header.ChainID
return c
}
// WithHeaderHash returns a Context with an updated CometBFT block header hash.
func (c Context) WithHeaderHash(hash []byte) Context {
temp := make([]byte, len(hash))
copy(temp, hash)
c.headerHash = temp
return c
}
// WithProposer returns a Context with an updated proposer consensus address.
func (c Context) WithProposer(addr ConsAddress) Context {
newHeader := c.BlockHeader()
newHeader.ProposerAddress = addr.Bytes()
return c.WithBlockHeader(newHeader)
}
// WithBlockHeight returns a Context with an updated block height.
func (c Context) WithBlockHeight(height int64) Context {
newHeader := c.BlockHeader()
newHeader.Height = height
return c.WithBlockHeader(newHeader)
}
// WithChainID returns a Context with an updated chain identifier.
func (c Context) WithChainID(chainID string) Context {
c.chainID = chainID
return c
}
// WithTxBytes returns a Context with an updated txBytes.
func (c Context) WithTxBytes(txBytes []byte) Context {
c.txBytes = txBytes
return c
}
// WithLogger returns a Context with an updated logger.
func (c Context) WithLogger(logger log.Logger) Context {
c.logger = logger
return c
}
// WithVoteInfos returns a Context with an updated consensus VoteInfo.
// Deprecated: use WithCometinfo() instead, will be removed after 0.52
func (c Context) WithVoteInfos(voteInfo []abci.VoteInfo) Context {
c.voteInfo = voteInfo
return c
}
// WithGasMeter returns a Context with an updated transaction GasMeter.
func (c Context) WithGasMeter(meter storetypes.GasMeter) Context {
c.gasMeter = meter
return c
}
// WithBlockGasMeter returns a Context with an updated block GasMeter
func (c Context) WithBlockGasMeter(meter storetypes.GasMeter) Context {
c.blockGasMeter = meter
return c
}
// WithKVGasConfig returns a Context with an updated gas configuration for
// the KVStore
func (c Context) WithKVGasConfig(gasConfig storetypes.GasConfig) Context {
c.kvGasConfig = gasConfig
return c
}
// WithTransientKVGasConfig returns a Context with an updated gas configuration for
// the transient KVStore
func (c Context) WithTransientKVGasConfig(gasConfig storetypes.GasConfig) Context {
c.transientKVGasConfig = gasConfig
return c
}
// WithIsCheckTx enables or disables CheckTx value for verifying transactions and returns an updated Context
func (c Context) WithIsCheckTx(isCheckTx bool) Context {
c.checkTx = isCheckTx
c.execMode = ExecModeCheck
return c
}
// WithIsRecheckTx called with true will also set true on checkTx in order to
// enforce the invariant that if recheckTx = true then checkTx = true as well.
func (c Context) WithIsReCheckTx(isRecheckTx bool) Context {
if isRecheckTx {
c.checkTx = true
}
c.recheckTx = isRecheckTx
c.execMode = ExecModeReCheck
return c
}
// WithIsSigverifyTx called with true will sigverify in auth module
func (c Context) WithIsSigverifyTx(isSigverifyTx bool) Context {
c.sigverifyTx = isSigverifyTx
return c
}
// WithExecMode returns a Context with an updated ExecMode.
func (c Context) WithExecMode(m ExecMode) Context {
c.execMode = m
return c
}
// WithMinGasPrices returns a Context with an updated minimum gas price value
func (c Context) WithMinGasPrices(gasPrices DecCoins) Context {
c.minGasPrice = gasPrices
return c
}
// WithConsensusParams returns a Context with an updated consensus params
func (c Context) WithConsensusParams(params cmtproto.ConsensusParams) Context {
c.consParams = params
return c
}
// WithEventManager returns a Context with an updated event manager
func (c Context) WithEventManager(em EventManagerI) Context {
c.eventManager = em
return c
}
// WithPriority returns a Context with an updated tx priority
func (c Context) WithPriority(p int64) Context {
c.priority = p
return c
}
// WithStreamingManager returns a Context with an updated streaming manager
func (c Context) WithStreamingManager(sm storetypes.StreamingManager) Context {
c.streamingManager = sm
return c
}
// WithCometInfo returns a Context with an updated comet info
func (c Context) WithCometInfo(cometInfo comet.Info) Context {
c.cometInfo = cometInfo
return c
}
// WithHeaderInfo returns a Context with an updated header info
func (c Context) WithHeaderInfo(headerInfo header.Info) Context {
// Set time to UTC
headerInfo.Time = headerInfo.Time.UTC()
c.headerInfo = headerInfo
return c
}
// TODO: remove???
func (c Context) IsZero() bool {
return c.ms == nil
}
func (c Context) WithValue(key, value interface{}) Context {
c.baseCtx = context.WithValue(c.baseCtx, key, value)
return c
}
func (c Context) Value(key interface{}) interface{} {
if key == SdkContextKey {
return c
}
return c.baseCtx.Value(key)
}
// ----------------------------------------------------------------------------
// Store / Caching
// ----------------------------------------------------------------------------
// KVStore fetches a KVStore from the MultiStore.
func (c Context) KVStore(key storetypes.StoreKey) storetypes.KVStore {
return gaskv.NewStore(c.ms.GetKVStore(key), c.gasMeter, c.kvGasConfig)
}
// TransientStore fetches a TransientStore from the MultiStore.
func (c Context) TransientStore(key storetypes.StoreKey) storetypes.KVStore {
return gaskv.NewStore(c.ms.GetKVStore(key), c.gasMeter, c.transientKVGasConfig)
}
// CacheContext returns a new Context with the multi-store cached and a new
// EventManager. The cached context is written to the context when writeCache
// is called. Note, events are automatically emitted on the parent context's
// EventManager when the caller executes the write.
func (c Context) CacheContext() (cc Context, writeCache func()) {
cms := c.ms.CacheMultiStore()
cc = c.WithMultiStore(cms).WithEventManager(NewEventManager())
writeCache = func() {
c.EventManager().EmitEvents(cc.EventManager().Events())
cms.Write()
}
return cc, writeCache
}
var (
_ context.Context = Context{}
_ storetypes.Context = Context{}
)
// ContextKey defines a type alias for a stdlib Context key.
type ContextKey string
// SdkContextKey is the key in the context.Context which holds the sdk.Context.
const SdkContextKey ContextKey = "sdk-context"
// WrapSDKContext returns a stdlib context.Context with the provided sdk.Context's internal
// context as a value. It is useful for passing an sdk.Context through methods that take a
// stdlib context.Context parameter such as generated gRPC methods. To get the original
// sdk.Context back, call UnwrapSDKContext.
//
// Deprecated: there is no need to wrap anymore as the Cosmos SDK context implements context.Context.
func WrapSDKContext(ctx Context) context.Context {
return ctx
}
// UnwrapSDKContext retrieves a Context from a context.Context instance
// attached with WrapSDKContext. It panics if a Context was not properly
// attached
func UnwrapSDKContext(ctx context.Context) Context {
if sdkCtx, ok := ctx.(Context); ok {
return sdkCtx
}
return ctx.Value(SdkContextKey).(Context)
}
// TryUnwrapSDKContext attempts to retrieve a Context from a context.Context
func TryUnwrapSDKContext(ctx context.Context) (Context, bool) {
if sdkCtx, ok := ctx.(Context); ok {
return sdkCtx, true
}
v := ctx.Value(SdkContextKey)
if v == nil {
return Context{}, false
}
c, ok := v.(Context)
return c, ok
}
// ToSDKEvidence takes comet evidence and returns sdk evidence
func ToSDKEvidence(ev []abci.Misbehavior) []comet.Evidence {
evidence := make([]comet.Evidence, len(ev))
for i, e := range ev {
evidence[i] = comet.Evidence{
Type: comet.MisbehaviorType(e.Type),
Height: e.Height,
Time: e.Time,
TotalVotingPower: e.TotalVotingPower,
Validator: comet.Validator{
Address: e.Validator.Address,
Power: e.Validator.Power,
},
}
}
return evidence
}
// ToSDKCommitInfo takes comet commit info and returns sdk commit info
func ToSDKCommitInfo(commit abci.CommitInfo) comet.CommitInfo {
ci := comet.CommitInfo{
Round: commit.Round,
}
for _, v := range commit.Votes {
ci.Votes = append(ci.Votes, comet.VoteInfo{
Validator: comet.Validator{
Address: v.Validator.Address,
Power: v.Validator.Power,
},
BlockIDFlag: comet.BlockIDFlag(v.BlockIdFlag),
})
}
return ci
}
// ToSDKExtendedCommitInfo takes comet extended commit info and returns sdk commit info
func ToSDKExtendedCommitInfo(commit abci.ExtendedCommitInfo) comet.CommitInfo {
ci := comet.CommitInfo{
Round: commit.Round,
Votes: make([]comet.VoteInfo, len(commit.Votes)),
}
for i, v := range commit.Votes {
ci.Votes[i] = comet.VoteInfo{
Validator: comet.Validator{
Address: v.Validator.Address,
Power: v.Validator.Power,
},
BlockIDFlag: comet.BlockIDFlag(v.BlockIdFlag),
}
}
return ci
}
package types
import (
"fmt"
"sort"
"strings"
"unicode"
"cosmossdk.io/errors"
"cosmossdk.io/math"
)
// ----------------------------------------------------------------------------
// Decimal Coin
// NewDecCoin creates a new DecCoin instance from an Int.
func NewDecCoin(denom string, amount math.Int) DecCoin {
coin := NewCoin(denom, amount)
return DecCoin{
Denom: coin.Denom,
Amount: math.LegacyNewDecFromInt(coin.Amount),
}
}
// NewDecCoinFromDec creates a new DecCoin instance from a Dec.
func NewDecCoinFromDec(denom string, amount math.LegacyDec) DecCoin {
mustValidateDenom(denom)
if amount.IsNegative() {
panic(fmt.Sprintf("negative decimal coin amount: %v\n", amount))
}
return DecCoin{
Denom: denom,
Amount: amount,
}
}
// NewDecCoinFromCoin creates a new DecCoin from a Coin.
func NewDecCoinFromCoin(coin Coin) DecCoin {
if err := coin.Validate(); err != nil {
panic(err)
}
return DecCoin{
Denom: coin.Denom,
Amount: math.LegacyNewDecFromInt(coin.Amount),
}
}
// NewInt64DecCoin returns a new DecCoin with a denomination and amount. It will
// panic if the amount is negative or denom is invalid.
func NewInt64DecCoin(denom string, amount int64) DecCoin {
return NewDecCoin(denom, math.NewInt(amount))
}
// IsZero returns if the DecCoin amount is zero.
func (coin DecCoin) IsZero() bool {
return coin.Amount.IsZero()
}
// IsGTE returns true if they are the same type and the receiver is
// an equal or greater value.
func (coin DecCoin) IsGTE(other DecCoin) bool {
if coin.Denom != other.Denom {
panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom))
}
return !coin.Amount.LT(other.Amount)
}
// IsLT returns true if they are the same type and the receiver is
// a smaller value.
func (coin DecCoin) IsLT(other DecCoin) bool {
if coin.Denom != other.Denom {
panic(fmt.Sprintf("invalid coin denominations; %s, %s", coin.Denom, other.Denom))
}
return coin.Amount.LT(other.Amount)
}
// IsEqual returns true if the two sets of Coins have the same value.
// Deprecated: Use DecCoin.Equal instead.
func (coin DecCoin) IsEqual(other DecCoin) bool {
return coin.Equal(other)
}
// Add adds amounts of two decimal coins with same denom.
func (coin DecCoin) Add(coinB DecCoin) DecCoin {
if coin.Denom != coinB.Denom {
panic(fmt.Sprintf("coin denom different: %v %v\n", coin.Denom, coinB.Denom))
}
return DecCoin{coin.Denom, coin.Amount.Add(coinB.Amount)}
}
// Sub subtracts amounts of two decimal coins with same denom.
func (coin DecCoin) Sub(coinB DecCoin) DecCoin {
if coin.Denom != coinB.Denom {
panic(fmt.Sprintf("coin denom different: %v %v\n", coin.Denom, coinB.Denom))
}
res := DecCoin{coin.Denom, coin.Amount.Sub(coinB.Amount)}
if res.IsNegative() {
panic("negative decimal coin amount")
}
return res
}
// TruncateDecimal returns a Coin with a truncated decimal and a DecCoin for the
// change. Note, the change may be zero.
func (coin DecCoin) TruncateDecimal() (Coin, DecCoin) {
truncated := coin.Amount.TruncateInt()
change := coin.Amount.Sub(math.LegacyNewDecFromInt(truncated))
return NewCoin(coin.Denom, truncated), NewDecCoinFromDec(coin.Denom, change)
}
// IsPositive returns true if coin amount is positive.
//
// TODO: Remove once unsigned integers are used.
func (coin DecCoin) IsPositive() bool {
return coin.Amount.IsPositive()
}
// IsNegative returns true if the coin amount is negative and false otherwise.
//
// TODO: Remove once unsigned integers are used.
func (coin DecCoin) IsNegative() bool {
return coin.Amount.IsNegative()
}
// String implements the Stringer interface for DecCoin. It returns a
// human-readable representation of a decimal coin.
func (coin DecCoin) String() string {
return fmt.Sprintf("%v%v", coin.Amount, coin.Denom)
}
// Validate returns an error if the DecCoin has a negative amount or if the denom is invalid.
func (coin DecCoin) Validate() error {
if err := ValidateDenom(coin.Denom); err != nil {
return err
}
if coin.IsNegative() {
return fmt.Errorf("decimal coin %s amount cannot be negative", coin)
}
return nil
}
// IsValid returns true if the DecCoin has a non-negative amount and the denom is valid.
func (coin DecCoin) IsValid() bool {
return coin.Validate() == nil
}
// ----------------------------------------------------------------------------
// Decimal Coins
// DecCoins defines a slice of coins with decimal values
type DecCoins []DecCoin
// NewDecCoins constructs a new coin set with decimal values
// from DecCoins. The provided coins will be sanitized by removing
// zero coins and sorting the coin set. A panic will occur if the coin set is not valid.
func NewDecCoins(decCoins ...DecCoin) DecCoins {
newDecCoins := sanitizeDecCoins(decCoins)
if err := newDecCoins.Validate(); err != nil {
panic(fmt.Errorf("invalid coin set %s: %w", newDecCoins, err))
}
return newDecCoins
}
func sanitizeDecCoins(decCoins []DecCoin) DecCoins {
// remove zeroes
newDecCoins := removeZeroDecCoins(decCoins)
if len(newDecCoins) == 0 {
return DecCoins{}
}
return newDecCoins.Sort()
}
// NewDecCoinsFromCoins constructs a new coin set with decimal values
// from regular Coins.
func NewDecCoinsFromCoins(coins ...Coin) DecCoins {
if len(coins) == 0 {
return DecCoins{}
}
decCoins := make([]DecCoin, 0, len(coins))
newCoins := NewCoins(coins...)
for _, coin := range newCoins {
decCoins = append(decCoins, NewDecCoinFromCoin(coin))
}
return decCoins
}
// String implements the Stringer interface for DecCoins. It returns a
// human-readable representation of decimal coins.
func (coins DecCoins) String() string {
if len(coins) == 0 {
return ""
}
out := ""
for _, coin := range coins {
out += fmt.Sprintf("%v,", coin.String())
}
return out[:len(out)-1]
}
// TruncateDecimal returns the coins with truncated decimals and returns the
// change. Note, it will not return any zero-amount coins in either the truncated or
// change coins.
func (coins DecCoins) TruncateDecimal() (truncatedCoins Coins, changeCoins DecCoins) {
for _, coin := range coins {
truncated, change := coin.TruncateDecimal()
if !truncated.IsZero() {
truncatedCoins = truncatedCoins.Add(truncated)
}
if !change.IsZero() {
changeCoins = changeCoins.Add(change)
}
}
return truncatedCoins, changeCoins
}
// Add adds two sets of DecCoins.
//
// NOTE: Add operates under the invariant that coins are sorted by
// denominations.
//
// CONTRACT: Add will never return Coins where one Coin has a non-positive
// amount. In otherwords, IsValid will always return true.
func (coins DecCoins) Add(coinsB ...DecCoin) DecCoins {
return coins.safeAdd(coinsB)
}
// safeAdd will perform addition of two DecCoins sets. If both coin sets are
// empty, then an empty set is returned. If only a single set is empty, the
// other set is returned. Otherwise, the coins are compared in order of their
// denomination and addition only occurs when the denominations match, otherwise
// the coin is simply added to the sum assuming it's not zero.
func (coins DecCoins) safeAdd(coinsB DecCoins) DecCoins {
sum := make(DecCoins, 0, len(coins)+len(coinsB))
indexA, indexB := 0, 0
lenA, lenB := len(coins), len(coinsB)
for {
if indexA == lenA {
if indexB == lenB {
// return nil coins if both sets are empty
return sum
}
// return set B (excluding zero coins) if set A is empty
return append(sum, removeZeroDecCoins(coinsB[indexB:])...)
} else if indexB == lenB {
// return set A (excluding zero coins) if set B is empty
return append(sum, removeZeroDecCoins(coins[indexA:])...)
}
coinA, coinB := coins[indexA], coinsB[indexB]
switch strings.Compare(coinA.Denom, coinB.Denom) {
case -1: // coin A denom < coin B denom
if !coinA.IsZero() {
sum = append(sum, coinA)
}
indexA++
case 0: // coin A denom == coin B denom
res := coinA.Add(coinB)
if !res.IsZero() {
sum = append(sum, res)
}
indexA++
indexB++
case 1: // coin A denom > coin B denom
if !coinB.IsZero() {
sum = append(sum, coinB)
}
indexB++
}
}
}
// negative returns a set of coins with all amount negative.
func (coins DecCoins) negative() DecCoins {
res := make([]DecCoin, 0, len(coins))
for _, coin := range coins {
res = append(res, DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.Neg(),
})
}
return res
}
// Sub subtracts a set of DecCoins from another (adds the inverse).
func (coins DecCoins) Sub(coinsB DecCoins) DecCoins {
diff, hasNeg := coins.SafeSub(coinsB)
if hasNeg {
panic("negative coin amount")
}
return diff
}
// SafeSub performs the same arithmetic as Sub but returns a boolean if any
// negative coin amount was returned.
func (coins DecCoins) SafeSub(coinsB DecCoins) (DecCoins, bool) {
diff := coins.safeAdd(coinsB.negative())
return diff, diff.IsAnyNegative()
}
// Intersect will return a new set of coins which contains the minimum DecCoin
// for common denoms found in both `coins` and `coinsB`. For denoms not common
// to both `coins` and `coinsB` the minimum is considered to be 0, thus they
// are not added to the final set. In other words, trim any denom amount from
// coin which exceeds that of coinB, such that (coin.Intersect(coinB)).IsLTE(coinB).
// See also Coins.Min().
func (coins DecCoins) Intersect(coinsB DecCoins) DecCoins {
res := make([]DecCoin, len(coins))
for i, coin := range coins {
minCoin := DecCoin{
Denom: coin.Denom,
Amount: math.LegacyMinDec(coin.Amount, coinsB.AmountOf(coin.Denom)),
}
res[i] = minCoin
}
return removeZeroDecCoins(res)
}
// GetDenomByIndex returns the Denom to make the findDup generic
func (coins DecCoins) GetDenomByIndex(i int) string {
return coins[i].Denom
}
// IsAnyNegative returns true if there is at least one coin whose amount
// is negative; returns false otherwise. It returns false if the DecCoins set
// is empty too.
//
// TODO: Remove once unsigned integers are used.
func (coins DecCoins) IsAnyNegative() bool {
for _, coin := range coins {
if coin.IsNegative() {
return true
}
}
return false
}
// MulDec multiplies all the coins by a decimal.
//
// CONTRACT: No zero coins will be returned.
func (coins DecCoins) MulDec(d math.LegacyDec) DecCoins {
var res DecCoins
for _, coin := range coins {
product := DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.Mul(d),
}
if !product.IsZero() {
res = res.Add(product)
}
}
return res
}
// MulDecTruncate multiplies all the decimal coins by a decimal, truncating. It
// returns nil DecCoins if d is zero.
//
// CONTRACT: No zero coins will be returned.
func (coins DecCoins) MulDecTruncate(d math.LegacyDec) DecCoins {
if d.IsZero() {
return DecCoins{}
}
var res DecCoins
for _, coin := range coins {
product := DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.MulTruncate(d),
}
if !product.IsZero() {
res = res.Add(product)
}
}
return res
}
// QuoDec divides all the decimal coins by a decimal. It panics if d is zero.
//
// CONTRACT: No zero coins will be returned.
func (coins DecCoins) QuoDec(d math.LegacyDec) DecCoins {
if d.IsZero() {
panic("invalid zero decimal")
}
var res DecCoins
for _, coin := range coins {
quotient := DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.Quo(d),
}
if !quotient.IsZero() {
res = res.Add(quotient)
}
}
return res
}
// QuoDecTruncate divides all the decimal coins by a decimal, truncating. It
// panics if d is zero.
//
// CONTRACT: No zero coins will be returned.
func (coins DecCoins) QuoDecTruncate(d math.LegacyDec) DecCoins {
if d.IsZero() {
panic("invalid zero decimal")
}
var res DecCoins
for _, coin := range coins {
quotient := DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.QuoTruncate(d),
}
if !quotient.IsZero() {
res = res.Add(quotient)
}
}
return res
}
// Empty returns true if there are no coins and false otherwise.
func (coins DecCoins) Empty() bool {
return len(coins) == 0
}
// AmountOf returns the amount of a denom from deccoins. It panics if the denom
// is invalid.
func (coins DecCoins) AmountOf(denom string) math.LegacyDec {
mustValidateDenom(denom)
return coins.AmountOfNoValidation(denom)
}
// AmountOfNoValidation returns the amount of a denom from deccoins without checking
// the correctness of the denom.
func (coins DecCoins) AmountOfNoValidation(denom string) math.LegacyDec {
switch len(coins) {
case 0:
return math.LegacyZeroDec()
case 1:
coin := coins[0]
if coin.Denom == denom {
return coin.Amount
}
return math.LegacyZeroDec()
default:
midIdx := len(coins) / 2 // 2:1, 3:1, 4:2
coin := coins[midIdx]
switch {
case denom < coin.Denom:
return coins[:midIdx].AmountOfNoValidation(denom)
case denom == coin.Denom:
return coin.Amount
default:
return coins[midIdx+1:].AmountOfNoValidation(denom)
}
}
}
// Equal returns true if the two sets of DecCoins have the same value.
func (coins DecCoins) Equal(coinsB DecCoins) bool {
if len(coins) != len(coinsB) {
return false
}
coins = coins.Sort()
coinsB = coinsB.Sort()
for i := 0; i < len(coins); i++ {
if !coins[i].Equal(coinsB[i]) {
return false
}
}
return true
}
// IsZero returns whether all coins are zero
func (coins DecCoins) IsZero() bool {
for _, coin := range coins {
if !coin.Amount.IsZero() {
return false
}
}
return true
}
// Validate checks that the DecCoins are sorted, have positive amount, with a valid and unique
// denomination (i.e no duplicates). Otherwise, it returns an error.
func (coins DecCoins) Validate() error {
switch len(coins) {
case 0:
return nil
case 1:
if err := ValidateDenom(coins[0].Denom); err != nil {
return err
}
if !coins[0].IsPositive() {
return fmt.Errorf("coin %s amount is not positive", coins[0])
}
return nil
default:
// check single coin case
if err := (DecCoins{coins[0]}).Validate(); err != nil {
return err
}
lowDenom := coins[0].Denom
seenDenoms := make(map[string]bool)
seenDenoms[lowDenom] = true
for _, coin := range coins[1:] {
if seenDenoms[coin.Denom] {
return fmt.Errorf("duplicate denomination %s", coin.Denom)
}
if err := ValidateDenom(coin.Denom); err != nil {
return err
}
if coin.Denom <= lowDenom {
return fmt.Errorf("denomination %s is not sorted", coin.Denom)
}
if !coin.IsPositive() {
return fmt.Errorf("coin %s amount is not positive", coin.Denom)
}
// we compare each coin against the last denom
lowDenom = coin.Denom
seenDenoms[coin.Denom] = true
}
return nil
}
}
// IsValid calls Validate and returns true when the DecCoins are sorted, have positive amount, with a
// valid and unique denomination (i.e no duplicates).
func (coins DecCoins) IsValid() bool {
return coins.Validate() == nil
}
// IsAllPositive returns true if there is at least one coin and all currencies
// have a positive value.
//
// TODO: Remove once unsigned integers are used.
func (coins DecCoins) IsAllPositive() bool {
if len(coins) == 0 {
return false
}
for _, coin := range coins {
if !coin.IsPositive() {
return false
}
}
return true
}
func removeZeroDecCoins(coins DecCoins) DecCoins {
result := make([]DecCoin, 0, len(coins))
for _, coin := range coins {
if !coin.IsZero() {
result = append(result, coin)
}
}
return result
}
//-----------------------------------------------------------------------------
// Sorting
var _ sort.Interface = DecCoins{}
// Len implements sort.Interface for DecCoins
func (coins DecCoins) Len() int { return len(coins) }
// Less implements sort.Interface for DecCoins
func (coins DecCoins) Less(i, j int) bool { return coins[i].Denom < coins[j].Denom }
// Swap implements sort.Interface for DecCoins
func (coins DecCoins) Swap(i, j int) { coins[i], coins[j] = coins[j], coins[i] }
// Sort is a helper function to sort the set of decimal coins in-place.
func (coins DecCoins) Sort() DecCoins {
// sort.Sort(coins) does a costly runtime copy as part of `runtime.convTSlice`
// So we avoid this heap allocation if len(coins) <= 1. In the future, we should hopefully find
// a strategy to always avoid this.
if len(coins) > 1 {
sort.Sort(coins)
}
return coins
}
// ----------------------------------------------------------------------------
// Parsing
// ParseDecCoin parses a decimal coin from a string, returning an error if
// invalid. An empty string is considered invalid.
func ParseDecCoin(coinStr string) (coin DecCoin, err error) {
var amountStr, denomStr string
// if custom parsing has not been set, use default coin regex
if reDecCoin == nil {
amountStr, denomStr, err = ParseDecAmount(coinStr)
if err != nil {
return DecCoin{}, err
}
} else {
coinStr = strings.TrimSpace(coinStr)
matches := reDecCoin.FindStringSubmatch(coinStr)
if matches == nil {
return DecCoin{}, fmt.Errorf("invalid decimal coin expression: %s", coinStr)
}
amountStr, denomStr = matches[1], matches[2]
}
amount, err := math.LegacyNewDecFromStr(amountStr)
if err != nil {
return DecCoin{}, errors.Wrap(err, fmt.Sprintf("failed to parse decimal coin amount: %s", amountStr))
}
if err := ValidateDenom(denomStr); err != nil {
return DecCoin{}, fmt.Errorf("invalid denom cannot contain spaces: %w", err)
}
return NewDecCoinFromDec(denomStr, amount), nil
}
// ParseDecAmount parses the given string into amount, denomination.
func ParseDecAmount(coinStr string) (string, string, error) {
var amountRune, denomRune []rune
// Indicates the start of denom parsing
seenLetter := false
// Indicates we're currently parsing the amount
parsingAmount := true
for _, r := range strings.TrimSpace(coinStr) {
if parsingAmount {
if unicode.IsDigit(r) || r == '.' {
amountRune = append(amountRune, r)
} else if unicode.IsSpace(r) { // if space is seen, indicates that we have finished parsing amount
parsingAmount = false
} else if unicode.IsLetter(r) { // if letter is seen, indicates that it is the start of denom
parsingAmount = false
seenLetter = true
denomRune = append(denomRune, r)
} else { // Invalid character encountered in amount part
return "", "", fmt.Errorf("invalid character in coin string: %s", string(r))
}
} else if !seenLetter { // This logic flow is for skipping spaces between amount and denomination
if unicode.IsLetter(r) {
seenLetter = true
denomRune = append(denomRune, r)
} else if !unicode.IsSpace(r) {
// Invalid character before denomination starts
return "", "", fmt.Errorf("invalid start of denomination: %s", string(r))
}
} else {
// Parsing the denomination
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '/' || r == ':' || r == '.' || r == '_' || r == '-' {
denomRune = append(denomRune, r)
} else {
// Invalid character encountered in denomination part
return "", "", fmt.Errorf("invalid character in denomination: %s", string(r))
}
}
}
return string(amountRune), string(denomRune), nil
}
// ParseDecCoins will parse out a list of decimal coins separated by commas. If the parsing is successuful,
// the provided coins will be sanitized by removing zero coins and sorting the coin set. Lastly
// a validation of the coin set is executed. If the check passes, ParseDecCoins will return the sanitized coins.
// Otherwise it will return an error.
// If an empty string is provided to ParseDecCoins, it returns nil Coins.
// Expected format: "{amount0}{denomination},...,{amountN}{denominationN}"
func ParseDecCoins(coinsStr string) (DecCoins, error) {
coinsStr = strings.TrimSpace(coinsStr)
if len(coinsStr) == 0 {
return nil, nil
}
coinStrs := strings.Split(coinsStr, ",")
decCoins := make(DecCoins, len(coinStrs))
for i, coinStr := range coinStrs {
coin, err := ParseDecCoin(coinStr)
if err != nil {
return nil, err
}
decCoins[i] = coin
}
newDecCoins := sanitizeDecCoins(decCoins)
if err := newDecCoins.Validate(); err != nil {
return nil, err
}
return newDecCoins, nil
}
package types
import (
"encoding/json"
"fmt"
"maps"
"reflect"
"slices"
"strings"
abci "github.com/cometbft/cometbft/api/cometbft/abci/v1"
"github.com/cosmos/gogoproto/jsonpb"
"github.com/cosmos/gogoproto/proto"
"github.com/cosmos/cosmos-sdk/codec"
)
type EventManagerI interface {
Events() Events
ABCIEvents() []abci.Event
EmitTypedEvent(tev proto.Message) error
EmitTypedEvents(tevs ...proto.Message) error
EmitEvent(event Event)
EmitEvents(events Events)
}
// ----------------------------------------------------------------------------
// Event Manager
// ----------------------------------------------------------------------------
var _ EventManagerI = (*EventManager)(nil)
// EventManager implements a simple wrapper around a slice of Event objects that
// can be emitted from.
type EventManager struct {
events Events
}
func NewEventManager() *EventManager {
return &EventManager{EmptyEvents()}
}
func (em *EventManager) Events() Events { return em.events }
// EmitEvent stores a single Event object.
// Deprecated: Use EmitTypedEvent
func (em *EventManager) EmitEvent(event Event) {
em.events = em.events.AppendEvent(event)
}
// EmitEvents stores a series of Event objects.
// Deprecated: Use EmitTypedEvents
func (em *EventManager) EmitEvents(events Events) {
em.events = em.events.AppendEvents(events)
}
// ABCIEvents returns all stored Event objects as abci.Event objects.
func (em EventManager) ABCIEvents() []abci.Event {
return em.events.ToABCIEvents()
}
// EmitTypedEvent takes typed event and emits converting it into Event
func (em *EventManager) EmitTypedEvent(tev proto.Message) error {
event, err := TypedEventToEvent(tev)
if err != nil {
return err
}
em.EmitEvent(event)
return nil
}
// EmitTypedEvents takes series of typed events and emit
func (em *EventManager) EmitTypedEvents(tevs ...proto.Message) error {
events := make(Events, len(tevs))
for i, tev := range tevs {
res, err := TypedEventToEvent(tev)
if err != nil {
return err
}
events[i] = res
}
em.EmitEvents(events)
return nil
}
// TypedEventToEvent takes typed event and converts to Event object
func TypedEventToEvent(tev proto.Message) (Event, error) {
evtType := proto.MessageName(tev)
evtJSON, err := codec.ProtoMarshalJSON(tev, nil)
if err != nil {
return Event{}, err
}
var attrMap map[string]json.RawMessage
err = json.Unmarshal(evtJSON, &attrMap)
if err != nil {
return Event{}, err
}
// sort the keys to ensure the order is always the same
keys := slices.Sorted(maps.Keys(attrMap))
attrs := make([]abci.EventAttribute, 0, len(attrMap))
for _, k := range keys {
v := attrMap[k]
attrs = append(attrs, abci.EventAttribute{
Key: k,
Value: string(v),
})
}
return Event{
Type: evtType,
Attributes: attrs,
}, nil
}
// ParseTypedEvent converts abci.Event back to a typed event.
func ParseTypedEvent(event abci.Event) (proto.Message, error) {
concreteGoType := proto.MessageType(event.Type)
if concreteGoType == nil {
return nil, fmt.Errorf("failed to retrieve the message of type %q", event.Type)
}
var value reflect.Value
if concreteGoType.Kind() == reflect.Ptr {
value = reflect.New(concreteGoType.Elem())
} else {
value = reflect.Zero(concreteGoType)
}
protoMsg, ok := value.Interface().(proto.Message)
if !ok {
return nil, fmt.Errorf("%q does not implement proto.Message", event.Type)
}
attrMap := make(map[string]json.RawMessage)
for _, attr := range event.Attributes {
attrMap[attr.Key] = json.RawMessage(attr.Value)
}
attrBytes, err := json.Marshal(attrMap)
if err != nil {
return nil, err
}
unmarshaler := jsonpb.Unmarshaler{AllowUnknownFields: true}
if err := unmarshaler.Unmarshal(strings.NewReader(string(attrBytes)), protoMsg); err != nil {
return nil, err
}
return protoMsg, nil
}
// ----------------------------------------------------------------------------
// Events
// ----------------------------------------------------------------------------
type (
// Event is a type alias for an ABCI Event
Event abci.Event
// Events defines a slice of Event objects
Events []Event
)
// NewEvent creates a new Event object with a given type and slice of one or more
// attributes.
func NewEvent(ty string, attrs ...Attribute) Event {
e := Event{Type: ty}
for _, attr := range attrs {
e.Attributes = append(e.Attributes, attr.ToKVPair())
}
return e
}
// NewAttribute returns a new key/value Attribute object.
func NewAttribute(k, v string) Attribute {
return Attribute{k, v}
}
// EmptyEvents returns an empty slice of events.
func EmptyEvents() Events {
return make(Events, 0)
}
func (a Attribute) String() string {
return fmt.Sprintf("%s: %s", a.Key, a.Value)
}
// ToKVPair converts an Attribute object into a CometBFT key/value pair.
func (a Attribute) ToKVPair() abci.EventAttribute {
return abci.EventAttribute{Key: a.Key, Value: a.Value}
}
// AppendAttributes adds one or more attributes to an Event.
func (e Event) AppendAttributes(attrs ...Attribute) Event {
for _, attr := range attrs {
e.Attributes = append(e.Attributes, attr.ToKVPair())
}
return e
}
// GetAttribute returns an attribute for a given key present in an event.
// If the key is not found, the boolean value will be false.
func (e Event) GetAttribute(key string) (Attribute, bool) {
for _, attr := range e.Attributes {
if attr.Key == key {
return Attribute{Key: attr.Key, Value: attr.Value}, true
}
}
return Attribute{}, false
}
// AppendEvent adds an Event to a slice of events.
func (e Events) AppendEvent(event Event) Events {
return append(e, event)
}
// AppendEvents adds a slice of Event objects to an exist slice of Event objects.
func (e Events) AppendEvents(events Events) Events {
return append(e, events...)
}
// ToABCIEvents converts a slice of Event objects to a slice of abci.Event
// objects.
func (e Events) ToABCIEvents() []abci.Event {
res := make([]abci.Event, len(e))
for i, ev := range e {
res[i] = abci.Event{Type: ev.Type, Attributes: ev.Attributes}
}
return res
}
// GetAttributes returns all attributes matching a given key present in events.
// If the key is not found, the boolean value will be false.
func (e Events) GetAttributes(key string) ([]Attribute, bool) {
attrs := make([]Attribute, 0)
for _, event := range e {
if attr, found := event.GetAttribute(key); found {
attrs = append(attrs, attr)
}
}
return attrs, len(attrs) > 0
}
// Common event types and attribute keys
const (
EventTypeTx = "tx"
AttributeKeyAccountSequence = "acc_seq"
AttributeKeySignature = "signature"
AttributeKeyFee = "fee"
AttributeKeyFeePayer = "fee_payer"
EventTypeMessage = "message"
AttributeKeyAction = "action"
AttributeKeyModule = "module"
AttributeKeySender = "sender"
AttributeKeyAmount = "amount"
)
type (
// StringAttributes defines a slice of StringEvents objects.
StringEvents []StringEvent
)
func (se StringEvents) String() string {
var sb strings.Builder
for _, e := range se {
fmt.Fprintf(&sb, "\t\t- %s\n", e.Type)
for _, attr := range e.Attributes {
fmt.Fprintf(&sb, "\t\t\t- %s\n", attr)
}
}
return strings.TrimRight(sb.String(), "\n")
}
// StringifyEvent converts an Event object to a StringEvent object.
func StringifyEvent(e abci.Event) StringEvent {
res := StringEvent{Type: e.Type}
for _, attr := range e.Attributes {
res.Attributes = append(
res.Attributes,
Attribute{Key: attr.Key, Value: attr.Value},
)
}
return res
}
// StringifyEvents converts a slice of Event objects into a slice of StringEvent
// objects.
func StringifyEvents(events []abci.Event) StringEvents {
res := make(StringEvents, 0, len(events))
for _, e := range events {
res = append(res, StringifyEvent(e))
}
return res
}
// MarkEventsToIndex returns the set of ABCI events, where each event's attribute
// has it's index value marked based on the provided set of events to index.
func MarkEventsToIndex(events []abci.Event, indexSet map[string]struct{}) []abci.Event {
indexAll := len(indexSet) == 0
updatedEvents := make([]abci.Event, len(events))
for i, e := range events {
updatedEvent := abci.Event{
Type: e.Type,
Attributes: make([]abci.EventAttribute, len(e.Attributes)),
}
for j, attr := range e.Attributes {
_, index := indexSet[fmt.Sprintf("%s.%s", e.Type, attr.Key)]
updatedAttr := abci.EventAttribute{
Key: attr.Key,
Value: attr.Value,
Index: index || indexAll,
}
updatedEvent.Attributes[j] = updatedAttr
}
updatedEvents[i] = updatedEvent
}
return updatedEvents
}
package types
// AnteHandler authenticates transactions, before their internal messages are
// executed. The provided ctx is expected to contain all relevant information
// needed to process the transaction, e.g. fee payment information. If new data
// is required for the remainder of the AnteHandler execution, a new Context should
// be created off of the provided Context and returned as <newCtx>.
//
// When exec module is in simulation mode (ctx.ExecMode() == ExecModeSimulate), it indicates if the AnteHandler is
// being executed in simulation mode, which attempts to estimate a gas cost for the tx.
// Any state modifications made will be discarded in simulation mode.
type AnteHandler func(ctx Context, tx Tx, _ bool) (newCtx Context, err error)
// PostHandler like AnteHandler but it executes after RunMsgs. Runs on success
// or failure and enables use cases like gas refunding.
type PostHandler func(ctx Context, tx Tx, _, success bool) (newCtx Context, err error)
// AnteDecorator wraps the next AnteHandler to perform custom pre-processing.
type AnteDecorator interface {
AnteHandle(ctx Context, tx Tx, _ bool, next AnteHandler) (newCtx Context, err error)
}
// PostDecorator wraps the next PostHandler to perform custom post-processing.
type PostDecorator interface {
PostHandle(ctx Context, tx Tx, _, success bool, next PostHandler) (newCtx Context, err error)
}
// ChainAnteDecorators ChainDecorator chains AnteDecorators together with each AnteDecorator
// wrapping over the decorators further along chain and returns a single AnteHandler.
//
// NOTE: The first element is outermost decorator, while the last element is innermost
// decorator. Decorator ordering is critical since some decorators will expect
// certain checks and updates to be performed (e.g. the Context) before the decorator
// is run. These expectations should be documented clearly in a CONTRACT docline
// in the decorator's godoc.
//
// NOTE: Any application that uses GasMeter to limit transaction processing cost
// MUST set GasMeter with the FIRST AnteDecorator. Failing to do so will cause
// transactions to be processed with an infinite gasmeter and open a DOS attack vector.
// Use `ante.SetUpContextDecorator` or a custom Decorator with similar functionality.
// Returns nil when no AnteDecorator are supplied.
func ChainAnteDecorators(chain ...AnteDecorator) AnteHandler {
if len(chain) == 0 {
return nil
}
handlerChain := make([]AnteHandler, len(chain)+1)
// set the terminal AnteHandler decorator
handlerChain[len(chain)] = func(ctx Context, tx Tx, _ bool) (Context, error) {
return ctx, nil
}
for i := 0; i < len(chain); i++ {
ii := i
handlerChain[ii] = func(ctx Context, tx Tx, _ bool) (Context, error) {
return chain[ii].AnteHandle(ctx, tx, ctx.ExecMode() == ExecModeSimulate, handlerChain[ii+1])
}
}
return handlerChain[0]
}
// ChainPostDecorators chains PostDecorators together with each PostDecorator
// wrapping over the decorators further along chain and returns a single PostHandler.
//
// NOTE: The first element is outermost decorator, while the last element is innermost
// decorator. Decorator ordering is critical since some decorators will expect
// certain checks and updates to be performed (e.g. the Context) before the decorator
// is run. These expectations should be documented clearly in a CONTRACT docline
// in the decorator's godoc.
func ChainPostDecorators(chain ...PostDecorator) PostHandler {
if len(chain) == 0 {
return nil
}
handlerChain := make([]PostHandler, len(chain)+1)
// set the terminal PostHandler decorator
handlerChain[len(chain)] = func(ctx Context, tx Tx, _, success bool) (Context, error) {
return ctx, nil
}
for i := 0; i < len(chain); i++ {
ii := i
handlerChain[ii] = func(ctx Context, tx Tx, _, success bool) (Context, error) {
return chain[ii].PostHandle(ctx, tx, ctx.ExecMode() == ExecModeSimulate, success, handlerChain[ii+1])
}
}
return handlerChain[0]
}
// Terminator AnteDecorator will get added to the chain to simplify decorator code
// Don't need to check if next == nil further up the chain
//
// ______
// <((((((\\\
// / . }\
// ;--..--._|}
// (\ '--/\--' )
// \\ | '-' :'|
// \\ . -==- .-|
// \\ \.__.' \--._
// [\\ __.--| // _/'--.
// \ \\ .'-._ ('-----'/ __/ \
// \ \\ / __>| | '--. |
// \ \\ | \ | / / /
// \ '\ / \ | | _/ /
// \ \ \ | | / /
// snd \ \ \ /
//
// Deprecated: Terminator is retired (ref https://github.com/cosmos/cosmos-sdk/pull/16076).
type Terminator struct{}
// AnteHandle returns the provided Context and nil error
func (t Terminator) AnteHandle(ctx Context, _ Tx, _ bool, _ AnteHandler) (Context, error) {
return ctx, nil
}
// PostHandle returns the provided Context and nil error
func (t Terminator) PostHandle(ctx Context, _ Tx, _, _ bool, _ PostHandler) (Context, error) {
return ctx, nil
}
package types
import "fmt"
// An Invariant is a function which tests a particular invariant.
// The invariant returns a descriptive message about what happened
// and a boolean indicating whether the invariant has been broken.
// The simulator will then halt and print the logs.
type Invariant func(ctx Context) (string, bool)
// Invariants defines a group of invariants
type Invariants []Invariant
// expected interface for registering invariants
type InvariantRegistry interface {
RegisterRoute(moduleName, route string, invar Invariant)
}
// FormatInvariant returns a standardized invariant message.
func FormatInvariant(module, name, msg string) string {
return fmt.Sprintf("%s: %s invariant\n%s\n", module, name, msg)
}
package types
import "cosmossdk.io/math"
// map coins is a map representation of sdk.Coins
// intended solely for use in bulk additions.
// All serialization and iteration should be done after conversion to sdk.Coins.
type MapCoins map[string]math.Int
func NewMapCoins(coins Coins) MapCoins {
m := make(MapCoins, len(coins))
m.Add(coins...)
return m
}
func (m MapCoins) Add(coins ...Coin) {
for _, coin := range coins {
existAmt, exists := m[coin.Denom]
// TODO: Once int supports in-place arithmetic, switch this to be in-place.
if exists {
m[coin.Denom] = existAmt.Add(coin.Amount)
} else {
m[coin.Denom] = coin.Amount
}
}
}
func (m MapCoins) ToCoins() Coins {
if len(m) == 0 {
return Coins{}
}
coins := make(Coins, 0, len(m))
for denom, amount := range m {
if amount.IsZero() {
continue
}
coins = append(coins, NewCoin(denom, amount))
}
if len(coins) == 0 {
return Coins{}
}
coins.Sort()
return coins
}
package types
import (
"encoding/hex"
"encoding/json"
"strings"
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
coretypes "github.com/cometbft/cometbft/rpc/core/types"
gogoprotoany "github.com/cosmos/gogoproto/types/any"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
)
func (gi GasInfo) String() string {
bz, _ := codec.MarshalYAML(codec.NewProtoCodec(nil), &gi)
return string(bz)
}
func (r Result) String() string {
bz, _ := codec.MarshalYAML(codec.NewProtoCodec(nil), &r)
return string(bz)
}
func (r Result) GetEvents() Events {
events := make(Events, len(r.Events))
for i, e := range r.Events {
events[i] = Event(e)
}
return events
}
// ABCIMessageLogs represents a slice of ABCIMessageLog.
type ABCIMessageLogs []ABCIMessageLog
func NewABCIMessageLog(i uint32, log string, events Events) ABCIMessageLog {
return ABCIMessageLog{
MsgIndex: i,
Log: log,
Events: StringifyEvents(events.ToABCIEvents()),
}
}
// String implements the fmt.Stringer interface for the ABCIMessageLogs type.
func (logs ABCIMessageLogs) String() (str string) {
if logs != nil {
raw, err := json.Marshal(logs)
if err == nil {
str = string(raw)
}
}
return str
}
// NewResponseResultTx returns a TxResponse given a ResultTx from tendermint
func NewResponseResultTx(res *coretypes.ResultTx, anyTx *codectypes.Any, timestamp string) *TxResponse {
if res == nil {
return nil
}
parsedLogs, _ := ParseABCILogs(res.TxResult.Log)
return &TxResponse{
TxHash: res.Hash.String(),
Height: res.Height,
Codespace: res.TxResult.Codespace,
Code: res.TxResult.Code,
Data: strings.ToUpper(hex.EncodeToString(res.TxResult.Data)),
RawLog: res.TxResult.Log,
Logs: parsedLogs,
Info: res.TxResult.Info,
GasWanted: res.TxResult.GasWanted,
GasUsed: res.TxResult.GasUsed,
Tx: anyTx,
Timestamp: timestamp,
Events: res.TxResult.Events,
}
}
// NewResponseResultBlock returns a BlockResponse given a ResultBlock from CometBFT
func NewResponseResultBlock(res *coretypes.ResultBlock, timestamp string) *cmtproto.Block {
if res == nil {
return nil
}
blk, err := res.Block.ToProto()
if err != nil {
return nil
}
return &cmtproto.Block{
Header: blk.Header,
Data: blk.Data,
Evidence: blk.Evidence,
LastCommit: blk.LastCommit,
}
}
// NewResponseFormatBroadcastTx returns a TxResponse given a ResultBroadcastTx from tendermint
func NewResponseFormatBroadcastTx(res *coretypes.ResultBroadcastTx) *TxResponse {
if res == nil {
return nil
}
parsedLogs, _ := ParseABCILogs(res.Log)
return &TxResponse{
Code: res.Code,
Codespace: res.Codespace,
Data: res.Data.String(),
RawLog: res.Log,
Logs: parsedLogs,
TxHash: res.Hash.String(),
}
}
func (r TxResponse) String() string {
bz, _ := codec.MarshalYAML(codec.NewProtoCodec(nil), &r)
return string(bz)
}
// Empty returns true if the response is empty
func (r TxResponse) Empty() bool {
return r.TxHash == "" && r.Logs == nil
}
func NewSearchTxsResult(totalCount, count, page, limit uint64, txs []*TxResponse) *SearchTxsResult {
totalPages := calcTotalPages(int64(totalCount), int64(limit))
return &SearchTxsResult{
TotalCount: totalCount,
Count: count,
PageNumber: page,
PageTotal: uint64(totalPages),
Limit: limit,
Txs: txs,
}
}
func NewSearchBlocksResult(totalCount, count, page, limit int64, blocks []*cmtproto.Block) *SearchBlocksResult {
totalPages := calcTotalPages(totalCount, limit)
return &SearchBlocksResult{
TotalCount: totalCount,
Count: count,
PageNumber: page,
PageTotal: totalPages,
Limit: limit,
Blocks: blocks,
}
}
// ParseABCILogs attempts to parse a stringified ABCI tx log into a slice of
// ABCIMessageLog types. It returns an error upon JSON decoding failure.
func ParseABCILogs(logs string) (res ABCIMessageLogs, err error) {
err = json.Unmarshal([]byte(logs), &res)
return res, err
}
var _, _ gogoprotoany.UnpackInterfacesMessage = SearchTxsResult{}, TxResponse{}
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
//
// types.UnpackInterfaces needs to be called for each nested Tx because
// there are generally interfaces to unpack in Tx's
func (s SearchTxsResult) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error {
for _, tx := range s.Txs {
err := codectypes.UnpackInterfaces(tx, unpacker)
if err != nil {
return err
}
}
return nil
}
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (r TxResponse) UnpackInterfaces(unpacker gogoprotoany.AnyUnpacker) error {
if r.Tx != nil {
var tx HasMsgs
return unpacker.UnpackAny(r.Tx, &tx)
}
return nil
}
// GetTx unpacks the Tx from within a TxResponse and returns it
func (r TxResponse) GetTx() HasMsgs {
if tx, ok := r.Tx.GetCachedValue().(HasMsgs); ok {
return tx
}
return nil
}
// calculate total pages in an overflow safe manner
func calcTotalPages(totalCount, limit int64) int64 {
totalPages := int64(0)
if totalCount != 0 && limit != 0 {
if totalCount%limit > 0 {
totalPages = totalCount/limit + 1
} else {
totalPages = totalCount / limit
}
}
return totalPages
}
package types
import (
"cosmossdk.io/math"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
)
// Delay, in blocks, between when validator updates are returned to the
// consensus-engine and when they are applied. For example, if
// ValidatorUpdateDelay is set to X, and if a validator set update is
// returned with new validators at the end of block 10, then the new
// validators are expected to sign blocks beginning at block 11+X.
//
// This value is constant as this should not change without a hard fork.
// For CometBFT this should be set to 1 block, for more details see:
// https://github.com/cometbft/cometbft/blob/main/spec/abci/abci%2B%2B_basic_concepts.md#consensusblock-execution-methods
const ValidatorUpdateDelay int64 = 1
var (
// DefaultBondDenom is the default bondable coin denomination (defaults to stake)
// Overwriting this value has the side effect of changing the default denomination in genesis
DefaultBondDenom = "stake"
// DefaultPowerReduction is the default amount of staking tokens required for 1 unit of consensus-engine power
DefaultPowerReduction = math.NewIntFromUint64(1000000)
// PubKeyEd25519Type is ed25519 for type the consensus params validator pub_key_types params
PubKeyEd25519Type = "ed25519"
)
// TokensToConsensusPower - convert input tokens to potential consensus-engine power
func TokensToConsensusPower(tokens, powerReduction math.Int) int64 {
return (tokens.Quo(powerReduction)).Int64()
}
// TokensFromConsensusPower - convert input power to tokens
func TokensFromConsensusPower(power int64, powerReduction math.Int) math.Int {
return math.NewInt(power).Mul(powerReduction)
}
// ______________________________________________________________________
// Delegation & Validator Interfaces are moved here to avoid direct dependency on the staking module in expected keeper interfaces
// BondStatus is the status of a validator.
type BondStatus int32
const (
// UNSPECIFIED defines an invalid validator status.
Unspecified BondStatus = 0
// UNBONDED defines a validator that is not bonded.
Unbonded BondStatus = 1
// UNBONDING defines a validator that is unbonding.
Unbonding BondStatus = 2
// BONDED defines a validator that is bonded.
Bonded BondStatus = 3
)
// BondStatus_name is the string representation of BondStatus.
var bondStatus_name = map[int32]string{
0: "BOND_STATUS_UNSPECIFIED",
1: "BOND_STATUS_UNBONDED",
2: "BOND_STATUS_UNBONDING",
3: "BOND_STATUS_BONDED",
}
func (x BondStatus) String() string {
return bondStatus_name[int32(x)]
}
// DelegationI delegation bond for a delegated proof of stake system
type DelegationI interface {
GetDelegatorAddr() string // delegator string for the bond
GetValidatorAddr() string // validator operator address
GetShares() math.LegacyDec // amount of validator's shares held in this delegation
}
// ValidatorI expected validator functions
type ValidatorI interface {
IsJailed() bool // whether the validator is jailed
GetMoniker() string // moniker of the validator
GetStatus() BondStatus // status of the validator
IsBonded() bool // check if has a bonded status
IsUnbonded() bool // check if has status unbonded
IsUnbonding() bool // check if has status unbonding
GetOperator() string // operator address to receive/return validators coins
ConsPubKey() (cryptotypes.PubKey, error) // validation consensus pubkey (cryptotypes.PubKey)
GetConsAddr() ([]byte, error) // validation consensus address
GetTokens() math.Int // validation tokens
GetBondedTokens() math.Int // validator bonded tokens
GetConsensusPower(math.Int) int64 // validation power in CometBFT
GetCommission() math.LegacyDec // validator commission rate
GetMinSelfDelegation() math.Int // validator minimum self delegation
GetDelegatorShares() math.LegacyDec // total outstanding delegator shares
TokensFromShares(math.LegacyDec) math.LegacyDec // token worth of provided delegator shares
TokensFromSharesTruncated(math.LegacyDec) math.LegacyDec // token worth of provided delegator shares, truncated
TokensFromSharesRoundUp(math.LegacyDec) math.LegacyDec // token worth of provided delegator shares, rounded up
SharesFromTokens(amt math.Int) (math.LegacyDec, error) // shares worth of delegator's bond
SharesFromTokensTruncated(amt math.Int) (math.LegacyDec, error) // truncated shares worth of delegator's bond
}
package types
import (
"encoding/json"
"fmt"
"strings"
"time"
"google.golang.org/protobuf/reflect/protoreflect"
"cosmossdk.io/core/transaction"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
)
type (
// Msg defines the interface a transaction message needed to fulfill.
Msg = transaction.Msg
// LegacyMsg defines the interface a transaction message needed to fulfill up through
// v0.47.
LegacyMsg interface {
Msg
// GetSigners returns the addrs of signers that must sign.
// CONTRACT: All signatures must be present to be valid.
// CONTRACT: Returns addrs in some deterministic order.
GetSigners() []AccAddress
}
// Fee defines an interface for an application application-defined concrete
// transaction type to be able to set and return the transaction fee.
Fee interface {
GetGas() uint64
GetAmount() Coins
}
// Signature defines an interface for an application application-defined
// concrete transaction type to be able to set and return transaction signatures.
Signature interface {
GetPubKey() cryptotypes.PubKey
GetSignature() []byte
}
// HasMsgs defines an interface a transaction must fulfill.
HasMsgs interface {
// GetMsgs gets the all the transaction's messages.
GetMsgs() []Msg
}
// Tx defines an interface a transaction must fulfill.
Tx interface {
transaction.Tx
HasMsgs
// GetReflectMessages gets a reflected version of the transaction's messages
// that can be used by dynamic APIs. These messages should not be used for actual
// processing as they cannot be guaranteed to be what handlers are expecting, but
// they can be used for dynamically reading specific fields from the message such
// as signers or validation data. Message processors should ALWAYS use the messages
// returned by GetMsgs.
GetReflectMessages() ([]protoreflect.Message, error)
}
// FeeTx defines the interface to be implemented by Tx to use the FeeDecorators
FeeTx interface {
Tx
GetGas() uint64
GetFee() Coins
FeePayer() []byte
FeeGranter() []byte
}
// TxWithMemo must have GetMemo() method to use ValidateMemoDecorator
TxWithMemo interface {
Tx
GetMemo() string
}
// TxWithTimeoutTimeStamp extends the Tx interface by allowing a transaction to
// set a timeout timestamp.
TxWithTimeoutTimeStamp interface {
Tx
GetTimeoutTimeStamp() time.Time
}
// TxWithTimeoutHeight extends the Tx interface by allowing a transaction to
// set a height timeout.
TxWithTimeoutHeight interface {
Tx
GetTimeoutHeight() uint64
}
// TxWithUnordered extends the Tx interface by allowing a transaction to set
// the unordered field, which implicitly relies on TxWithTimeoutTimeStamp.
TxWithUnordered interface {
TxWithTimeoutTimeStamp
GetUnordered() bool
}
// HasValidateBasic defines a type that has a ValidateBasic method.
// ValidateBasic is deprecated and now facultative.
// Prefer validating messages directly in the msg server.
HasValidateBasic interface {
// ValidateBasic does a simple validation check that
// doesn't require access to any other information.
ValidateBasic() error
}
)
// TxDecoder unmarshals transaction bytes
type TxDecoder func(txBytes []byte) (Tx, error)
// TxEncoder marshals transaction to bytes
type TxEncoder func(tx Tx) ([]byte, error)
// MsgTypeURL returns the TypeURL of a `sdk.Msg`.
var MsgTypeURL = codectypes.MsgTypeURL
// GetMsgFromTypeURL returns a `sdk.Msg` message type from a type URL
func GetMsgFromTypeURL(cdc codec.Codec, input string) (Msg, error) {
var msg Msg
bz, err := json.Marshal(struct {
Type string `json:"@type"`
}{
Type: input,
})
if err != nil {
return nil, err
}
if err := cdc.UnmarshalInterfaceJSON(bz, &msg); err != nil {
return nil, fmt.Errorf("failed to determine sdk.Msg for %s URL : %w", input, err)
}
return msg, nil
}
// GetModuleNameFromTypeURL assumes that module name is the second element of the msg type URL
// e.g. "cosmos.bank.v1beta1.MsgSend" => "bank"
// It returns an empty string if the input is not a valid type URL
func GetModuleNameFromTypeURL(input string) string {
moduleName := strings.Split(input, ".")
if len(moduleName) > 1 {
return moduleName[1]
}
return ""
}
package types
import (
"encoding/binary"
"fmt"
"time"
"github.com/cosmos/cosmos-sdk/types/kv"
)
// Uint64ToBigEndian - marshals uint64 to a bigendian byte slice so it can be sorted
func Uint64ToBigEndian(i uint64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, i)
return b
}
// BigEndianToUint64 returns an uint64 from big endian encoded bytes. If encoding
// is empty, zero is returned.
func BigEndianToUint64(bz []byte) uint64 {
if len(bz) == 0 {
return 0
}
return binary.BigEndian.Uint64(bz)
}
// Slight modification of the RFC3339Nano but it right pads all zeros and drops the time zone info
const SortableTimeFormat = "2006-01-02T15:04:05.000000000"
// Formats a time.Time into a []byte that can be sorted
func FormatTimeBytes(t time.Time) []byte {
return []byte(FormatTimeString(t))
}
// Formats a time.Time into a string
func FormatTimeString(t time.Time) string {
return t.UTC().Round(0).Format(SortableTimeFormat)
}
// Parses a []byte encoded using FormatTimeKey back into a time.Time
func ParseTimeBytes(bz []byte) (time.Time, error) {
return ParseTime(bz)
}
// Parses an encoded type using FormatTimeKey back into a time.Time
func ParseTime(t any) (time.Time, error) {
var (
result time.Time
err error
)
switch t := t.(type) {
case time.Time:
result, err = t, nil
case []byte:
result, err = time.Parse(SortableTimeFormat, string(t))
case string:
result, err = time.Parse(SortableTimeFormat, t)
default:
return time.Time{}, fmt.Errorf("unexpected type %T", t)
}
if err != nil {
return result, err
}
return result.UTC().Round(0), nil
}
// copy bytes
func CopyBytes(bz []byte) (ret []byte) {
if bz == nil {
return nil
}
ret = make([]byte, len(bz))
copy(ret, bz)
return ret
}
// AppendLengthPrefixedBytes combines the slices of bytes to one slice of bytes.
func AppendLengthPrefixedBytes(args ...[]byte) []byte {
length := 0
for _, v := range args {
length += len(v)
}
res := make([]byte, length)
length = 0
for _, v := range args {
copy(res[length:length+len(v)], v)
length += len(v)
}
return res
}
// ParseLengthPrefixedBytes panics when store key length is not equal to the given length.
func ParseLengthPrefixedBytes(key []byte, startIndex, sliceLength int) ([]byte, int) {
neededLength := startIndex + sliceLength
endIndex := neededLength - 1
kv.AssertKeyAtLeastLength(key, neededLength)
byteSlice := key[startIndex:neededLength]
return byteSlice, endIndex
}