types

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2025 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

package Decimal implements a fixed-point decimal number. It is mostly a wrapper around github.com/cockroachdb/apd/v3, with some functionality that makes it easier to use in the context of Kwil. It enforces certain semantics of Postgres's decimal, such as precision and scale.

Index

Constants

View Source
const AccountIDVersion = 0
View Source
const (
	BlockVersion = 0
)
View Source
const (
	HashLen = 32
)
View Source
const MsgDescriptionMaxLength = 200

MsgDescriptionMaxLength is the max length of Description filed in TransactionBody and CallMessageBody

View Source
const (

	// NumericStr is a fixed point number.
	NumericStr = "numeric"
)
View Source
const ValidatorVersion = 0

Variables

View Source
var (
	IntType = &DataType{
		Name: intStr,
	}
	IntArrayType = ArrayType(IntType)
	TextType     = &DataType{
		Name: textStr,
	}
	TextArrayType = ArrayType(TextType)
	BoolType      = &DataType{
		Name: boolStr,
	}
	BoolArrayType = ArrayType(BoolType)
	ByteaType     = &DataType{
		Name: byteaStr,
	}
	ByteaArrayType = ArrayType(ByteaType)
	UUIDType       = &DataType{
		Name: uuidStr,
	}
	UUIDArrayType = ArrayType(UUIDType)
	// NumericType contains 1,0 metadata.
	// For type detection, users should prefer compare a datatype
	// name with the NumericStr constant.
	NumericType = &DataType{
		Name:     NumericStr,
		Metadata: [2]uint16{0, 0},
	}
	NumericArrayType = ArrayType(NumericType)
	// NullType is a special type used to denote a null value where
	// we do not yet know the type.
	NullType = &DataType{
		Name: nullStr,
	}
	NullArrayType = ArrayType(NullType)
)

declared DataType constants. We do not have one for fixed because fixed types require metadata.

View Source
var (
	// ErrTxNotFound indicates when the a transaction was not found in the
	// nodes blocks or mempool.
	ErrTxNotFound      = errors.New("transaction not found")
	ErrTxAlreadyExists = errors.New("transaction already exists")

	ErrMigrationComplete = errors.New("network is halted following migration")

	// These errors indicate a problem with the transaction itself.
	ErrWrongChain            = errors.New("wrong chain ID")
	ErrInvalidNonce          = errors.New("invalid nonce")
	ErrInvalidAmount         = errors.New("invalid amount")
	ErrInsufficientBalance   = errors.New("insufficient balance for fee or transfer")
	ErrInsufficientFee       = errors.New("insufficient fee set")
	ErrTxTimeout             = errors.New("timed out waiting for tx to be included in a block")
	ErrMempoolFull           = errors.New("mempool is full")
	ErrTxTooLarge            = errors.New("transaction size limit exceeded")
	ErrUnknownPayloadType    = errors.New("unknown payload type")
	ErrDisallowedInMigration = errors.New("transaction type not allowed during migration")
)
View Source
var ErrNotFound = errors.New("not found")
View Source
var ErrOverflow = errors.New("overflow")
View Source
var SerializationByteOrder = binary.LittleEndian

Functions

func BroadcastCodeToError added in v0.4.0

func BroadcastCodeToError(code TxCode) error

BroadcastCodeToError converts a TxCode to an error.

func CallSigText added in v0.4.0

func CallSigText(namespace, action string, payload []byte, challenge []byte) string

func CheckDecimalPrecisionAndScale added in v0.4.0

func CheckDecimalPrecisionAndScale(precision, scale uint16) error

CheckDecimalPrecisionAndScale checks if the precision and scale are valid.

func DecimalCmp added in v0.4.0

func DecimalCmp(x, y *Decimal) (int64, error)

DecimalCmp compares two decimals. It returns -1 if x < y, 0 if x == y, and 1 if x > y.

func EmptyIfNil added in v0.4.0

func EmptyIfNil(b []byte) []byte

func EncodeBlock added in v0.4.0

func EncodeBlock(block *Block) []byte

func EncodeBlockHeader added in v0.4.0

func EncodeBlockHeader(hdr *BlockHeader) []byte

func GetRawBlockTx added in v0.4.0

func GetRawBlockTx(rawBlk []byte, idx uint32) ([]byte, error)

GetRawBlockTx extracts a transaction from a serialized block by its index in the block. This allows to more efficiently extract one transaction without copying all of the transactions in the block, and it avoids hashing all of the transactions, which would be required to match by txID.

func MergeUpdates added in v0.4.0

func MergeUpdates(np *NetworkParameters, updates ParamUpdates) (err error)

func NilIfEmpty added in v0.4.0

func NilIfEmpty(b []byte) []byte

func ReadBigInt added in v0.4.0

func ReadBigInt(r io.Reader) (*big.Int, error)

ReadBigInt reads a big.Int from a reader, as serialized by WriteBigInt.

func ReadBytes added in v0.4.0

func ReadBytes(r io.Reader) ([]byte, error)

ReadBytes reads a byte slice from a reader. This expects a 32-bit length prefix as written by WriteBytes.

func ReadCompactBytes added in v0.4.0

func ReadCompactBytes(r io.Reader) ([]byte, error)

ReadCompactBytes reads a byte slice from a reader. This uses a compact length (signed varint) prefix rather than a fixed 32-bit length prefix.

func ReadCompactString added in v0.4.0

func ReadCompactString(r io.Reader) (string, error)

ReadCompactString reads a string from a reader. This expects a compact length (unsigned varint) prefix as written by WriteCompactString. Unlike ReadString, this does not pass through to ReadBytes since there is no nil string, and there is no need to use a signed varint here.

func ReadString added in v0.4.0

func ReadString(r io.Reader) (string, error)

ReadString reads a string from a reader. This expects a 32-bit length prefix as written by WriteString.

func RegisterPayload added in v0.4.0

func RegisterPayload(pType PayloadType)

RegisterPayload registers a new payload type. This should be done on application initialization. A known payload type does not require a corresponding route handler to be registered with extensions/consensus so that they become available for consensus according to chain config.

func ScanTo added in v0.4.0

func ScanTo(src []any, dst ...any) error

ScanTo scans the src values into the dst values.

func StmtSigText added in v0.4.0

func StmtSigText(stmt string, payload []byte, challenge []byte) string

func ValidateUpdates added in v0.4.0

func ValidateUpdates(pu ParamUpdates) error

func WriteBigInt added in v0.4.0

func WriteBigInt(w io.Writer, b *big.Int) error

WriteBigInt writes a serialized big.Int to a writer. Nil is kept distinct from 0. Currently non-nil values are written with their string representation from String(). This is not ideal but it's the best we can do for now given some major shortcomings fo the Bytes method of big.Int.

func WriteBytes added in v0.4.0

func WriteBytes(w io.Writer, data []byte) error

WriteBytes writes a byte slice to a writer. This uses a 32-bit length prefix to indicate how much data to read when deserializing.

func WriteCompactBytes added in v0.4.0

func WriteCompactBytes(w io.Writer, data []byte) error

WriteCompactBytes is like WriteBytes, but it uses a compact length (signed varint) prefix rather than a fixed 32-bit length prefix.

func WriteCompactString added in v0.4.0

func WriteCompactString(w io.Writer, s string) error

WriteCompactString is like WriteString, but it uses a compact length (unsigned varint) prefix rather than a fixed 32-bit length prefix. Unlike WriteString, which passes through to WriteBytes, this does not pass through to WriteCompactBytes since there is no nil string, and there is no need to use a signed varint here.

func WriteString added in v0.4.0

func WriteString(w io.Writer, s string) error

WriteString writes a string to a writer. This uses a 32-bit length prefix.

Types

type Account

type Account struct {
	ID      *AccountID `json:"id"`
	Balance *big.Int   `json:"balance"`
	Nonce   int64      `json:"nonce"`
}

type AccountID added in v0.4.0

type AccountID struct {
	Identifier HexBytes       `json:"identifier"`
	KeyType    crypto.KeyType `json:"key_type"`
}

AccountID uniquely identifies kwil accounts. It is a combination of the Identifier and the key type. Identifier can be a public key or an address.

func GetSignerAccount added in v0.4.0

func GetSignerAccount(signer auth.Signer) (*AccountID, error)

GetSignerAccount returns the account ID of the signer.

func (AccountID) Bytes added in v0.4.0

func (id AccountID) Bytes() []byte

func (*AccountID) Equals added in v0.4.0

func (a *AccountID) Equals(other *AccountID) bool

func (AccountID) MarshalBinary added in v0.4.0

func (id AccountID) MarshalBinary() ([]byte, error)

MarshalBinary serializes the Account ID. This does not error, as it uses a bytes.Buffer writer internally.

func (AccountID) PrettyString added in v0.4.0

func (a AccountID) PrettyString() string

PrettyString returns a human-readable representation of the AccountID.

func (AccountID) String added in v0.4.0

func (a AccountID) String() string

func (*AccountID) UnmarshalBinary added in v0.4.0

func (id *AccountID) UnmarshalBinary(b []byte) error

type AccountStatus

type AccountStatus uint32
const (
	AccountStatusLatest AccountStatus = iota
	AccountStatusPending
)

type AckStatus added in v0.4.0

type AckStatus int
const (
	// AckReject means the validator did not accept the proposed block and
	// responded with a NACK. This can occur due to issues like apphash mismatch,
	// validator set mismatch, consensus params mismatch, merkle root mismatch, etc.
	AckReject AckStatus = iota
	// AckAgree means the validator accepted the proposed block and
	// computed the same AppHash as the leader after processing the block.
	AckAgree
	// AckForked means the validator accepted the proposed block and
	// successfully processed it, but diverged after processing the block.
	// The leader identifies this from the app hash mismatch in the vote.
	AckForked
)

func (*AckStatus) String added in v0.4.0

func (ack *AckStatus) String() string

func (AckStatus) WasAck added in v0.4.0

func (ack AckStatus) WasAck() bool

WasAck indicates if the validator's ACK bool is true or false. In other words, if the AckStatus is AckReject. Either AckAgree or AckForked indicate that the validator accepted the block; the difference is if the app hash was the same as the leader's.

type ActionCall added in v0.4.0

type ActionCall struct {
	Namespace string
	Action    string
	Arguments []*EncodedValue
}

ActionCall models the arguments of an action call. It would be serialized into CallMessage.Body. This is not a transaction payload. See transactions.ActionExecution for the transaction payload used for executing an action.

func (ActionCall) MarshalBinary added in v0.4.0

func (ac ActionCall) MarshalBinary() ([]byte, error)

func (*ActionCall) UnmarshalBinary added in v0.4.0

func (ac *ActionCall) UnmarshalBinary(b []byte) error

type ActionExecution added in v0.4.0

type ActionExecution struct {
	Namespace string
	Action    string
	Arguments [][]*EncodedValue
}

ActionExecution is the payload that is used to execute an action

func (ActionExecution) MarshalBinary added in v0.4.0

func (a ActionExecution) MarshalBinary() ([]byte, error)

func (ActionExecution) Type added in v0.4.0

func (a ActionExecution) Type() PayloadType

func (*ActionExecution) UnmarshalBinary added in v0.4.0

func (a *ActionExecution) UnmarshalBinary(b []byte) error

type ApproveResolution added in v0.4.0

type ApproveResolution struct {
	ResolutionID *UUID
}

ApproveResolution is a payload for approving on a resolution.

func (ApproveResolution) MarshalBinary added in v0.4.0

func (v ApproveResolution) MarshalBinary() ([]byte, error)

func (*ApproveResolution) Type added in v0.4.0

func (v *ApproveResolution) Type() PayloadType

func (*ApproveResolution) UnmarshalBinary added in v0.4.0

func (v *ApproveResolution) UnmarshalBinary(bts []byte) error

type AuthenticatedQuery added in v0.4.0

type AuthenticatedQuery struct {
	// Body is the body of the actual message
	Body *RawStatement `json:"body"`

	// Challenge is a random value for call authentication with replay
	Challenge []byte

	// the type of authenticator, which will be used to derive 'identifier'
	// from the 'sender`
	AuthType string `json:"auth_type"`

	// Sender is the public key of the sender
	Sender HexBytes `json:"sender"`

	// SignatureData is the content of is the sender's signature of the
	// serialized call body. This is ALWAYS set for authenticated queries.
	SignatureData []byte `json:"signature"`
}

AuthenticatedQuery represents a message that can be used to execute a SELECT query. It can be signed like a transaction or call message, however unlike a CallMessage, it MUST be signed.

func CreateAuthenticatedQuery added in v0.4.0

func CreateAuthenticatedQuery(stmt string, params map[string]any, challenge []byte, signer auth.Signer) (*AuthenticatedQuery, error)

CreateAuthenticatedQuery creates a new authenticated query message from a statement. The statement is signed by the signer, and the challenge is included in the signature for replay protection.

func (*AuthenticatedQuery) SigText added in v0.4.0

func (a *AuthenticatedQuery) SigText() (string, error)

SigText returns the text that should be signed by the signer.

type Block added in v0.4.0

type Block struct {
	Header    *BlockHeader   `json:"header"`
	Txns      []*Transaction `json:"txns"`
	Signature []byte         `json:"sig"` // Signature is the block producer's signature (leader in our model)
}

func DecodeBlock added in v0.4.0

func DecodeBlock(rawBlk []byte) (*Block, error)

func NewBlock added in v0.4.0

func NewBlock(height int64, prevHash, appHash, valSetHash, paramsHash Hash, stamp time.Time, txns []*Transaction) *Block

func (*Block) Bytes added in v0.4.0

func (b *Block) Bytes() []byte

Bytes returns the serialized block. This is equivalent to calling EncodeBlock with the block.

func (*Block) CalcMerkleRoot added in v0.4.0

func (b *Block) CalcMerkleRoot() Hash

func (*Block) Hash added in v0.4.0

func (b *Block) Hash() Hash

func (*Block) SerializeSize added in v0.4.0

func (b *Block) SerializeSize() int64

SerializeSize returns the serialized size of the block. To get the total size of all transactions in the block, use the TxnsSize method. If both sizes are required, use the Size method to get both sizes in one call.

func (*Block) Sign added in v0.4.0

func (b *Block) Sign(signer crypto.PrivateKey) error

func (*Block) Size added in v0.4.0

func (b *Block) Size() (block, txns int64)

Size returns both the total size of the serialized block, and the total size of all serialized transactions in the block.

func (*Block) TxnsSize added in v0.4.0

func (b *Block) TxnsSize() int64

TxnsSize returns the total size of all serialized transactions in the block.

func (*Block) VerifySignature added in v0.4.0

func (b *Block) VerifySignature(pubKey crypto.PublicKey) (bool, error)

type BlockExecRequest added in v0.4.0

type BlockExecRequest struct {
	Height   int64
	Block    *Block
	BlockID  Hash
	Proposer crypto.PublicKey
}

type BlockExecResult added in v0.4.0

type BlockExecResult struct {
	TxResults        []TxResult
	AppHash          Hash
	ValidatorUpdates []*Validator
	ParamUpdates     ParamUpdates
}

type BlockExecutionStatus added in v0.4.0

type BlockExecutionStatus struct {
	StartTime time.Time
	EndTime   time.Time
	Height    int64
	TxIDs     []Hash
	TxStatus  map[Hash]bool
}

type BlockHeader added in v0.4.0

type BlockHeader struct {
	Version  uint16
	Height   int64
	NumTxns  uint32
	PrevHash Hash // PrevHash is previous block's hash
	// PrevAppHash is the app hash from the execution of the previous block,
	// which corresponds to the app hash in CommitInfo for the previous block.
	PrevAppHash Hash
	Timestamp   time.Time
	MerkleRoot  Hash // Merkle tree reference to hash of all transactions for the block

	// Hash of the current validator set for the block
	ValidatorSetHash Hash

	// Hash of the network params for the block
	NetworkParamsHash Hash

	// New leader for this block if changed through some kind of offline consensus.
	// NOTE: leader updates currently can occur two ways:
	// 1. By creating the param_updates resolutions with the leader change and
	//    letting the validators vote on it. This is the preferred method but requires
	//    the leader to be online to propose a block containing the resolution related
	//    transactions.
	// 2. By using the "validators replace-leader" command. This is a temporary solution.
	//    In scenarios where the leader is offline and unrecoverable, the validators
	//    can offline agree on a new leader and issue `kwild validators promote` command
	//    to promote the new leader. It's important that the leader candidate also issues
	//    this command and become a leader and propose a block with the leader update.
	//    If enough validators agree to the change, they can accept the proposals and
	//    commit the block with the leader update. Once the block is committed, the other
	//    validators that didn't participate in the offline agreement will update their
	//    leader to the new candidate.
	NewLeader crypto.PublicKey
}

BlockHeader is the header of a block.

func DecodeBlockHeader added in v0.4.0

func DecodeBlockHeader(r io.Reader) (*BlockHeader, error)

func (*BlockHeader) Hash added in v0.4.0

func (bh *BlockHeader) Hash() Hash

func (BlockHeader) MarshalJSON added in v0.4.0

func (bh BlockHeader) MarshalJSON() ([]byte, error)

func (*BlockHeader) String added in v0.4.0

func (bh *BlockHeader) String() string

func (*BlockHeader) UnmarshalJSON added in v0.4.0

func (bh *BlockHeader) UnmarshalJSON(b []byte) error

type CallMessage added in v0.4.0

type CallMessage struct {
	// Body is the body of the actual message
	Body *CallMessageBody `json:"body"`

	// the type of authenticator, which will be used to derive 'identifier'
	// from the 'sender`
	AuthType string `json:"auth_type"`

	// Sender is the public key of the sender
	Sender HexBytes `json:"sender"`

	// SignatureData is the content of is the sender's signature of the
	// serialized call body. This is only set when using authenticated call
	// RPCs, in which case the Challenge field of the call body is also set.
	// Note that this was historically called Signature, which was an
	// *auth.Signature struct, but it is now a []byte that represents just the
	// signature data since the type is already in the AuthType field above.
	SignatureData []byte `json:"signature"`
}

CallMessage represents a message could be used to call an action. This is meant to work like transactions.Transaction, except that it is not a transaction.

func CreateCallMessage added in v0.4.0

func CreateCallMessage(ac *ActionCall, challenge []byte, signer auth.Signer) (*CallMessage, error)

CreateCallMessage creates a new call message from a ActionCall payload. If a signer is provided, the sender and authenticator type are set. If a challenge is also provided, it will also sign a serialization of the request that includes the challenge for replay protection. Thus, if a challenge is provided, a signer must also be provided.

type CallMessageBody added in v0.4.0

type CallMessageBody struct {
	// Payload is the payload of the message, it is RLP encoded
	Payload []byte `json:"payload"`

	// Challenge is a random value for call authentication with replay
	// protection. It is provided by the authenticating RPC server, where it is
	// generated with a csPRNG.
	Challenge []byte `json:"challenge"`
}

CallMessageBody is the body of a call message. The serialization of this body is signed when authenticated call RPCs are enabled.

type CallResult added in v0.4.0

type CallResult struct {
	QueryResult *QueryResult `json:"query_result"`
	Logs        string       `json:"logs"`
	Error       *string      `json:"error"`
}

CallResult is the result of an action call.

type ChainInfo

type ChainInfo struct {
	ChainID     string `json:"chain_id"`
	BlockHeight uint64 `json:"block_height"`
	BlockHash   Hash   `json:"block_hash"`
	Gas         bool   `json:"gas"`
}

ChainInfo describes the current status of a Kwil blockchain.

type CommitInfo added in v0.4.0

type CommitInfo struct {
	AppHash          Hash         `json:"app_hash"`
	Votes            []*VoteInfo  `json:"votes"`
	ParamUpdates     ParamUpdates `json:"param_updates,omitempty"`
	ValidatorUpdates []*Validator `json:"validator_updates,omitempty"`
}

CommitInfo includes the information about the commit of the block. Such as the signatures of the validators agreeing to the block.

func (*CommitInfo) MarshalBinary added in v0.4.0

func (ci *CommitInfo) MarshalBinary() ([]byte, error)

func (*CommitInfo) UnmarshalBinary added in v0.4.0

func (ci *CommitInfo) UnmarshalBinary(data []byte) error

type CommitRequest added in v0.4.0

type CommitRequest struct {
	Height  int64
	AppHash Hash
	Syncing bool
}

type ConsensusParamUpdateProposal added in v0.4.0

type ConsensusParamUpdateProposal struct {
	ID          UUID         `json:"id"`
	Description string       `json:"description"`
	Updates     ParamUpdates `json:"updates"`
}

type CreateResolution added in v0.4.0

type CreateResolution struct {
	Resolution *VotableEvent
}

CreateResolution is a payload for creating a new resolution.

func (CreateResolution) MarshalBinary added in v0.4.0

func (v CreateResolution) MarshalBinary() ([]byte, error)

func (*CreateResolution) Type added in v0.4.0

func (v *CreateResolution) Type() PayloadType

func (*CreateResolution) UnmarshalBinary added in v0.4.0

func (v *CreateResolution) UnmarshalBinary(bts []byte) error

type DataType added in v0.2.0

type DataType struct {
	// Name is the name of the type.
	Name string `json:"name"`
	// IsArray is true if the type is an array.
	IsArray bool `json:"is_array"`
	// Metadata is the metadata of the type.
	Metadata [2]uint16 `json:"metadata"`
}

DataType is a data type. It includes both built-in types and user-defined types.

func ArrayType added in v0.2.0

func ArrayType(t *DataType) *DataType

ArrayType creates an array type of the given type. It panics if the type is already an array.

func NewNumericType added in v0.4.0

func NewNumericType(precision, scale uint16) (*DataType, error)

NewNumericType creates a new fixed point numeric type.

func ParseDataType added in v0.4.0

func ParseDataType(s string) (*DataType, error)

ParseDataType parses a string into a data type.

func (*DataType) Clean added in v0.2.0

func (c *DataType) Clean() error

func (*DataType) Copy added in v0.2.0

func (c *DataType) Copy() *DataType

Copy returns a copy of the type.

func (*DataType) Equals added in v0.2.0

func (c *DataType) Equals(other *DataType) bool

Equals returns true if the type is equal to the other type, or if either type is null.

func (*DataType) EqualsStrict added in v0.2.0

func (c *DataType) EqualsStrict(other *DataType) bool

EqualsStrict returns true if the type is equal to the other type. The types must be exactly the same, including metadata. Unlike Equals, it will return false if one of the types is null and the other is not.

func (*DataType) HasMetadata added in v0.4.0

func (c *DataType) HasMetadata() bool

func (*DataType) IsNumeric added in v0.2.0

func (c *DataType) IsNumeric() bool

func (DataType) MarshalBinary added in v0.4.0

func (c DataType) MarshalBinary() ([]byte, error)

func (*DataType) PGScalar added in v0.4.0

func (c *DataType) PGScalar() (string, error)

PGScalar returns the scalar representation of the type in Postgres. For example, if this is of type DECIMAL(100,5)[], it will return NUMERIC(100,5).

func (*DataType) PGString added in v0.2.0

func (c *DataType) PGString() (string, error)

PGString returns the string representation of the type in Postgres.

func (DataType) SerializeSize added in v0.4.0

func (c DataType) SerializeSize() int

func (*DataType) String added in v0.2.0

func (c *DataType) String() string

String returns the string representation of the type.

func (*DataType) UnmarshalBinary added in v0.4.0

func (c *DataType) UnmarshalBinary(data []byte) error

type DatasetIdentifier

type DatasetIdentifier struct {
	Name      string   `json:"name"`
	Owner     HexBytes `json:"owner"`
	Namespace string   `json:"namespace"`
}

DatasetIdentifier contains the information required to identify a dataset.

type Decimal added in v0.4.0

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

Decimal is a decimal number. It has a set precision and scale that will be used on all mathematical operations that are methods of the Decimal type. To perform mathematical operations with maximum precision and scale, use the math functions in this package instead of the methods.

func DecimalAdd added in v0.4.0

func DecimalAdd(x, y *Decimal) (*Decimal, error)

DecimalAdd adds two decimals together. It will return a decimal with maximum precision and scale.

func DecimalDiv added in v0.4.0

func DecimalDiv(x, y *Decimal) (*Decimal, error)

DecimalDiv divides x by y. It will return a decimal with maximum precision and scale.

func DecimalMod added in v0.4.0

func DecimalMod(x, y *Decimal) (*Decimal, error)

DecimalMod returns the remainder of x divided by y. It will return a decimal with maximum precision and scale.

func DecimalMul added in v0.4.0

func DecimalMul(x, y *Decimal) (*Decimal, error)

DecimalMul multiplies two decimals together. It will return a decimal with maximum precision and scale.

func DecimalPow added in v0.4.0

func DecimalPow(x, y *Decimal) (*Decimal, error)

DecimalPow raises x to the power of y.

func DecimalSub added in v0.4.0

func DecimalSub(x, y *Decimal) (*Decimal, error)

DecimalSub subtracts y from x. It will return a decimal with maximum precision and scale.

func MustParseDecimal added in v0.4.0

func MustParseDecimal(s string) *Decimal

MustParseDecimal is like ParseDecimal but panics if the string cannot be parsed.

func MustParseDecimalExplicit added in v0.4.0

func MustParseDecimalExplicit(s string, precision, scale uint16) *Decimal

MustParseDecimalExplicit is like ParseDecimalExplicit but panics if the string cannot be parsed.

func NewDecimalFromBigInt added in v0.4.0

func NewDecimalFromBigInt(i *big.Int, exp int32) (*Decimal, error)

NewDecimalFromBigInt creates a new Decimal from a big.Int and an exponent. The negative of the exponent is the scale of the decimal.

func NewDecimalFromInt added in v0.4.0

func NewDecimalFromInt(i int64) *Decimal

func NewNaNDecimal added in v0.4.0

func NewNaNDecimal() *Decimal

NewNaNDecimal creates a new NaN Decimal.

func ParseDecimal added in v0.4.0

func ParseDecimal(s string) (*Decimal, error)

ParseDecimal creates a new Decimal from a string. It automatically infers the precision and scale.

func ParseDecimalExplicit added in v0.4.0

func ParseDecimalExplicit(s string, precision, scale uint16) (*Decimal, error)

ParseDecimalExplicit creates a new Decimal from a string, with an explicit precision and scale. The precision must be between 1 and 1000, and the scale must be between 0 and precision.

func (*Decimal) Abs added in v0.4.0

func (d *Decimal) Abs() (*Decimal, error)

Abs returns the absolute value of the decimal.

func (*Decimal) Add added in v0.4.0

func (z *Decimal) Add(x, y *Decimal) (*Decimal, error)

Add adds two decimals together. It stores the result in z, and returns it. It will use the precision and scale of z.

func (*Decimal) BigInt added in v0.4.0

func (d *Decimal) BigInt() *big.Int

BigInt returns the underlying big int of the decimal. This is the unscaled value of the decimal.

func (*Decimal) Cmp added in v0.4.0

func (z *Decimal) Cmp(x *Decimal) (int, error)

Cmp compares two decimals. It returns -1 if x < y, 0 if x == y, and 1 if x > y.

func (*Decimal) Div added in v0.4.0

func (z *Decimal) Div(x, y *Decimal) (*Decimal, error)

Div divides x by y. It stores the result in z, and returns it. It will use the precision and scale of z.

func (*Decimal) Exp added in v0.4.0

func (d *Decimal) Exp() int32

Exp is the exponent of the decimal.

func (*Decimal) Float64 added in v0.4.0

func (d *Decimal) Float64() (float64, error)

Float64 returns the decimal as a float64.

func (*Decimal) FullString added in v0.4.0

func (d *Decimal) FullString() string

FullString returns the full string representation of the decimal. It will never return scientific notation.

func (Decimal) Inf added in v0.4.0

func (d Decimal) Inf() bool

func (*Decimal) Int64 added in v0.4.0

func (d *Decimal) Int64() (int64, error)

Int64 returns the decimal as an int64. If it cannot be represented as an int64, it will return an error.

func (*Decimal) IsNegative added in v0.4.0

func (d *Decimal) IsNegative() bool

IsNegative returns true if the decimal is negative.

func (*Decimal) IsPositive added in v0.4.0

func (d *Decimal) IsPositive() bool

IsPositive returns true if the decimal is positive.

func (*Decimal) IsZero added in v0.4.0

func (d *Decimal) IsZero() bool

IsZero returns true if the decimal is zero.

func (Decimal) MarshalBinary added in v0.4.0

func (d Decimal) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface. This supports a variety of standard library functionality, include Gob encoding.

func (Decimal) MarshalJSON added in v0.4.0

func (d Decimal) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Decimal) Mod added in v0.4.0

func (z *Decimal) Mod(x, y *Decimal) (*Decimal, error)

Mod returns the remainder of x divided by y. It stores the result in z, and returns it. It will use the precision and scale of z.

func (*Decimal) Mul added in v0.4.0

func (z *Decimal) Mul(x, y *Decimal) (*Decimal, error)

Mul multiplies two decimals together. It stores the result in z, and returns it. It will use the precision and scale of z.

func (Decimal) NaN added in v0.4.0

func (d Decimal) NaN() bool

func (*Decimal) Neg added in v0.4.0

func (d *Decimal) Neg() error

Neg negates the decimal.

func (*Decimal) Precision added in v0.4.0

func (d *Decimal) Precision() uint16

Precision returns the precision of the decimal. This is the number of significant digits in the decimal. It will be a value between 1 and 1000

func (*Decimal) Round added in v0.4.0

func (d *Decimal) Round(scale uint16) error

Round rounds the decimal to the specified scale.

func (*Decimal) Scale added in v0.4.0

func (d *Decimal) Scale() uint16

Scale returns the scale of the decimal. This is the number of digits to the right of the decimal point. It will be a value between 0 and 1000

func (*Decimal) Scan added in v0.4.0

func (d *Decimal) Scan(src interface{}) error

Scan implements the database/sql.Scanner interface.

func (*Decimal) SetPrecisionAndScale added in v0.4.0

func (d *Decimal) SetPrecisionAndScale(precision, scale uint16) error

SetPrecisionAndScale sets the precision and scale of the decimal. The precision must be between 1 and 1000, and the scale must be between 0 and precision.

func (*Decimal) SetString added in v0.4.0

func (d *Decimal) SetString(s string) error

SetString sets the value of the decimal from a string.

func (*Decimal) Sign added in v0.4.0

func (d *Decimal) Sign() int

Sign returns the sign of the decimal. It returns -1 if the decimal is negative, 0 if it is zero, and 1 if it is positive.

func (*Decimal) String added in v0.4.0

func (d *Decimal) String() string

String returns the string representation of the decimal.

func (*Decimal) Sub added in v0.4.0

func (z *Decimal) Sub(x, y *Decimal) (*Decimal, error)

Sub subtracts y from x. It stores the result in z, and returns it. It will use the precision and scale of z.

func (*Decimal) UnmarshalBinary added in v0.4.0

func (d *Decimal) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

func (*Decimal) UnmarshalJSON added in v0.4.0

func (d *Decimal) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (Decimal) Value added in v0.4.0

func (d Decimal) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface. It converts d to a string.

type DecimalArray added in v0.4.0

type DecimalArray []*Decimal

DecimalArray is an array of decimals. It is primarily used to store arrays of decimals in Postgres.

func (DecimalArray) Value added in v0.4.0

func (da DecimalArray) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type DeleteResolution added in v0.4.0

type DeleteResolution struct {
	ResolutionID *UUID
}

DeleteResolution is a payload for deleting a resolution.

func (DeleteResolution) MarshalBinary added in v0.4.0

func (d DeleteResolution) MarshalBinary() ([]byte, error)

func (*DeleteResolution) Type added in v0.4.0

func (d *DeleteResolution) Type() PayloadType

func (*DeleteResolution) UnmarshalBinary added in v0.4.0

func (d *DeleteResolution) UnmarshalBinary(bts []byte) error

type Duration added in v0.4.0

type Duration time.Duration

Duration is a wrapper around time.Duration that implements text (un)marshalling for the go-toml package to work with Go duration strings instead of integers.

func (Duration) MarshalText added in v0.4.0

func (d Duration) MarshalText() ([]byte, error)

func (Duration) String added in v0.4.0

func (d Duration) String() string

func (*Duration) UnmarshalText added in v0.4.0

func (d *Duration) UnmarshalText(text []byte) error

type EncodedValue added in v0.4.0

type EncodedValue struct {
	Type DataType `json:"type"`
	// The double slice handles arrays of encoded values.
	// If there is only one element, the outer slice will have length 1.
	Data [][]byte `json:"data"`
}

EncodedValue is used to encode a value with its type specified. This is used as arguments for actions.

func EncodeValue added in v0.4.0

func EncodeValue(v any) (*EncodedValue, error)

EncodeValue encodes a value to its detected type. It will reflect the value of the passed argument to determine its type.

func (*EncodedValue) Decode added in v0.4.0

func (e *EncodedValue) Decode() (any, error)

Decode decodes the encoded value to its native Go type.

func (EncodedValue) MarshalBinary added in v0.4.0

func (e EncodedValue) MarshalBinary() ([]byte, error)

func (*EncodedValue) UnmarshalBinary added in v0.4.0

func (e *EncodedValue) UnmarshalBinary(bts []byte) error

type Event added in v0.4.0

type Event struct{}

func (Event) MarshalBinary added in v0.4.0

func (e Event) MarshalBinary() ([]byte, error)

func (*Event) UnmarshalBinary added in v0.4.0

func (e *Event) UnmarshalBinary(data []byte) error

type GenesisInfo added in v0.3.0

type GenesisInfo struct {
	// AppHash is the application hash of the old network at the StartHeight
	AppHash HexBytes `json:"app_hash"`
	// Validators is the list of validators that the new network should start with
	Validators []*Validator `json:"validators"`
}

GenesisInfo holds the genesis information that the new network should use in its genesis file.

type Hash added in v0.4.0

type Hash [HashLen]byte

Hash is the Kwil hash type. Use either [NewHash], or a Hasher created by NewHasher to create a Hash from data.

var ZeroHash Hash

func CalcMerkleRoot added in v0.4.0

func CalcMerkleRoot(leaves []Hash) Hash

CalcMerkleRoot computes the merkel root for a slice of hashes. This is based on the "inline" implementation from btcd / dcrd.

func HashBytes added in v0.4.0

func HashBytes(b []byte) Hash

func NewHashFromBytes added in v0.4.0

func NewHashFromBytes(b []byte) (Hash, error)

NewHashFromBytes creates a Hash from a byte slice.

func NewHashFromString added in v0.4.0

func NewHashFromString(s string) (Hash, error)

NewHashFromString parses a hexadecimal string into a Hash.

func (Hash) IsZero added in v0.4.0

func (h Hash) IsZero() bool

func (Hash) MarshalJSON added in v0.4.0

func (h Hash) MarshalJSON() ([]byte, error)

MarshalJSON ensures the hash marshals to JSON as a hexadecimal string.

func (Hash) MarshalText added in v0.4.0

func (h Hash) MarshalText() ([]byte, error)

wrappers for go-toml

func (*Hash) Scan added in v0.4.0

func (h *Hash) Scan(src any) error

Scan implements the database/sql.Scanner interface.

func (Hash) String added in v0.4.0

func (h Hash) String() string

String returns the hexadecimal representation of the hash (always 64 characters)

func (*Hash) UnmarshalJSON added in v0.4.0

func (h *Hash) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals a hash from a hexadecimal JSON string.

func (*Hash) UnmarshalText added in v0.4.0

func (h *Hash) UnmarshalText(text []byte) error

func (Hash) Value added in v0.4.0

func (h Hash) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface.

type Hasher added in v0.4.0

type Hasher interface {
	// Write more data to the running hash. It never returns an error.
	io.Writer

	// Sum appends the current hash to b and returns the resulting slice.
	// It does not change the underlying hash state.
	Sum(b []byte) Hash

	// Reset resets the Hash to its initial state.
	Reset()
}

Hasher is like the standard library's hash.Hash, but with fewer methods and returning a Hash instead of a byte slice. Use NewHasher to get a Hasher.

func NewHasher added in v0.4.0

func NewHasher() Hasher

NewHasher returns a new instance of a Hasher. If you do not need to use the Write or Reset methods, you can use HashBytes instead.

type Health added in v0.3.0

type Health struct {
	ChainInfo

	// Healthy is based on several factors determined by the service and it's
	// configuration, such as the maximum age of the best block and if the node
	// is still syncing (in catch-up or replay).
	Healthy bool `json:"healthy"`

	// Version is the service API version.
	Version string `json:"version"`

	BlockTimestamp int64 `json:"block_time"` // epoch millis
	BlockAge       int64 `json:"block_age"`  // milliseconds
	Syncing        bool  `json:"syncing"`
	Height         int64 `json:"height"`
	AppHash        Hash  `json:"app_hash"`
	PeerCount      int   `json:"peer_count"`

	// Mode is an oddball field as it pertains to the service config rather than
	// state of the node. It is provided here as a convenience so applications
	// can discern node state and the mode of interaction with one request.
	Mode ServiceMode `json:"mode"` // e.g. "private"
}

Health is the response for MethodHealth. This determines the serialized response for the Health method required by the rpcserver.Svc interface. This is the response with which most health checks will be concerned.

type HexBytes

type HexBytes []byte

HexBytes is used to decode hexadecimal text into a byte slice.

func (*HexBytes) Equals added in v0.4.0

func (hb *HexBytes) Equals(other HexBytes) bool

func (HexBytes) Format added in v0.2.0

func (hb HexBytes) Format(s fmt.State, verb rune)

Format writes either address of 0th element in a slice in base 16 notation, with leading 0x (%p), or casts HexBytes to bytes and writes as hexadecimal string to s.

func (HexBytes) MarshalJSON

func (hb HexBytes) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (HexBytes) MarshalText added in v0.4.0

func (hb HexBytes) MarshalText() ([]byte, error)

func (HexBytes) String

func (hb HexBytes) String() string

func (*HexBytes) UnmarshalJSON

func (hb *HexBytes) UnmarshalJSON(b []byte) error

UnmarshalText satisfies the json.Unmarshaler interface.

func (*HexBytes) UnmarshalText added in v0.4.0

func (hb *HexBytes) UnmarshalText(b []byte) error

type JoinRequest

type JoinRequest struct {
	Candidate *AccountID   `json:"candidate"`  // pubkey of the candidate validator
	Power     int64        `json:"power"`      // the requested power
	ExpiresAt time.Time    `json:"expires_at"` // the timestamp at which the join request expires
	Board     []*AccountID `json:"board"`      // slice of pubkeys of all the eligible voting validators
	Approved  []bool       `json:"approved"`   // slice of bools indicating if the corresponding validator approved
}

type Migration added in v0.3.0

type Migration struct {
	ID               *UUID  `json:"id"`                 // ID is the UUID of the migration resolution/proposal
	ActivationPeriod int64  `json:"activation_height"`  // ActivationPeriod is the amount of blocks before the migration is activated.
	Duration         int64  `json:"migration_duration"` // MigrationDuration is the duration of the migration process starting from the ActivationHeight
	Timestamp        string `json:"timestamp"`          // Timestamp when the migration was proposed
}

Migration is a migration resolution that is proposed by a validator for initiating the migration process.

type MigrationMetadata added in v0.3.0

type MigrationMetadata struct {
	MigrationState   MigrationState `json:"migration_state"`   // MigrationState is the current state of the migration
	GenesisInfo      *GenesisInfo   `json:"genesis_info"`      // GenesisInfo is the genesis information
	SnapshotMetadata []byte         `json:"snapshot_metadata"` // SnapshotMetadata is the snapshot metadata
	Version          int            `json:"version"`           // Version of the migration metadata
}

MigrationMetadata holds metadata about a migration, informing consumers of what information the current node has available for the migration.

type MigrationState added in v0.3.0

type MigrationState struct {
	Status        MigrationStatus `json:"status"`                 // Status is the current status of the migration
	StartHeight   int64           `json:"start_height,omitempty"` // StartHeight is the block height at which the migration started on the old chain
	EndHeight     int64           `json:"end_height,omitempty"`   // EndHeight is the block height at which the migration ends on the old chain
	CurrentHeight int64           `json:"chain_height,omitempty"` // CurrentHeight is the current block height of the node
}

type MigrationStatus added in v0.3.0

type MigrationStatus string

MigrationStatus represents the status of the nodes in the zero downtime migration process.

const (
	// NoActiveMigration indicates there is currently no migration process happening on the network.
	NoActiveMigration MigrationStatus = "NoActiveMigration"

	// ActivationPeriod represents the phase after the migration proposal has been approved by the network,
	// but before the migration begins. During this phase, validators prepare their nodes for migration.
	ActivationPeriod MigrationStatus = "ActivationPeriod"

	// MigrationInProgress indicates that the nodes on the old network are in migration mode and
	// records the state changes to be replicated on the new network.
	MigrationInProgress MigrationStatus = "MigrationInProgress"

	// MigrationCompleted indicates that the migration process has successfully finished on the old network,
	// and the old network is ready to be decommissioned once the new network has caught up.
	MigrationCompleted MigrationStatus = "MigrationCompleted"

	// GenesisMigration refers to the phase where the nodes on the new network during migration bootstraps
	// with the genesis state and replicates the state changes from the old network.
	GenesisMigration MigrationStatus = "GenesisMigration"
)

func (MigrationStatus) Active added in v0.4.0

func (ms MigrationStatus) Active() bool

func (MigrationStatus) NoneActive added in v0.4.0

func (ms MigrationStatus) NoneActive() bool

func (MigrationStatus) Valid added in v0.4.0

func (ms MigrationStatus) Valid() bool

type NamedValue added in v0.4.0

type NamedValue struct {
	Name  string
	Value *EncodedValue
}

type NetworkParameters added in v0.4.0

type NetworkParameters struct {
	// Leader is the leader's public key. The leader must be in the current
	// validator set.
	Leader PublicKey `json:"leader"`

	// MaxBlockSize is the maximum total size of the serialized transactions in
	// a block, in bytes. The size of the serialized block will be slightly
	// larger for the header and other encoding overhead
	MaxBlockSize int64 `json:"max_block_size"`

	// JoinExpiry is the time duration (in seconds) after which a resolution is
	// considered expired since its creation.
	JoinExpiry Duration `json:"join_expiry"`

	// DisabledGasCosts indicates whether gas costs are disabled.
	DisabledGasCosts bool `json:"disabled_gas_costs"`

	// MaxVotesPerTx is the maximum number of votes allowed in a single transaction.
	MaxVotesPerTx int64 `json:"max_votes_per_tx"`

	// MigrationStatus is the status of the migration to the new network. This
	// is not configurable, but is mutable and used to track the status of the
	// migration on nodes of the old network. The "param" tag is used since json
	// is explicitly omitted via the "json:"-" tag.
	MigrationStatus MigrationStatus `json:"-" param:"migration_status"`
}

NetworkParameters are network level configurations that can be evolved over the lifetime of a network. Fields that should not (un)marshal as part of the genesis.json file should contain the `json:"-"` tag.

func (*NetworkParameters) Clone added in v0.4.0

func (np *NetworkParameters) Clone() *NetworkParameters

func (*NetworkParameters) Equals added in v0.4.0

func (np *NetworkParameters) Equals(other *NetworkParameters) bool

func (*NetworkParameters) Hash added in v0.4.0

func (np *NetworkParameters) Hash() Hash

func (NetworkParameters) MarshalBinary added in v0.4.0

func (np NetworkParameters) MarshalBinary() ([]byte, error)

func (*NetworkParameters) SanityChecks added in v0.4.0

func (np *NetworkParameters) SanityChecks() error

func (NetworkParameters) String added in v0.4.0

func (np NetworkParameters) String() string

func (NetworkParameters) ToMap added in v0.4.0

func (np NetworkParameters) ToMap() map[ParamName]any

func (*NetworkParameters) UnmarshalBinary added in v0.4.0

func (np *NetworkParameters) UnmarshalBinary(data []byte) error

type NodeStatus added in v0.4.0

type NodeStatus struct {
	Role            string             `json:"role"`
	CatchingUp      bool               `json:"catching_up"`
	CommittedHeader *BlockHeader       `json:"committed_header"`
	CommitInfo      *CommitInfo        `json:"commit_info"`
	Params          *NetworkParameters `json:"params"`
}

type ParamName added in v0.4.0

type ParamName = string
var (
	ParamNameLeader           ParamName
	ParamNameMaxBlockSize     ParamName
	ParamNameJoinExpiry       ParamName
	ParamNameDisabledGasCosts ParamName
	ParamNameMaxVotesPerTx    ParamName
	ParamNameMigrationStatus  ParamName
)

The ParamName values correspond to the fields of the NetworkParameters struct.

type ParamUpdates added in v0.4.0

type ParamUpdates map[ParamName]any

ParamUpdates is the mechanism by which changes to network parameters are specified. Rather than a struct with pointer fields to indicate changes, we use a map to make updates easy to specify while keeping the NetworkParameters struct simple and easy to use without nil checks.

This approach also makes update serialization more compact, only encoding data for updated fields.

This approach however requires the definition of parameter names (ParamName) and code to assert type of the values. The parameter names are enumerated below, and their values are set using reflection during package initialization.

func (ParamUpdates) Bytes added in v0.4.0

func (pu ParamUpdates) Bytes() []byte

Bytes returns the serialization of the updates. This will panic if there are invalid update keys. Use ValidateUpdates first to ensure they are valid.

func (ParamUpdates) Equals added in v0.4.0

func (pu ParamUpdates) Equals(other ParamUpdates) bool

func (ParamUpdates) MarshalBinary added in v0.4.0

func (pu ParamUpdates) MarshalBinary() ([]byte, error)

MarshalBinary encodes ParamUpdates into a binary format.

func (ParamUpdates) Merge added in v0.4.0

func (pu ParamUpdates) Merge(other ParamUpdates)

func (ParamUpdates) String added in v0.4.0

func (pu ParamUpdates) String() string

func (*ParamUpdates) UnmarshalBinary added in v0.4.0

func (pu *ParamUpdates) UnmarshalBinary(data []byte) error

UnmarshalBinary decodes a binary format into ParamUpdates.

func (*ParamUpdates) UnmarshalJSON added in v0.4.0

func (pu *ParamUpdates) UnmarshalJSON(b []byte) error

type Payload added in v0.4.0

type Payload interface {
	encoding.BinaryMarshaler
	encoding.BinaryUnmarshaler

	Type() PayloadType
}

Payload is the interface that all payloads must implement Implementations should use Kwil's serialization package to encode and decode themselves

func UnmarshalPayload added in v0.4.0

func UnmarshalPayload(payloadType PayloadType, payload []byte) (Payload, error)

UnmarshalPayload unmarshals a serialized transaction payload into an instance of the type registered for the given PayloadType.

type PayloadType added in v0.4.0

type PayloadType string

PayloadType is the type of payload

const (
	PayloadTypeRawStatement        PayloadType = "raw_statement"
	PayloadTypeExecute             PayloadType = "execute"
	PayloadTypeTransfer            PayloadType = "transfer"
	PayloadTypeValidatorJoin       PayloadType = "validator_join"
	PayloadTypeValidatorLeave      PayloadType = "validator_leave"
	PayloadTypeValidatorRemove     PayloadType = "validator_remove"
	PayloadTypeValidatorApprove    PayloadType = "validator_approve"
	PayloadTypeValidatorVoteIDs    PayloadType = "validator_vote_ids"
	PayloadTypeValidatorVoteBodies PayloadType = "validator_vote_bodies"
	PayloadTypeCreateResolution    PayloadType = "create_resolution"
	PayloadTypeApproveResolution   PayloadType = "approve_resolution"
	PayloadTypeDeleteResolution    PayloadType = "delete_resolution"
)

func (PayloadType) String added in v0.4.0

func (p PayloadType) String() string

func (PayloadType) Valid added in v0.4.0

func (p PayloadType) Valid() bool

Valid says if the payload type is known. This does not mean that the node will execute the transaction, e.g. not yet activated, or removed.

type PendingResolution added in v0.3.0

type PendingResolution struct {
	Type         string       `json:"type"`
	ResolutionID *UUID        `json:"resolution_id"` // Resolution ID
	ExpiresAt    time.Time    `json:"expires_at"`    // ExpiresAt is the timestamp at which the resolution expires
	Board        []*AccountID `json:"board"`         // Board is the list of validators who are eligible to vote on the resolution
	Approved     []bool       `json:"approved"`      // Approved is the list of bools indicating if the corresponding validator approved the resolution
}

type PublicKey added in v0.4.0

type PublicKey struct {
	crypto.PublicKey
}

func (PublicKey) MarshalJSON added in v0.4.0

func (pk PublicKey) MarshalJSON() ([]byte, error)

func (PublicKey) String added in v0.4.0

func (pk PublicKey) String() string

func (*PublicKey) UnmarshalJSON added in v0.4.0

func (pk *PublicKey) UnmarshalJSON(b []byte) error

type QueryResult added in v0.4.0

type QueryResult struct {
	ColumnNames []string    `json:"column_names"`
	ColumnTypes []*DataType `json:"column_types"`
	Values      [][]any     `json:"values"`
}

QueryResult is the result of a SQL query or action.

func (*QueryResult) ExportToStringMap added in v0.4.0

func (qr *QueryResult) ExportToStringMap() []map[string]string

ExportToStringMap converts the QueryResult to a slice of maps.

func (*QueryResult) Scan added in v0.4.0

func (q *QueryResult) Scan(fn func() error, vals ...any) error

Scan scans a value from the query result. It accepts a slice of pointers to values, and a function that will be called for each row in the result set. The passed values can be of type *string, *int64, *int, *bool, *[]byte, *UUID, *Decimal, *[]string, *[]int64, *[]int, *[]bool, *[]*int64, *[]*int, *[]*bool, *[]*UUID, *[]*Decimal, *[]UUID, *[]Decimal, *[][]byte, or *[]*[]byte.

type RawStatement added in v0.4.0

type RawStatement struct {
	Statement  string
	Parameters []*NamedValue
}

RawStatement is a raw SQL statement that is executed as a transaction

func (RawStatement) MarshalBinary added in v0.4.0

func (r RawStatement) MarshalBinary() ([]byte, error)

func (RawStatement) Type added in v0.4.0

func (r RawStatement) Type() PayloadType

func (*RawStatement) UnmarshalBinary added in v0.4.0

func (r *RawStatement) UnmarshalBinary(b []byte) error

type ServiceMode added in v0.3.0

type ServiceMode string

ServiceMode describes the operating mode of the user service. Namely, if the service is in private mode (where calls are authenticated, query is disabled, and raw transactions cannot be retrieved).

const (
	ModeOpen    ServiceMode = "open"
	ModePrivate ServiceMode = "private"
)

type Signature added in v0.4.0

type Signature struct {
	PubKeyType crypto.KeyType
	PubKey     []byte // public key of the validator

	Data []byte
}

func SignVote added in v0.4.0

func SignVote(blkID Hash, ack bool, appHash *Hash, privKey crypto.PrivateKey) (*Signature, error)

SignVote signs a vote for the given block ID. This should probably go to node/types.

func (*Signature) Bytes added in v0.4.0

func (sig *Signature) Bytes() []byte

func (Signature) MarshalJSON added in v0.4.0

func (sig Signature) MarshalJSON() ([]byte, error)

func (*Signature) ReadFrom added in v0.4.0

func (s *Signature) ReadFrom(r io.Reader) (int64, error)

func (*Signature) UnmarshalJSON added in v0.4.0

func (sig *Signature) UnmarshalJSON(data []byte) error

UnmarshalJSON

func (*Signature) WriteTo added in v0.4.0

func (s *Signature) WriteTo(w io.Writer) (int64, error)

type SignedMsgSerializationType added in v0.4.0

type SignedMsgSerializationType string

SignedMsgSerializationType is the type of serialization performed on a transaction body(in signing and verification) The main reason we need this is that this type could also to used as the 'version' of the serialization. For now, i think it's a bit redundant. To sign a transaction, you need three types:

  1. the type of payload
  2. the type of serialization
  3. the type of signature(e.g. signer)

But in the future, take eth signing for example, we might change the `signedMsgTmpl` for personal_sign, or `domain` for eip712, this type could be used to distinguish the different versions.

NOTE: The valid combination of 2.) and 3.) are:

  • `SignedMsgConcat` + `PersonalSigner/CometBftSigner/NearSigner`, which is the default for the `client` package
  • `SignedMsgEip712` + `Eip712Signer`
const (
	// SignedMsgConcat is a human-readable serialization of the transaction body
	// it needs a signer that signs
	SignedMsgConcat SignedMsgSerializationType = "concat"

	SignedMsgDirect SignedMsgSerializationType = "direct"

	// DefaultSignedMsgSerType is the default serialization type
	// It's `concat` for now, since it's the only one known works for every signer
	DefaultSignedMsgSerType = SignedMsgConcat
)

func (SignedMsgSerializationType) String added in v0.4.0

type Transaction added in v0.4.0

type Transaction struct {
	// Signature is the signature of the transaction.
	Signature *auth.Signature `json:"signature,omitempty"`

	// Body is the body of the transaction. It gets serialized and signed.
	Body *TransactionBody `json:"body,omitempty"`

	// Serialization is the serialization performed on `Body`
	// in order to generate the message that being signed.
	Serialization SignedMsgSerializationType `json:"serialization"`

	// Sender is the user identifier, which is generally an address but may be
	// a public key of the sender, hence bytes that encode as hexadecimal.
	Sender HexBytes `json:"sender"`
	// contains filtered or unexported fields
}

func CreateNodeTransaction added in v0.4.0

func CreateNodeTransaction(contents Payload, chainID string, nonce uint64) (*Transaction, error)

CreateNodeTransaction creates a new unsigned transaction with the "direct" serialization type.

func CreateTransaction added in v0.4.0

func CreateTransaction(contents Payload, chainID string, nonce uint64) (*Transaction, error)

CreateTransaction creates a new unsigned transaction.

func (*Transaction) Bytes added in v0.4.0

func (t *Transaction) Bytes() []byte

Bytes returns the serialized transaction.

func (*Transaction) Hash added in v0.4.0

func (t *Transaction) Hash() Hash

Hash gives the hash of the transaction that is the unique identifier for the transaction.

func (*Transaction) HashCache added in v0.4.0

func (t *Transaction) HashCache() Hash

HashCache is like Hash, but caches the hash of the transaction. If it is already cached, it is returned as is. Use this with caution:

  1. it is not safe for concurrent use
  2. the allocation and storage of the hash may potentially be undesirable
  3. the hash is not guaranteed to be valid if the transaction is modified

func (*Transaction) MarshalBinary added in v0.4.0

func (t *Transaction) MarshalBinary() ([]byte, error)

MarshalBinary produces the full binary serialization of the transaction, which is the form used in p2p messaging and blockchain storage.

func (*Transaction) ReadFrom added in v0.4.0

func (t *Transaction) ReadFrom(r io.Reader) (int64, error)

func (*Transaction) SerializeMsg added in v0.4.0

func (t *Transaction) SerializeMsg() ([]byte, error)

SerializeMsg produces the serialization of the transaction that is to be used in both signing and verification of transaction.

func (*Transaction) SerializeSize added in v0.4.0

func (t *Transaction) SerializeSize() int64

SerializeSize gives the size of the serialized transaction.

func (*Transaction) Sign added in v0.4.0

func (t *Transaction) Sign(signer auth.Signer) error

Sign signs transaction body with given signer. It will serialize the transaction body first and sign it.

func (*Transaction) StrictUnmarshal added in v0.4.0

func (t *Transaction) StrictUnmarshal()

func (*Transaction) UnmarshalBinary added in v0.4.0

func (t *Transaction) UnmarshalBinary(data []byte) error

func (*Transaction) WriteTo added in v0.4.0

func (t *Transaction) WriteTo(w io.Writer) (int64, error)

type TransactionBody added in v0.4.0

type TransactionBody struct {
	// Description is a human-readable description of the transaction.
	Description string `json:"desc"`

	// Payload is the raw bytes of the payload data.
	Payload []byte `json:"payload"`

	// PayloadType is the type of the payload, which may be used to determine
	// how to decode the payload.
	PayloadType PayloadType `json:"type"`

	// Fee is the fee the sender is willing to pay for the transaction.
	Fee *big.Int `json:"fee"` // MarshalJSON and UnmarshalJSON handle this field, but still tagged for reflection

	// Nonce should be the next nonce of the sender..
	Nonce uint64 `json:"nonce"`

	// ChainID identifies the Kwil chain for which the transaction is intended.
	// Alternatively, this could be withheld from the TransactionBody and passed
	// as an argument to SerializeMsg, as is seen in ethereum signers. However,
	// the full transaction serialization must include it anyway since it passes
	// through the consensus engine and p2p systems as an opaque blob that must
	// be unmarshaled with the chain ID in Kwil blockchain application.
	ChainID string `json:"chain_id"`
	// contains filtered or unexported fields
}

TransactionBody is the body of a transaction that gets included in the signature. This type implements json.Marshaler and json.Unmarshaler to ensure that the Fee field is represented as a string in JSON rather than a number.

func (TransactionBody) Bytes added in v0.4.0

func (tb TransactionBody) Bytes() []byte

func (TransactionBody) MarshalBinary added in v0.4.0

func (tb TransactionBody) MarshalBinary() ([]byte, error)

func (TransactionBody) MarshalJSON added in v0.4.0

func (t TransactionBody) MarshalJSON() ([]byte, error)

MarshalJSON marshals to JSON but with Fee as a string.

func (*TransactionBody) ReadFrom added in v0.4.0

func (tb *TransactionBody) ReadFrom(r io.Reader) (int64, error)

func (*TransactionBody) SerializeMsg added in v0.4.0

func (t *TransactionBody) SerializeMsg(mst SignedMsgSerializationType) ([]byte, error)

SerializeMsg prepares a message for signing or verification using a certain message construction format. This is done since a Kwil transaction is foreign to wallets, and it is signed as a message, not a transaction that is native to the wallet. As such we define conventions for constructing user-friendly messages. The Kwil frontend SDKs must implement these serialization schemes.

func (TransactionBody) SerializeSize added in v0.4.0

func (tb TransactionBody) SerializeSize() int64

SerializeSize gives the size of the serialized transaction body.

func (*TransactionBody) StrictUnmarshal added in v0.4.0

func (tb *TransactionBody) StrictUnmarshal()

func (*TransactionBody) UnmarshalBinary added in v0.4.0

func (tb *TransactionBody) UnmarshalBinary(data []byte) error

func (*TransactionBody) UnmarshalJSON added in v0.4.0

func (t *TransactionBody) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals from JSON, handling a fee string.

func (TransactionBody) WriteTo added in v0.4.0

func (tb TransactionBody) WriteTo(w io.Writer) (int64, error)

type Transfer added in v0.4.0

type Transfer struct {
	To     *AccountID `json:"to"`     // to be string as user identifier
	Amount *big.Int   `json:"amount"` // big.Int
}

Transfer transfers an amount of tokens from the sender to the receiver.

func (Transfer) MarshalBinary added in v0.4.0

func (v Transfer) MarshalBinary() ([]byte, error)

func (Transfer) Type added in v0.4.0

func (v Transfer) Type() PayloadType

func (*Transfer) UnmarshalBinary added in v0.4.0

func (v *Transfer) UnmarshalBinary(b []byte) error

type TxCode added in v0.4.0

type TxCode uint16
const (
	CodeOk                  TxCode = 0
	CodeEncodingError       TxCode = 1
	CodeInvalidTxType       TxCode = 2 // ErrUnknownPayloadType
	CodeInvalidSignature    TxCode = 3
	CodeInvalidNonce        TxCode = 4
	CodeWrongChain          TxCode = 5
	CodeInsufficientBalance TxCode = 6
	CodeInsufficientFee     TxCode = 7 // tx fee set too low, unrelated to balance
	CodeInvalidAmount       TxCode = 8
	CodeInvalidSender       TxCode = 9
	CodeTxTimeoutCommit     TxCode = 10
	CodeMempoolFull         TxCode = 11

	// engine-related error code
	CodeInvalidSchema         TxCode = 100 // TODO: remove, as this is not applicable to the engine
	CodeDatasetMissing        TxCode = 110
	CodeDatasetExists         TxCode = 120
	CodeInvalidResolutionType TxCode = 130

	CodeNetworkInMigration TxCode = 200
	CodeNetworkHalted      TxCode = 201

	CodeUnknownError TxCode = math.MaxUint16
)

func BroadcastErrorToCode added in v0.4.0

func BroadcastErrorToCode(err error) TxCode

BroadcastErrorToCode converts an error from a broadcast method to a TxCode.

type TxQueryResponse added in v0.4.0

type TxQueryResponse struct {
	Hash   Hash         `json:"tx_hash,omitempty"`
	Height int64        `json:"height,omitempty"`
	Tx     *Transaction `json:"tx"`
	Result *TxResult    `json:"tx_result"`
}

TxQueryResponse is the response of a transaction query.

type TxResult added in v0.4.0

type TxResult struct {
	Code   uint32  `json:"code"`
	Gas    int64   `json:"gas"`
	Log    string  `json:"log,omitempty"`
	Events []Event `json:"events,omitempty"`
}

TxResult is the result of a transaction execution on chain.

func (TxResult) MarshalBinary added in v0.4.0

func (tr TxResult) MarshalBinary() ([]byte, error)

func (*TxResult) UnmarshalBinary added in v0.4.0

func (tr *TxResult) UnmarshalBinary(data []byte) error

type UUID

type UUID [16]byte

UUID is a rfc4122 compliant uuidv5

func MustParseUUID added in v0.4.0

func MustParseUUID(s string) *UUID

MustParseUUID parses a uuid from a string and panics on error

func NewUUIDV5

func NewUUIDV5(from []byte) *UUID

NewUUIDV5 generates a uuidv5 from a byte slice. This is used to deterministically generate uuids.

func NewUUIDV5WithNamespace added in v0.2.0

func NewUUIDV5WithNamespace(namespace UUID, from []byte) UUID

NewUUIDV5WithNamespace generates a uuidv5 from a byte slice and a namespace. This is used to deterministically generate uuids.

func ParseUUID added in v0.2.0

func ParseUUID(s string) (*UUID, error)

ParseUUID parses a uuid from a string

func VotableEventID added in v0.4.0

func VotableEventID(ty string, body []byte) UUID

VotableEventID returns the ID of an event that can be voted on. This may be used to determine the ID of an event prior to the event being created.

func (*UUID) Bytes added in v0.2.0

func (u *UUID) Bytes() []byte

func (UUID) MarshalBinary added in v0.4.0

func (u UUID) MarshalBinary() ([]byte, error)

func (UUID) MarshalJSON added in v0.2.0

func (u UUID) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*UUID) Scan

func (u *UUID) Scan(src any) error

func (UUID) String

func (u UUID) String() string

String returns the string representation of the uuid

func (*UUID) UnmarshalBinary added in v0.4.0

func (u *UUID) UnmarshalBinary(b []byte) error

func (*UUID) UnmarshalJSON added in v0.2.0

func (u *UUID) UnmarshalJSON(b []byte) error

func (UUID) Value

func (u UUID) Value() (driver.Value, error)

type UUIDArray

type UUIDArray []*UUID

UUIDArray is a slice of UUIDs. It is used to store arrays of UUIDs in the database.

func (UUIDArray) Bytes added in v0.2.0

func (u UUIDArray) Bytes() [][]byte

func (*UUIDArray) Scan

func (u *UUIDArray) Scan(src any) error

func (UUIDArray) Value

func (u UUIDArray) Value() (driver.Value, error)

type Validator

type Validator struct {
	AccountID
	Power int64 `json:"power"`
}

func (*Validator) Bytes added in v0.4.0

func (v *Validator) Bytes() []byte

func (*Validator) MarshalBinary added in v0.4.0

func (v *Validator) MarshalBinary() ([]byte, error)

func (*Validator) MarshalJSON added in v0.4.0

func (v *Validator) MarshalJSON() ([]byte, error)

func (*Validator) String

func (v *Validator) String() string

func (*Validator) UnmarshalBinary added in v0.4.0

func (v *Validator) UnmarshalBinary(b []byte) error

func (*Validator) UnmarshalJSON added in v0.4.0

func (v *Validator) UnmarshalJSON(b []byte) error

type ValidatorApprove added in v0.4.0

type ValidatorApprove struct {
	Candidate []byte
	KeyType   crypto.KeyType
}

ValidatorApprove is used to vote for a validators approval to join the network

func (ValidatorApprove) MarshalBinary added in v0.4.0

func (v ValidatorApprove) MarshalBinary() ([]byte, error)

func (*ValidatorApprove) Type added in v0.4.0

func (v *ValidatorApprove) Type() PayloadType

func (*ValidatorApprove) UnmarshalBinary added in v0.4.0

func (v *ValidatorApprove) UnmarshalBinary(b []byte) error

type ValidatorJoin added in v0.4.0

type ValidatorJoin struct {
	Power uint64
}

ValidatorJoin requests to join the network with a certain amount of power

func (ValidatorJoin) MarshalBinary added in v0.4.0

func (v ValidatorJoin) MarshalBinary() ([]byte, error)

func (*ValidatorJoin) Type added in v0.4.0

func (v *ValidatorJoin) Type() PayloadType

func (*ValidatorJoin) UnmarshalBinary added in v0.4.0

func (v *ValidatorJoin) UnmarshalBinary(b []byte) error

type ValidatorLeave added in v0.4.0

type ValidatorLeave struct{}

Validator leave is used to signal that the sending validator is leaving the network

func (ValidatorLeave) MarshalBinary added in v0.4.0

func (v ValidatorLeave) MarshalBinary() ([]byte, error)

func (*ValidatorLeave) Type added in v0.4.0

func (v *ValidatorLeave) Type() PayloadType

func (*ValidatorLeave) UnmarshalBinary added in v0.4.0

func (v *ValidatorLeave) UnmarshalBinary(b []byte) error

type ValidatorRemove added in v0.4.0

type ValidatorRemove struct {
	Validator []byte
	KeyType   crypto.KeyType
}

ValidatorRemove is used to vote for a validators removal from the network

func (ValidatorRemove) MarshalBinary added in v0.4.0

func (v ValidatorRemove) MarshalBinary() ([]byte, error)

func (*ValidatorRemove) Type added in v0.4.0

func (v *ValidatorRemove) Type() PayloadType

func (*ValidatorRemove) UnmarshalBinary added in v0.4.0

func (v *ValidatorRemove) UnmarshalBinary(b []byte) error

type ValidatorVoteBodies added in v0.4.0

type ValidatorVoteBodies struct {
	// Events is an array of the full resolution bodies the caller is voting for.
	Events []*VotableEvent
}

ValidatorVoteBodies is a payload for submitting the full vote bodies for any resolution.

func (ValidatorVoteBodies) MarshalBinary added in v0.4.0

func (v ValidatorVoteBodies) MarshalBinary() ([]byte, error)

func (*ValidatorVoteBodies) Type added in v0.4.0

func (v *ValidatorVoteBodies) Type() PayloadType

func (*ValidatorVoteBodies) UnmarshalBinary added in v0.4.0

func (v *ValidatorVoteBodies) UnmarshalBinary(bts []byte) error

type ValidatorVoteIDs added in v0.4.0

type ValidatorVoteIDs struct {
	// ResolutionIDs is an array of all resolution IDs the caller is approving.
	ResolutionIDs []*UUID
}

ValidatorVoteIDs is a payload for submitting approvals for any pending resolution, by ID.

func (*ValidatorVoteIDs) MarshalBinary added in v0.4.0

func (v *ValidatorVoteIDs) MarshalBinary() ([]byte, error)

func (*ValidatorVoteIDs) Type added in v0.4.0

func (v *ValidatorVoteIDs) Type() PayloadType

func (*ValidatorVoteIDs) UnmarshalBinary added in v0.4.0

func (v *ValidatorVoteIDs) UnmarshalBinary(bts []byte) error

type VotableEvent

type VotableEvent struct {
	Type string `json:"type"`
	Body []byte `json:"body"`
}

VotableEvent is an event that can be voted. It contains an event type and a body. An ID can be generated from the event type and body.

func (*VotableEvent) ID

func (e *VotableEvent) ID() *UUID

func (VotableEvent) MarshalBinary added in v0.4.0

func (e VotableEvent) MarshalBinary() ([]byte, error)

func (*VotableEvent) UnmarshalBinary added in v0.4.0

func (e *VotableEvent) UnmarshalBinary(b []byte) error

type VoteInfo added in v0.4.0

type VoteInfo struct {
	// Ack is set to true if the validator agrees with the block
	// in terms of the AppHash, ValidatorSet, MerkleRoot of Txs etc.
	AckStatus AckStatus `json:"ack"`

	// AppHash is optional, it set only if the AckStatus is AckStatusDiverged.
	// AppHash is implied to be the AppHash in the CommitInfo if the AckStatus is AckStatusAgree.
	// AppHash is nil if the AckStatus is AckStatusDisagree.
	AppHash *Hash `json:"app_hash,omitempty"`

	// VoteSignature is the signature of the blkHash + nack | blkHash + ack + appHash
	Signature Signature `json:"sig"`
}

VoteInfo represents the leader's interpretation of the AckRes vote received from the validator. This only includes the votes that influenced the commit decision of the block. It does not include the feedback votes for an already committed block such as OutOfSync Vote etc. Validators and sentry nodes use this information from the CommitInfo to verify that the committed block state was agreed upon by the majority of the validators from the validator set.

func (*VoteInfo) MarshalBinary added in v0.4.0

func (v *VoteInfo) MarshalBinary() ([]byte, error)

func (*VoteInfo) UnmarshalBinary added in v0.4.0

func (v *VoteInfo) UnmarshalBinary(data []byte) error

func (*VoteInfo) Verify added in v0.4.0

func (v *VoteInfo) Verify(blkID Hash, appHash Hash) error

Directories

Path Synopsis
Package types contains the type used by the administrative RPC client and servers.
Package types contains the type used by the administrative RPC client and servers.
Package types contains the type used by the chain RPC client and server.
Package types contains the type used by the chain RPC client and server.

Jump to

Keyboard shortcuts

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