asserter

package
v0.8.9 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2024 License: Apache-2.0 Imports: 10 Imported by: 138

README

Asserter

GoDoc

The Asserter package is used to validate the correctness of Mesh types. It is important to note that this validation only ensures that required fields are populated, fields are in the correct format, and transaction operations only contain types and statuses specified in the /network/status endpoint.

If you want more intensive validation, try running the Mesh CLI.

Installation

go get github.com/coinbase/mesh-sdk-go/asserter

Validation file

Asserter package also allows you to specify a validation file which can be used to have a stricter validation against your implementation.

A simple validation files looks like this. Let's break it down and see what it means

"enabled": true

Specifies if we want to enable this validation or not.

"chain_type": "account",

Specify the chain type. Supported types are account and utxo. Right now we only support account based implementation for validation using this file.

"payment": {
  "name": "PAYMENT",
  "operation": {
    "count": 2,
    "should_balance": true
  }
},

This first validation will validate payment or transaction type. The payment object is defined below

  • name: The string used for defining a payment or transaction
  • operation:
    • count: Count of payment operations (defined by name) which should be present in the transaction. If the number is -1, then we won't validate the count
    • should_balance: If the sum total of the amount defined in the all the operations (defined by name) in a particular transaction should add up to 0 or not. This is really helpful to validate a debit and credit operation in the implementation
"fee": {
  "name": "FEE",
  "operation": {
    "count": 1,
    "should_balance": false
  }
}

Similar to payment type we have fee type. The fields here have the same usage as above.


NOTE

Right now we only support payment and fee operation type with count and total balance match. We will keep adding more validations to it.


Documentation

Index

Constants

View Source
const (
	// MinUnixEpoch is the unix epoch time in milliseconds of
	// 01/01/2000 at 12:00:00 AM.
	MinUnixEpoch = 946713600000

	// MaxUnixEpoch is the unix epoch time in milliseconds of
	// 01/01/2040 at 12:00:00 AM.
	MaxUnixEpoch = 2209017600000
)
View Source
const (
	OperationStatusSuccess   = "SUCCESS"
	OperationStatusOk        = "OK"
	OperationStatusCompleted = "COMPLETED"
	OperationStatusFailed    = "FAILED"
	OperationStatusFailure   = "FAILURE"
)

Variables

View Source
var (
	ErrCurrencyUsedMultipleTimes = errors.New("currency is used multiple times")

	ErrReturnedBlockHashMismatch = errors.New(
		"request block hash does not match response block hash",
	)
	ErrReturnedBlockIndexMismatch = errors.New(
		"request block index does not match response block index",
	)

	AccountBalanceErrs = []error{
		ErrCurrencyUsedMultipleTimes,
		ErrReturnedBlockHashMismatch,
		ErrReturnedBlockIndexMismatch,
	}
)

Account Balance Errors

View Source
var (
	ErrAmountValueMissing            = errors.New("Amount.Value is missing")
	ErrAmountIsNotInt                = errors.New("Amount.Value is not an integer")
	ErrAmountCurrencyIsNil           = errors.New("Amount.Currency is nil")
	ErrAmountCurrencySymbolEmpty     = errors.New("Amount.Currency.Symbol is empty")
	ErrAmountCurrencyHasNegDecimals  = errors.New("Amount.Currency.Decimals must be >= 0")
	ErrOperationIdentifierIndexIsNil = errors.New(
		"Operation.OperationIdentifier.Index is invalid",
	)
	ErrOperationIdentifierIndexOutOfOrder = errors.New(
		"Operation.OperationIdentifier.Index is out of order",
	)
	ErrOperationIdentifierNetworkIndexInvalid = errors.New(
		"Operation.OperationIdentifier.NetworkIndex is invalid",
	)
	ErrAccountIsNil                           = errors.New("Account is nil")
	ErrAccountAddrMissing                     = errors.New("Account.Address is missing")
	ErrAccountSubAccountAddrMissing           = errors.New("Account.SubAccount.Address is missing")
	ErrOperationStatusMissing                 = errors.New("Operation.Status is missing")
	ErrOperationStatusInvalid                 = errors.New("Operation.Status is invalid")
	ErrOperationTypeInvalid                   = errors.New("Operation.Type is invalid")
	ErrOperationIsNil                         = errors.New("Operation is nil")
	ErrOperationStatusNotEmptyForConstruction = errors.New(
		"Operation.Status must be empty for construction",
	)
	ErrRelatedOperationIndexOutOfOrder = errors.New(
		"related operation has index greater than operation",
	)
	ErrRelatedOperationIndexDuplicate  = errors.New("found duplicate related operation index")
	ErrRelatedOperationMissing         = errors.New("related operations key is missing")
	ErrRelatedOperationInFeeNotAllowed = errors.New(
		"fee operation shouldn't have related_operations",
	)
	ErrBlockIdentifierIsNil                  = errors.New("BlockIdentifier is nil")
	ErrBlockIdentifierHashMissing            = errors.New("BlockIdentifier.Hash is missing")
	ErrBlockIdentifierIndexIsNeg             = errors.New("BlockIdentifier.Index is negative")
	ErrPartialBlockIdentifierIsNil           = errors.New("PartialBlockIdentifier is nil")
	ErrPartialBlockIdentifierHashIsEmpty     = errors.New("PartialBlockIdentifier hash is empty")
	ErrPartialBlockIdentifierIndexIsNegative = errors.New(
		"PartialBlockIdentifier index is negative",
	)
	ErrTxIdentifierIsNil           = errors.New("TransactionIdentifier is nil")
	ErrTxIdentifierHashMissing     = errors.New("TransactionIdentifier.Hash is missing")
	ErrNoOperationsForConstruction = errors.New(
		"operations cannot be empty for construction",
	)
	ErrTxIsNil                        = errors.New("Transaction is nil")
	ErrTimestampBeforeMin             = errors.New("timestamp is before 01/01/2000")
	ErrTimestampAfterMax              = errors.New("timestamp is after 01/01/2040")
	ErrBlockIsNil                     = errors.New("Block is nil")
	ErrBlockHashEqualsParentBlockHash = errors.New(
		"BlockIdentifier.Hash == ParentBlockIdentifier.Hash",
	)
	ErrBlockIndexPrecedesParentBlockIndex = errors.New(
		"BlockIdentifier.Index <= ParentBlockIdentifier.Index",
	)
	ErrInvalidDirection = errors.New(
		"invalid direction (must be 'forward' or 'backward')",
	)
	ErrDuplicateRelatedTransaction = errors.New("duplicate related transaction")
	ErrPaymentAmountNotBalancing   = errors.New("payment amount doesn't balance")
	ErrFeeAmountNotBalancing       = errors.New("fee amount doesn't balance")
	ErrPaymentCountMismatch        = errors.New("payment count doesn't match")
	ErrFeeCountMismatch            = errors.New("fee count doesn't match")
	ErrFeeAmountNotNegative        = errors.New("fee amount is not negative")

	BlockErrs = []error{
		ErrAmountValueMissing,
		ErrAmountIsNotInt,
		ErrAmountCurrencyIsNil,
		ErrAmountCurrencySymbolEmpty,
		ErrAmountCurrencyHasNegDecimals,
		ErrOperationIdentifierIndexIsNil,
		ErrOperationIdentifierIndexOutOfOrder,
		ErrOperationIdentifierNetworkIndexInvalid,
		ErrAccountIsNil,
		ErrAccountAddrMissing,
		ErrAccountSubAccountAddrMissing,
		ErrOperationStatusMissing,
		ErrOperationStatusInvalid,
		ErrOperationTypeInvalid,
		ErrOperationIsNil,
		ErrOperationStatusNotEmptyForConstruction,
		ErrRelatedOperationIndexOutOfOrder,
		ErrRelatedOperationIndexDuplicate,
		ErrRelatedOperationMissing,
		ErrBlockIdentifierIsNil,
		ErrBlockIdentifierHashMissing,
		ErrBlockIdentifierIndexIsNeg,
		ErrPartialBlockIdentifierIsNil,
		ErrPartialBlockIdentifierHashIsEmpty,
		ErrPartialBlockIdentifierIndexIsNegative,
		ErrTxIdentifierIsNil,
		ErrTxIdentifierHashMissing,
		ErrNoOperationsForConstruction,
		ErrTxIsNil,
		ErrTimestampBeforeMin,
		ErrTimestampAfterMax,
		ErrBlockIsNil,
		ErrBlockHashEqualsParentBlockHash,
		ErrBlockIndexPrecedesParentBlockIndex,
		ErrInvalidDirection,
		ErrDuplicateRelatedTransaction,
		ErrPaymentAmountNotBalancing,
		ErrFeeAmountNotBalancing,
		ErrFeeAmountNotNegative,
	}
)

Block Errors

View Source
var (
	ErrCoinIsNil            = errors.New("coin cannot be nil")
	ErrCoinDuplicate        = errors.New("duplicate coin identifier detected")
	ErrCoinIdentifierIsNil  = errors.New("coin identifier cannot be nil")
	ErrCoinIdentifierNotSet = errors.New("coin identifier cannot be empty")
	ErrCoinChangeIsNil      = errors.New("coin change cannot be nil")
	ErrCoinActionInvalid    = errors.New("not a valid coin action")

	CoinErrs = []error{
		ErrCoinIsNil,
		ErrCoinDuplicate,
		ErrCoinIdentifierIsNil,
		ErrCoinIdentifierNotSet,
		ErrCoinChangeIsNil,
		ErrCoinActionInvalid,
	}
)

Coin Errors

View Source
var (
	ErrConstructionPreprocessResponseIsNil = errors.New(
		"ConstructionPreprocessResponse cannot be nil",
	)
	ErrConstructionMetadataResponseIsNil = errors.New(
		"ConstructionMetadataResponse cannot be nil",
	)
	ErrConstructionMetadataResponseMetadataMissing = errors.New("Metadata is nil")
	ErrTxIdentifierResponseIsNil                   = errors.New(
		"TransactionIdentifierResponse cannot be nil",
	)
	ErrConstructionCombineResponseIsNil = errors.New(
		"construction combine response cannot be nil",
	)
	ErrSignedTxEmpty = errors.New(
		"signed transaction cannot be empty",
	)
	ErrConstructionDeriveResponseIsNil = errors.New(
		"construction derive response cannot be nil",
	)
	ErrConstructionParseResponseIsNil = errors.New(
		"construction parse response cannot be nil",
	)
	ErrConstructionParseResponseOperationsEmpty        = errors.New("operations cannot be empty")
	ErrConstructionParseResponseSignersEmptyOnSignedTx = errors.New(
		"signers cannot be empty on signed transaction",
	)
	ErrConstructionParseResponseSignersNonEmptyOnUnsignedTx = errors.New(
		"signers should be empty for unsigned txs",
	)
	ErrConstructionPayloadsResponseIsNil = errors.New(
		"construction payloads response cannot be nil",
	)
	ErrConstructionPayloadsResponseUnsignedTxEmpty = errors.New(
		"unsigned transaction cannot be empty",
	)
	ErrConstructionPayloadsResponsePayloadsEmpty = errors.New("signing payloads cannot be empty")
	ErrPublicKeyIsNil                            = errors.New("PublicKey cannot be nil")
	ErrPublicKeyBytesEmpty                       = errors.New("public key bytes cannot be empty")
	ErrPublicKeyBytesZero                        = errors.New("public key bytes 0")
	ErrCurveTypeNotSupported                     = errors.New("not a supported CurveType")
	ErrSigningPayloadIsNil                       = errors.New("signing payload cannot be nil")
	ErrSigningPayloadBytesEmpty                  = errors.New(
		"signing payload bytes cannot be empty",
	)
	ErrSigningPayloadBytesZero = errors.New(
		"signing payload bytes cannot be 0",
	)
	ErrSignaturesEmpty               = errors.New("signatures cannot be empty")
	ErrSignaturesReturnedSigMismatch = errors.New(
		"requested signature type does not match returned signature type",
	)
	ErrSignatureBytesEmpty       = errors.New("signature bytes cannot be empty")
	ErrSignatureBytesZero        = errors.New("signature bytes cannot be 0")
	ErrSignatureTypeNotSupported = errors.New("not a supported SignatureType")

	ConstructionErrs = []error{
		ErrConstructionPreprocessResponseIsNil,
		ErrConstructionMetadataResponseIsNil,
		ErrConstructionMetadataResponseMetadataMissing,
		ErrTxIdentifierResponseIsNil,
		ErrConstructionCombineResponseIsNil,
		ErrSignedTxEmpty,
		ErrConstructionDeriveResponseIsNil,
		ErrConstructionParseResponseIsNil,
		ErrConstructionParseResponseOperationsEmpty,
		ErrConstructionParseResponseSignersEmptyOnSignedTx,
		ErrConstructionParseResponseSignersNonEmptyOnUnsignedTx,
		ErrConstructionPayloadsResponseIsNil,
		ErrConstructionPayloadsResponseUnsignedTxEmpty,
		ErrConstructionPayloadsResponsePayloadsEmpty,
		ErrPublicKeyIsNil,
		ErrPublicKeyBytesEmpty,
		ErrPublicKeyBytesZero,
		ErrCurveTypeNotSupported,
		ErrSigningPayloadIsNil,
		ErrSigningPayloadBytesEmpty,
		ErrSigningPayloadBytesZero,
		ErrSignaturesEmpty,
		ErrSignaturesReturnedSigMismatch,
		ErrSignatureBytesEmpty,
		ErrSignatureBytesZero,
		ErrSignatureTypeNotSupported,
	}
)

Construction Errors

View Source
var (
	ErrSubNetworkIdentifierInvalid = errors.New(
		"NetworkIdentifier.SubNetworkIdentifier.Network is missing",
	)
	ErrNetworkIdentifierIsNil               = errors.New("NetworkIdentifier is nil")
	ErrNetworkIdentifierBlockchainMissing   = errors.New("NetworkIdentifier.Blockchain is missing")
	ErrNetworkIdentifierNetworkMissing      = errors.New("NetworkIdentifier.Network is missing")
	ErrPeerIDMissing                        = errors.New("Peer.PeerID is missing")
	ErrVersionIsNil                         = errors.New("version is nil")
	ErrVersionNodeVersionMissing            = errors.New("Version.NodeVersion is missing")
	ErrVersionMiddlewareVersionMissing      = errors.New("Version.MiddlewareVersion is missing")
	ErrNetworkStatusResponseIsNil           = errors.New("network status response is nil")
	ErrNoAllowedOperationStatuses           = errors.New("no Allow.OperationStatuses found")
	ErrNoSuccessfulAllowedOperationStatuses = errors.New(
		"no successful Allow.OperationStatuses found",
	)
	ErrErrorCodeUsedMultipleTimes = errors.New("error code used multiple times")
	ErrErrorDetailsPopulated      = errors.New(
		"error details populated in /network/options",
	)
	ErrAllowIsNil                                    = errors.New("Allow is nil")
	ErrNetworkOptionsResponseIsNil                   = errors.New("options is nil")
	ErrNetworkListResponseIsNil                      = errors.New("NetworkListResponse is nil")
	ErrNetworkListResponseNetworksContainsDuplicates = errors.New(
		"NetworkListResponse.Networks contains duplicates",
	)
	ErrBalanceExemptionIsNil                  = errors.New("BalanceExemption is nil")
	ErrBalanceExemptionTypeInvalid            = errors.New("BalanceExemption.Type is invalid")
	ErrBalanceExemptionMissingSubject         = errors.New("BalanceExemption missing subject")
	ErrBalanceExemptionSubAccountAddressEmpty = errors.New(
		"BalanceExemption.SubAccountAddress is empty",
	)
	ErrBalanceExemptionNoHistoricalLookup = errors.New(
		"BalanceExemptions only supported when HistoricalBalanceLookup supported",
	)
	ErrTimestampStartIndexInvalid = errors.New(
		"TimestampStartIndex is invalid",
	)
	ErrSyncStatusCurrentIndexNegative = errors.New(
		"SyncStatus.CurrentIndex is negative",
	)
	ErrSyncStatusTargetIndexNegative = errors.New(
		"SyncStatus.TargetIndex is negative",
	)
	ErrSyncStatusStageInvalid = errors.New(
		"SyncStatus.Stage is invalid",
	)

	NetworkErrs = []error{
		ErrSubNetworkIdentifierInvalid,
		ErrNetworkIdentifierIsNil,
		ErrNetworkIdentifierBlockchainMissing,
		ErrNetworkIdentifierNetworkMissing,
		ErrPeerIDMissing,
		ErrVersionIsNil,
		ErrVersionNodeVersionMissing,
		ErrVersionMiddlewareVersionMissing,
		ErrNetworkStatusResponseIsNil,
		ErrNoAllowedOperationStatuses,
		ErrNoSuccessfulAllowedOperationStatuses,
		ErrErrorCodeUsedMultipleTimes,
		ErrErrorDetailsPopulated,
		ErrAllowIsNil,
		ErrNetworkOptionsResponseIsNil,
		ErrNetworkListResponseIsNil,
		ErrNetworkListResponseNetworksContainsDuplicates,
		ErrBalanceExemptionIsNil,
		ErrBalanceExemptionTypeInvalid,
		ErrBalanceExemptionMissingSubject,
		ErrBalanceExemptionSubAccountAddressEmpty,
		ErrBalanceExemptionNoHistoricalLookup,
		ErrTimestampStartIndexInvalid,
		ErrSyncStatusCurrentIndexNegative,
		ErrSyncStatusTargetIndexNegative,
		ErrSyncStatusStageInvalid,
	}
)

Network Errors

View Source
var (
	ErrNoSupportedNetworks = errors.New(
		"no supported networks",
	)
	ErrSupportedNetworksDuplicate = errors.New(
		"supported network duplicate",
	)
	ErrRequestedNetworkNotSupported = errors.New(
		"requestNetwork is not supported",
	)
	ErrAccountBalanceRequestIsNil = errors.New(
		"AccountBalanceRequest is nil",
	)
	ErrAccountBalanceRequestHistoricalBalanceLookupNotSupported = errors.New(
		"historical balance lookup is not supported",
	)
	ErrBlockRequestIsNil                      = errors.New("BlockRequest is nil")
	ErrBlockTransactionRequestIsNil           = errors.New("BlockTransactionRequest is nil")
	ErrConstructionMetadataRequestIsNil       = errors.New("ConstructionMetadataRequest is nil")
	ErrConstructionSubmitRequestIsNil         = errors.New("ConstructionSubmitRequest is nil")
	ErrConstructionSubmitRequestSignedTxEmpty = errors.New(
		"ConstructionSubmitRequest.SignedTransaction is empty",
	)
	ErrMempoolTransactionRequestIsNil = errors.New(
		"MempoolTransactionRequest is nil",
	)
	ErrMetadataRequestIsNil = errors.New(
		"MetadataRequest is nil",
	)
	ErrNetworkRequestIsNil = errors.New(
		"NetworkRequest is nil",
	)
	ErrConstructionDeriveRequestIsNil = errors.New(
		"ConstructionDeriveRequest is nil",
	)
	ErrConstructionPreprocessRequestIsNil = errors.New(
		"ConstructionPreprocessRequest is nil",
	)
	ErrConstructionPreprocessRequestSuggestedFeeMultiplierIsNeg = errors.New(
		"suggested fee multiplier cannot be less than 0",
	)
	ErrConstructionPayloadsRequestIsNil          = errors.New("ConstructionPayloadsRequest is nil")
	ErrConstructionCombineRequestIsNil           = errors.New("ConstructionCombineRequest is nil")
	ErrConstructionCombineRequestUnsignedTxEmpty = errors.New("UnsignedTransaction cannot be empty")
	ErrConstructionHashRequestIsNil              = errors.New("ConstructionHashRequest is nil")
	ErrConstructionHashRequestSignedTxEmpty      = errors.New("SignedTransaction cannot be empty")
	ErrConstructionParseRequestIsNil             = errors.New("ConstructionParseRequest is nil")
	ErrConstructionParseRequestEmpty             = errors.New("Transaction cannot be empty")
	ErrCallRequestIsNil                          = errors.New("CallRequest is nil")
	ErrCallMethodEmpty                           = errors.New("call method cannot be empty")
	ErrCallMethodUnsupported                     = errors.New("call method is not supported")
	ErrCallMethodDuplicate                       = errors.New("duplicate call method detected")
	ErrAccountCoinsRequestIsNil                  = errors.New("AccountCoinsRequest is nil")
	ErrMempoolCoinsNotSupported                  = errors.New("mempool coins not supported")
	ErrEventsBlocksRequestIsNil                  = errors.New("EventsBlocksRequest is nil")
	ErrOffsetIsNegative                          = errors.New("offset is negative")
	ErrLimitIsNegative                           = errors.New("limit is negative")
	ErrSearchTransactionsRequestIsNil            = errors.New("SearchTransactionsRequest is nil")
	ErrOperatorInvalid                           = errors.New("operator is invalid")
	ErrMaxBlockInvalid                           = errors.New("max block invalid")
	ErrDuplicateCurrency                         = errors.New("duplicate currency")

	ServerErrs = []error{
		ErrNoSupportedNetworks,
		ErrSupportedNetworksDuplicate,
		ErrRequestedNetworkNotSupported,
		ErrAccountBalanceRequestIsNil,
		ErrAccountBalanceRequestHistoricalBalanceLookupNotSupported,
		ErrBlockRequestIsNil,
		ErrBlockTransactionRequestIsNil,
		ErrConstructionMetadataRequestIsNil,
		ErrConstructionSubmitRequestIsNil,
		ErrConstructionSubmitRequestSignedTxEmpty,
		ErrMempoolTransactionRequestIsNil,
		ErrMetadataRequestIsNil,
		ErrNetworkRequestIsNil,
		ErrConstructionDeriveRequestIsNil,
		ErrConstructionPreprocessRequestIsNil,
		ErrConstructionPreprocessRequestSuggestedFeeMultiplierIsNeg,
		ErrConstructionPayloadsRequestIsNil,
		ErrConstructionCombineRequestIsNil,
		ErrConstructionCombineRequestUnsignedTxEmpty,
		ErrConstructionHashRequestIsNil,
		ErrConstructionHashRequestSignedTxEmpty,
		ErrConstructionParseRequestIsNil,
		ErrConstructionParseRequestEmpty,
		ErrCallRequestIsNil,
		ErrCallMethodEmpty,
		ErrCallMethodUnsupported,
		ErrCallMethodDuplicate,
		ErrAccountCoinsRequestIsNil,
		ErrMempoolCoinsNotSupported,
		ErrEventsBlocksRequestIsNil,
		ErrOffsetIsNegative,
		ErrLimitIsNegative,
		ErrSearchTransactionsRequestIsNil,
		ErrOperatorInvalid,
		ErrMaxBlockInvalid,
		ErrDuplicateCurrency,
	}
)

Server Errors

View Source
var (
	ErrMaxSequenceInvalid    = errors.New("max sequence invalid")
	ErrSequenceInvalid       = errors.New("sequence invalid")
	ErrBlockEventTypeInvalid = errors.New("block event type invalid")
	ErrSequenceOutOfOrder    = errors.New("sequence out of order")

	EventsErrs = []error{
		ErrMaxSequenceInvalid,
		ErrSequenceInvalid,
		ErrBlockEventTypeInvalid,
		ErrSequenceOutOfOrder,
	}
)

Events Errors

View Source
var (
	ErrNextOffsetInvalid = errors.New("next offset invalid")
	ErrTotalCountInvalid = errors.New("total count invalid")

	SearchErrs = []error{
		ErrNextOffsetInvalid,
		ErrTotalCountInvalid,
	}
)

Search Errors

View Source
var (
	ErrErrorIsNil           = errors.New("Error is nil")
	ErrErrorCodeIsNeg       = errors.New("Error.Code is negative")
	ErrErrorMessageMissing  = errors.New("Error.Message is missing")
	ErrErrorUnexpectedCode  = errors.New("Error.Code unexpected")
	ErrErrorMessageMismatch = errors.New(
		"Error.Message does not match message from /network/options",
	)
	ErrErrorRetriableMismatch = errors.New("Error.Retriable mismatch")
	ErrErrorDescriptionEmpty  = errors.New(
		"Error.Description is provided but is empty",
	)

	ErrorErrs = []error{
		ErrErrorIsNil,
		ErrErrorCodeIsNeg,
		ErrErrorMessageMissing,
		ErrErrorUnexpectedCode,
		ErrErrorMessageMismatch,
		ErrErrorRetriableMismatch,
		ErrErrorDescriptionEmpty,
	}
)

Error Errors

View Source
var (
	ErrStringArrayEmpty             = errors.New("string array is empty")
	ErrStringArrayEmptyString       = errors.New("empty string exists in string array")
	ErrStringArrayDuplicateString   = errors.New("duplicate string exists in string array")
	ErrAccountArrayEmpty            = errors.New("account array is empty")
	ErrAccountArrayInvalidAccount   = errors.New("invalid account exists in account array")
	ErrAccountArrayDuplicateAccount = errors.New("duplicate account exists in account array")
)

Util Errors

View Source
var (
	// ErrAsserterNotInitialized is returned when some call in the asserter
	// package requires the asserter to be initialized first.
	ErrAsserterNotInitialized = errors.New("asserter not initialized")
)

Functions

func AccountArray added in v0.4.1

func AccountArray(arrName string, arr []*types.AccountIdentifier) error

AccountArray ensures all *types.AccountIdentifier in an array are valid and not duplicates.

func AccountBalanceResponse added in v0.1.5

func AccountBalanceResponse(
	requestBlock *types.PartialBlockIdentifier,
	response *types.AccountBalanceResponse,
) error

AccountBalanceResponse returns an error if the provided types.BlockIdentifier is invalid, if the requestBlock is not nil and not equal to the response block, or if the same currency is present in multiple amounts.

func AccountCoinsResponse added in v0.6.0

func AccountCoinsResponse(
	response *types.AccountCoinsResponse,
) error

AccountCoinsResponse returns an error if the provided *types.AccountCoinsResponse is invalid.

func AccountIdentifier

func AccountIdentifier(account *types.AccountIdentifier) error

AccountIdentifier returns an error if a types.AccountIdentifier is missing an address or a provided SubAccount is missing an identifier.

func Allow added in v0.1.2

func Allow(allowed *types.Allow) error

Allow ensures a types.Allow object is valid.

func Amount

func Amount(amount *types.Amount) error

Amount ensures a types.Amount has an integer value, specified precision, and symbol.

func AssertUniqueAmounts added in v0.4.1

func AssertUniqueAmounts(amounts []*types.Amount) error

AssertUniqueAmounts returns an error if a slice of types.Amount is invalid. It is considered invalid if the same currency is returned multiple times (these should be consolidated) or if a types.Amount is considered invalid.

func BalanceExemptions added in v0.5.0

func BalanceExemptions(exemptions []*types.BalanceExemption) error

BalanceExemptions ensures []*types.BalanceExemption is valid.

func BlockEvent added in v0.6.0

func BlockEvent(
	event *types.BlockEvent,
) error

BlockEvent ensures a *types.BlockEvent is valid.

func BlockIdentifier

func BlockIdentifier(blockIdentifier *types.BlockIdentifier) error

BlockIdentifier ensures a types.BlockIdentifier is well-formatted.

func BytesArrayZero added in v0.4.6

func BytesArrayZero(arr []byte) bool

BytesArrayZero returns a boolean indicating if all elements in an array are 0.

func CallMethods added in v0.5.0

func CallMethods(methods []string) error

CallMethods ensures Allow.CallMethods are valid.

func Coin added in v0.3.3

func Coin(coin *types.Coin) error

Coin returns an error if the provided *types.Coin is invalid.

func CoinAction added in v0.3.3

func CoinAction(action types.CoinAction) error

CoinAction returns an error if the provided types.CoinAction is invalid.

func CoinChange added in v0.3.3

func CoinChange(change *types.CoinChange) error

CoinChange returns an error if the provided *types.CoinChange is invalid.

func CoinIdentifier added in v0.3.3

func CoinIdentifier(coinIdentifier *types.CoinIdentifier) error

CoinIdentifier returns an error if the provided *types.CoinIdentifier is invalid.

func Coins added in v0.3.3

func Coins(coins []*types.Coin) error

Coins returns an error if the provided []*types.Coin is invalid. If there are any duplicate identifiers, this function will also return an error.

func ConstructionCombineResponse added in v0.3.0

func ConstructionCombineResponse(
	response *types.ConstructionCombineResponse,
) error

ConstructionCombineResponse returns an error if a *types.ConstructionCombineResponse does not have a populated SignedTransaction.

func ConstructionDeriveResponse added in v0.3.0

func ConstructionDeriveResponse(
	response *types.ConstructionDeriveResponse,
) error

ConstructionDeriveResponse returns an error if a *types.ConstructionDeriveResponse does not have a populated Address.

func ConstructionMetadataResponse added in v0.3.0

func ConstructionMetadataResponse(
	response *types.ConstructionMetadataResponse,
) error

ConstructionMetadataResponse returns an error if the metadata is not a JSON object.

func ConstructionPayloadsResponse added in v0.3.0

func ConstructionPayloadsResponse(
	response *types.ConstructionPayloadsResponse,
) error

ConstructionPayloadsResponse returns an error if a *types.ConstructionPayloadsResponse does not have an UnsignedTransaction or has no valid *SigningPaylod.

func ConstructionPreprocessResponse added in v0.4.1

func ConstructionPreprocessResponse(
	response *types.ConstructionPreprocessResponse,
) error

ConstructionPreprocessResponse returns an error if the request public keys are not valid AccountIdentifiers.

func ContainsCurrency added in v0.2.0

func ContainsCurrency(currencies []*types.Currency, currency *types.Currency) bool

ContainsCurrency returns a boolean indicating if a *types.Currency is contained within a slice of *types.Currency. The check for equality takes into account everything within the types.Currency struct (including currency.Metadata).

func ContainsDuplicateCurrency added in v0.6.0

func ContainsDuplicateCurrency(currencies []*types.Currency) *types.Currency

ContainsDuplicateCurrency retruns a boolean indicating if an array of *types.Currency contains any duplicate currencies.

func Currency added in v0.4.1

func Currency(currency *types.Currency) error

Currency ensures a *types.Currency is valid.

func CurveType added in v0.3.0

func CurveType(
	curve types.CurveType,
) error

CurveType returns an error if the curve is not a valid types.CurveType.

func DuplicateRelatedTransaction added in v0.6.9

func DuplicateRelatedTransaction(
	items []*types.RelatedTransaction,
) *types.RelatedTransaction

DuplicateRelatedTransaction returns nil if no duplicates are found in the array and returns the first duplicated item found otherwise.

func Err added in v0.4.1

func Err(err error) (bool, string)

Err takes an error as an argument and returns whether or not the error is one thrown by the asserter along with the specific source of the error

func Error added in v0.0.4

func Error(err *types.Error) error

Error ensures a types.Error is valid.

func Errors added in v0.0.4

func Errors(rosettaErrors []*types.Error) error

Errors ensures each types.Error in a slice is valid and that there is no error code collision.

func EventsBlocksResponse added in v0.6.0

func EventsBlocksResponse(
	response *types.EventsBlocksResponse,
) error

EventsBlocksResponse ensures a *types.EventsBlocksResponse is valid.

func InitOperationStatus added in v0.8.4

func InitOperationStatus(asserter *Asserter)

InitOperationStatus initializes operation status map for a generic rosetta client

func MempoolTransactions

func MempoolTransactions(
	transactions []*types.TransactionIdentifier,
) error

MempoolTransactions returns an error if any types.TransactionIdentifier returns is missing a hash. The correctness of each populated MempoolTransaction is asserted by Transaction.

func NetworkIdentifier

func NetworkIdentifier(network *types.NetworkIdentifier) error

NetworkIdentifier ensures a types.NetworkIdentifier has a valid blockchain and network.

func NetworkListResponse added in v0.1.2

func NetworkListResponse(response *types.NetworkListResponse) error

NetworkListResponse ensures a types.NetworkListResponse object is valid.

func NetworkOptionsResponse added in v0.1.2

func NetworkOptionsResponse(options *types.NetworkOptionsResponse) error

NetworkOptionsResponse ensures a types.NetworkOptionsResponse object is valid.

func NetworkStatusResponse

func NetworkStatusResponse(response *types.NetworkStatusResponse) error

NetworkStatusResponse ensures any types.NetworkStatusResponse is valid.

func OperationIdentifier

func OperationIdentifier(
	identifier *types.OperationIdentifier,
	index int64,
) error

OperationIdentifier returns an error if index of the types.Operation is out-of-order or if the NetworkIndex is invalid.

func OperationStatuses

func OperationStatuses(statuses []*types.OperationStatus) error

OperationStatuses ensures all items in Options.Allow.OperationStatuses are valid and that there exists at least 1 successful status.

func OperationTypes added in v0.1.6

func OperationTypes(types []string) error

OperationTypes ensures all items in Options.Allow.OperationStatuses are valid and that there are no repeats.

func PartialBlockIdentifier added in v0.1.0

func PartialBlockIdentifier(blockIdentifier *types.PartialBlockIdentifier) error

PartialBlockIdentifier ensures a types.PartialBlockIdentifier is well-formatted.

func Peer

func Peer(peer *types.Peer) error

Peer ensures a types.Peer has a valid peer_id.

func PublicKey added in v0.3.0

func PublicKey(
	publicKey *types.PublicKey,
) error

PublicKey returns an error if the *types.PublicKey is nil, is not valid hex, or has an undefined CurveType.

func SignatureType added in v0.3.0

func SignatureType(
	signature types.SignatureType,
) error

SignatureType returns an error if signature is not a valid types.SignatureType.

func Signatures added in v0.3.0

func Signatures(
	signatures []*types.Signature,
) error

Signatures returns an error if any *types.Signature is invalid.

func SigningPayload added in v0.3.0

func SigningPayload(
	signingPayload *types.SigningPayload,
) error

SigningPayload returns an error if a *types.SigningPayload is nil, has an empty address, has invlaid hex, or has an invalid SignatureType (if populated).

func StringArray

func StringArray(arrName string, arr []string) error

StringArray ensures all strings in an array are non-empty strings and not duplicates.

func SubNetworkIdentifier

func SubNetworkIdentifier(subNetworkIdentifier *types.SubNetworkIdentifier) error

SubNetworkIdentifier asserts a types.SubNetworkIdentifier is valid (if not nil).

func SupportedNetworks added in v0.1.6

func SupportedNetworks(supportedNetworks []*types.NetworkIdentifier) error

SupportedNetworks returns an error if there is an invalid types.NetworkIdentifier or there is a duplicate.

func SyncStatus added in v0.6.5

func SyncStatus(status *types.SyncStatus) error

SyncStatus ensures any types.SyncStatus is valid.

func Timestamp

func Timestamp(timestamp int64) error

Timestamp returns an error if the timestamp on a block is less than or equal to 0.

func TransactionIdentifier

func TransactionIdentifier(
	transactionIdentifier *types.TransactionIdentifier,
) error

TransactionIdentifier returns an error if a types.TransactionIdentifier has an invalid hash.

func TransactionIdentifierResponse added in v0.3.3

func TransactionIdentifierResponse(
	response *types.TransactionIdentifierResponse,
) error

TransactionIdentifierResponse returns an error if the types.TransactionIdentifier in the response is not valid.

func Version

func Version(version *types.Version) error

Version ensures the version of the node is returned.

Types

type Asserter

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

Asserter contains all logic to perform static validation on Rosetta Server responses.

func NewClientWithFile added in v0.1.6

func NewClientWithFile(
	filePath string,
) (*Asserter, error)

NewClientWithFile constructs a new Asserter using a specification file instead of responses. This can be useful for running reliable systems that error when updates to the server (more error types, more operations, etc.) significantly change how to parse the chain. The filePath provided is parsed relative to the current directory.

func NewClientWithOptions added in v0.1.6

func NewClientWithOptions(
	network *types.NetworkIdentifier,
	genesisBlockIdentifier *types.BlockIdentifier,
	operationTypes []string,
	operationStatuses []*types.OperationStatus,
	errors []*types.Error,
	timestampStartIndex *int64,
	validationConfig *Validations,
) (*Asserter, error)

NewClientWithOptions constructs a new Asserter using the provided arguments instead of using a NetworkStatusResponse and a NetworkOptionsResponse.

func NewClientWithResponses added in v0.1.6

func NewClientWithResponses(
	network *types.NetworkIdentifier,
	networkStatus *types.NetworkStatusResponse,
	networkOptions *types.NetworkOptionsResponse,
	validationFilePath string,
) (*Asserter, error)

NewClientWithResponses constructs a new Asserter from a NetworkStatusResponse and NetworkOptionsResponse.

func NewGenericAsserter added in v0.8.5

func NewGenericAsserter(
	supportedOperationTypes []string,
	historicalBalanceLookup bool,
	supportedNetworks []*types.NetworkIdentifier,
	operationStatuses []*types.OperationStatus,
	errors []*types.Error,
	genesisBlockIdentifier *types.BlockIdentifier,
	timestampStartIndex int64,
	validationFilePath string,
) (*Asserter, error)

NewGenericAsserter constructs a new Asserter for generic usage

func NewGenericRosettaClient added in v0.8.4

func NewGenericRosettaClient(
	network *types.NetworkIdentifier,
	genesisBlockIdentifier *types.BlockIdentifier,
) (*Asserter, error)

NewGenericRosettaClient constructs a new Asserter using the provided arguments and without a Rosetta Spec validation. This is used to ignore rosetta spec validation

func NewServer added in v0.1.6

func NewServer(
	supportedOperationTypes []string,
	historicalBalanceLookup bool,
	supportedNetworks []*types.NetworkIdentifier,
	callMethods []string,
	mempoolCoins bool,
	validationFilePath string,
) (*Asserter, error)

NewServer constructs a new Asserter for use in the server package.

func (*Asserter) AccountBalanceRequest added in v0.1.6

func (a *Asserter) AccountBalanceRequest(request *types.AccountBalanceRequest) error

AccountBalanceRequest ensures that a types.AccountBalanceRequest is well-formatted.

func (*Asserter) AccountCoinsRequest added in v0.6.0

func (a *Asserter) AccountCoinsRequest(request *types.AccountCoinsRequest) error

AccountCoinsRequest ensures that a types.AccountCoinsRequest is well-formatted.

func (*Asserter) Block

func (a *Asserter) Block(
	block *types.Block,
) error

Block runs a basic set of assertions for each returned block.

func (*Asserter) BlockRequest added in v0.1.6

func (a *Asserter) BlockRequest(request *types.BlockRequest) error

BlockRequest ensures that a types.BlockRequest is well-formatted.

func (*Asserter) BlockTransactionRequest added in v0.1.6

func (a *Asserter) BlockTransactionRequest(request *types.BlockTransactionRequest) error

BlockTransactionRequest ensures that a types.BlockTransactionRequest is well-formatted.

func (*Asserter) CallRequest added in v0.5.0

func (a *Asserter) CallRequest(request *types.CallRequest) error

CallRequest ensures that a types.CallRequest is well-formatted.

func (*Asserter) ClientConfiguration added in v0.1.6

func (a *Asserter) ClientConfiguration() (*Configuration, error)

ClientConfiguration returns all variables currently set in an Asserter. This function will error if it is called on an uninitialized asserter.

func (*Asserter) ConstructionCombineRequest added in v0.3.0

func (a *Asserter) ConstructionCombineRequest(request *types.ConstructionCombineRequest) error

ConstructionCombineRequest ensures that a types.ConstructionCombineRequest is well-formatted.

func (*Asserter) ConstructionDeriveRequest added in v0.3.0

func (a *Asserter) ConstructionDeriveRequest(request *types.ConstructionDeriveRequest) error

ConstructionDeriveRequest ensures that a types.ConstructionDeriveRequest is well-formatted.

func (*Asserter) ConstructionHashRequest added in v0.3.0

func (a *Asserter) ConstructionHashRequest(request *types.ConstructionHashRequest) error

ConstructionHashRequest ensures that a types.ConstructionHashRequest is well-formatted.

func (*Asserter) ConstructionMetadataRequest added in v0.1.6

func (a *Asserter) ConstructionMetadataRequest(request *types.ConstructionMetadataRequest) error

ConstructionMetadataRequest ensures that a types.ConstructionMetadataRequest is well-formatted.

func (*Asserter) ConstructionParseRequest added in v0.3.0

func (a *Asserter) ConstructionParseRequest(request *types.ConstructionParseRequest) error

ConstructionParseRequest ensures that a types.ConstructionParseRequest is well-formatted.

func (*Asserter) ConstructionParseResponse added in v0.3.0

func (a *Asserter) ConstructionParseResponse(
	response *types.ConstructionParseResponse,
	signed bool,
) error

ConstructionParseResponse returns an error if a *types.ConstructionParseResponse does not have a valid set of operations or if the signers is empty.

func (*Asserter) ConstructionPayloadsRequest added in v0.3.0

func (a *Asserter) ConstructionPayloadsRequest(request *types.ConstructionPayloadsRequest) error

ConstructionPayloadsRequest ensures that a types.ConstructionPayloadsRequest is well-formatted.

func (*Asserter) ConstructionPreprocessRequest added in v0.3.0

func (a *Asserter) ConstructionPreprocessRequest(
	request *types.ConstructionPreprocessRequest,
) error

ConstructionPreprocessRequest ensures that a types.ConstructionPreprocessRequest is well-formatted.

func (*Asserter) ConstructionSubmitRequest added in v0.1.6

func (a *Asserter) ConstructionSubmitRequest(request *types.ConstructionSubmitRequest) error

ConstructionSubmitRequest ensures that a types.ConstructionSubmitRequest is well-formatted.

func (*Asserter) Direction added in v0.6.8

func (a *Asserter) Direction(direction types.Direction) error

Direction returns an error if the value passed is not types.Forward or types.Backward

func (*Asserter) Error added in v0.4.9

func (a *Asserter) Error(
	err *types.Error,
) error

Error ensures a *types.Error matches some error provided in `/network/options`.

func (*Asserter) EventsBlocksRequest added in v0.6.0

func (a *Asserter) EventsBlocksRequest(request *types.EventsBlocksRequest) error

EventsBlocksRequest ensures that a types.EventsBlocksRequest is well-formatted.

func (*Asserter) MempoolTransactionRequest added in v0.1.6

func (a *Asserter) MempoolTransactionRequest(request *types.MempoolTransactionRequest) error

MempoolTransactionRequest ensures that a types.MempoolTransactionRequest is well-formatted.

func (*Asserter) MetadataRequest added in v0.1.6

func (a *Asserter) MetadataRequest(request *types.MetadataRequest) error

MetadataRequest ensures that a types.MetadataRequest is well-formatted.

func (*Asserter) NetworkRequest added in v0.1.6

func (a *Asserter) NetworkRequest(request *types.NetworkRequest) error

NetworkRequest ensures that a types.NetworkRequest is well-formatted.

func (*Asserter) Operation

func (a *Asserter) Operation(
	operation *types.Operation,
	index int64,
	construction bool,
) error

Operation ensures a types.Operation has a valid type, status, and amount.

func (*Asserter) OperationStatus added in v0.1.6

func (a *Asserter) OperationStatus(status *string, construction bool) error

OperationStatus returns an error if an operation.Status is not valid.

func (*Asserter) OperationSuccessful

func (a *Asserter) OperationSuccessful(operation *types.Operation) (bool, error)

OperationSuccessful returns a boolean indicating if a types.Operation is successful and should be applied in a transaction. This should only be called AFTER an operation has been validated.

func (*Asserter) OperationType added in v0.1.6

func (a *Asserter) OperationType(t string) error

OperationType returns an error if an operation.Type is not valid.

func (*Asserter) Operations added in v0.3.0

func (a *Asserter) Operations(
	operations []*types.Operation,
	construction bool,
) error

Operations returns an error if any *types.Operation in a []*types.Operation is invalid.

func (*Asserter) RelatedTransactions added in v0.6.8

func (a *Asserter) RelatedTransactions(relatedTransactions []*types.RelatedTransaction) error

RelatedTransactions returns an error if the related transactions array is non-null and non-empty and any of the related transactions contain invalid types, invalid network identifiers, invalid transaction identifiers, or a direction not defined by the enum.

func (*Asserter) SearchTransactionsRequest added in v0.6.0

func (a *Asserter) SearchTransactionsRequest(
	request *types.SearchTransactionsRequest,
) error

SearchTransactionsRequest ensures that a types.SearchTransactionsRequest is well-formatted.

func (*Asserter) SearchTransactionsResponse added in v0.6.0

func (a *Asserter) SearchTransactionsResponse(
	response *types.SearchTransactionsResponse,
) error

SearchTransactionsResponse ensures a *types.SearchTransactionsResponse is valid.

func (*Asserter) SupportedNetwork added in v0.1.6

func (a *Asserter) SupportedNetwork(
	requestNetwork *types.NetworkIdentifier,
) error

SupportedNetwork returns a boolean indicating if the requestNetwork is allowed. This should be called after the requestNetwork is asserted.

func (*Asserter) Transaction

func (a *Asserter) Transaction(
	transaction *types.Transaction,
) error

Transaction returns an error if the types.TransactionIdentifier is invalid, if any types.Operation within the types.Transaction is invalid, or if any operation index is reused within a transaction.

func (*Asserter) ValidCallMethod added in v0.5.0

func (a *Asserter) ValidCallMethod(method string) error

ValidCallMethod returns an error if a CallRequest.Method is not valid.

func (*Asserter) ValidSupportedNetwork added in v0.3.0

func (a *Asserter) ValidSupportedNetwork(
	requestNetwork *types.NetworkIdentifier,
) error

ValidSupportedNetwork returns an error if a types.NetworkIdentifier is not valid or not supported.

func (*Asserter) ValidatePaymentAndFee added in v0.7.0

func (a *Asserter) ValidatePaymentAndFee(
	paymentTotal *big.Int,
	paymentCount int,
	feeTotal *big.Int,
	feeCount int,
) error

type ChainType added in v0.7.0

type ChainType string
const (
	Account ChainType = "account"
	UTXO    ChainType = "utxo"
)

type Configuration added in v0.1.7

type Configuration struct {
	NetworkIdentifier          *types.NetworkIdentifier `json:"network_identifier"`
	GenesisBlockIdentifier     *types.BlockIdentifier   `json:"genesis_block_identifier"`
	AllowedOperationTypes      []string                 `json:"allowed_operation_types"`
	AllowedOperationStatuses   []*types.OperationStatus `json:"allowed_operation_statuses"`
	AllowedErrors              []*types.Error           `json:"allowed_errors"`
	AllowedTimestampStartIndex int64                    `json:"allowed_timestamp_start_index"`
}

Configuration is the static configuration of an Asserter. This configuration can be exported by the Asserter and used to instantiate an Asserter.

type Operation added in v0.7.0

type Operation struct {
	Count         int  `json:"count"`
	ShouldBalance bool `json:"should_balance"`
}

type ValidationOperation added in v0.7.0

type ValidationOperation struct {
	Name      string     `json:"name"`
	Operation *Operation `json:"operation"`
}

type Validations added in v0.7.0

type Validations struct {
	Enabled          bool                 `json:"enabled"`
	RelatedOpsExists bool                 `json:"related_ops_exists"`
	ChainType        ChainType            `json:"chain_type"`
	Payment          *ValidationOperation `json:"payment"`
	Fee              *ValidationOperation `json:"fee"`
}

Validations is used to define stricter validations on the transaction. Fore more details please refer to https://github.com/coinbase/rosetta-sdk-go/tree/master/asserter#readme

Jump to

Keyboard shortcuts

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