iotago

package module
v2.0.0-...-2cd5660 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2021 License: MIT Imports: 23 Imported by: 0

README


The official Go client library for interacting with the Tangle

Developer documentation portal

Auto-generated docs Discord StackExchange MIT license Supported IRI API endpoints Code quality Build status

AboutPrerequisitesInstallationGetting startedAPI referenceExamplesSupporting the projectJoining the discussion


About

This is the official Go client library for Chrysalis Phase 2.

This is beta software, so there may be performance and stability issues. Please report any issues in our issue tracker.

Prerequisites

Installation

Getting started

Examples

Native code and PoW

Supporting the project

See the contributing guidelines for more information.

Writing tests

Writing documentation and example code

Joining the discussion

If you want to get involved in the community, need help with getting setup, have any issues related with the library or just want to discuss blockchain, distributed ledgers, and IoT with other people, feel free to join our Discord.

Documentation

Overview

Package iotago provides IOTA data models, a node API client and builders to craft messages and transactions.

Creating Messages

// create a new node API client
nodeHTTPAPIClient := iotago.NewNodeHTTPAPIClient("https://example.com")

// fetch the node's info to know the min. required PoW score
info, err := nodeHTTPAPIClient.Info()
if err != nil {
	return err
}

// craft an indexation payload
indexationPayload := &iotago.Indexation{
	Index: []byte("hello world"),
	Data:  []byte{1, 2, 3, 4},
}

ctx, cancelFunc := context.WithTimeout(context.Background(), 15*time.Second)
defer cancelFunc()

// build a message by fetching tips via the node API client and then do local Proof-of-Work
msg, err := iotago.NewMessageBuilder().
	Payload(indexationPayload).
	Tips(nodeHTTPAPIClient).
	ProofOfWork(ctx, info.MinPowScore).
	Build()

// submit the message to the node
if _, err := nodeHTTPAPIClient.SubmitMessage(msg); err != nil {
	return err
}

Index

Constants

View Source
const (
	// The length of an Ed25519 address
	Ed25519AddressBytesLength = blake2b.Size256
	// The size of a serialized Ed25519 address with its type denoting byte.
	Ed25519AddressSerializedBytesSize = SmallTypeDenotationByteSize + Ed25519AddressBytesLength
)
View Source
const (
	// The byte size of a single byte.
	OneByte = 1
	// The byte size of an int16.
	Int16ByteSize = 2
	// The byte size of a uint16.
	UInt16ByteSize = 2
	// The byte size of an int32.
	Int32ByteSize = 4
	// The byte size of a uint32.
	UInt32ByteSize = 4
	// The byte size of a float32.
	Float32ByteSize = 4
	// The byte size of an int64.
	Int64ByteSize = 8
	// The byte size of an uint64.
	UInt64ByteSize = 8
	// The byte size of a float64.
	Float64ByteSize = 8
	// The size of a type denotation.
	TypeDenotationByteSize = UInt32ByteSize
	// The size of a type denotation for a small range of possible values.
	SmallTypeDenotationByteSize = OneByte
	// // The byte size of struct array lengths.
	StructArrayLengthByteSize = UInt16ByteSize
	// // The byte size of byte array lengths.
	ByteArrayLengthByteSize = UInt32ByteSize
	// The size of the payload length denoting bytes.
	PayloadLengthByteSize = UInt32ByteSize
	// The minimum size of a payload (together with its length denotation).
	MinPayloadByteSize = UInt32ByteSize + OneByte
	// The IOTA token supply.
	TokenSupply = 2_779_530_283_277_761
)
View Source
const (
	// Defines the indexation payload's ID.
	IndexationPayloadTypeID uint32 = 2
	// type bytes + index prefix + one char + data length
	IndexationBinSerializedMinSize = TypeDenotationByteSize + UInt16ByteSize + OneByte + UInt32ByteSize
	// Defines the max length of the index within an Indexation.
	IndexationIndexMaxLength = 64
	// Defines the min length of the index within an Indexation.
	IndexationIndexMinLength = 1
)
View Source
const (
	// Defines the length of a message ID.
	MessageIDLength = blake2b.Size256
	// Defines the length of the network ID in bytes.
	MessageNetworkIDLength = UInt64ByteSize
	// Defines the minimum size of a message: network ID + parent count + 1 parent + uint16 payload length + nonce
	MessageBinSerializedMinSize = MessageNetworkIDLength + OneByte + MessageIDLength + UInt32ByteSize + UInt64ByteSize
	// Defines the maximum size of a message.
	MessageBinSerializedMaxSize = 32768
	// Defines the minimum amount of parents in a message.
	MinParentsInAMessage = 1
	// Defines the maximum amount of parents in a message.
	MaxParentsInAMessage = 8
)
View Source
const (
	// Defines the Milestone payload's ID.
	MilestonePayloadTypeID uint32 = 1
	// Defines the length of the inclusion merkle proof within a milestone payload.
	MilestoneInclusionMerkleProofLength = blake2b.Size256
	// Defines the length of the milestone signature.
	MilestoneSignatureLength = ed25519.SignatureSize
	// Defines the length of a Milestone ID.
	MilestoneIDLength = blake2b.Size256
	// Defines the length of a public key within a milestone.
	MilestonePublicKeyLength = ed25519.PublicKeySize
	// Defines the serialized size of a milestone payload.
	// payload type + index + timestamp + parent count + 1 parent + inclusion-merkle-proof + pubkeys-length + pubkey + sigs-length + sigs
	MilestoneBinSerializedMinSize = TypeDenotationByteSize + UInt32ByteSize + UInt64ByteSize + OneByte + MessageIDLength +
		MilestoneInclusionMerkleProofLength + OneByte + ed25519.PublicKeySize + OneByte + MilestoneSignatureLength
	// MaxSignaturesInAMilestone is the maximum amount of signatures in a milestone.
	MaxSignaturesInAMilestone = 255
	// MinSignaturesInAMilestone is the minimum amount of signatures in a milestone.
	MinSignaturesInAMilestone = 1
	// MaxPublicKeysInAMilestone is the maximum amount of public keys in a milestone.
	MaxPublicKeysInAMilestone = 255
	// MinPublicKeysInAMilestone is the minimum amount of public keys in a milestone.
	MinPublicKeysInAMilestone = 1
)
View Source
const (
	// NodeEventMilestonesLatest is the name of the latest milestone event channel.
	NodeEventMilestonesLatest = "milestones/latest"
	// NodeEventMilestonesConfirmed is the name of the confirmed milestone event channel.
	NodeEventMilestonesConfirmed = "milestones/confirmed"

	// NodeEventMessages is the name of the received messages event channel.
	NodeEventMessages = "messages"
	// NodeEventMessagesReferenced is the name of the referenced messages metadata event channel.
	NodeEventMessagesReferenced = "messages/referenced"
	// NodeEventMessagesIndexation is the name of the indexed messages  event channel.
	NodeEventMessagesIndexation = "messages/indexation/{index}"
	// NodeEventMessagesMetadata is the name of the message metadata event channel.
	NodeEventMessagesMetadata = "messages/{messageId}/metadata"

	// NodeEventTransactionsIncludedMessage is the name of the included transaction message event channel.
	NodeEventTransactionsIncludedMessage = "transactions/{transactionId}/included-message"

	// NodeEventOutputs is the name of the outputs event channel.
	NodeEventOutputs = "outputs/{outputId}"

	// NodeEventReceipts is the name of the receipts event channel.
	NodeEventReceipts = "receipts"

	// NodeEventAddressesOutput is the name of the address outputs event channel.
	NodeEventAddressesOutput = "addresses/{address}/outputs"
	// NodeEventAddressesEd25519Output is the name of the ed25519 address outputs event channel.
	NodeEventAddressesEd25519Output = "addresses/ed25519/{address}/outputs"
)
View Source
const (
	// NodeAPIRouteHealth is the route for querying a node's health status.
	NodeAPIRouteHealth = "/health"

	// NodeAPIRouteInfo is the route for getting the node info.
	// GET returns the node info.
	NodeAPIRouteInfo = "/api/v1/info"

	// NodeAPIRouteTips is the route for getting two tips.
	// GET returns the tips.
	NodeAPIRouteTips = "/api/v1/tips"

	// NodeAPIRouteMessageMetadata is the route for getting message metadata by it's messageID.
	// GET returns message metadata (including info about "promotion/reattachment needed").
	NodeAPIRouteMessageMetadata = "/api/v1/messages/%s/metadata"

	// NodeAPIRouteMessageBytes is the route for getting message raw data by it's messageID.
	// GET returns raw message data (bytes).
	NodeAPIRouteMessageBytes = "/api/v1/messages/%s/raw"

	// NodeAPIRouteMessageChildren is the route for getting message IDs of the children of a message, identified by it's messageID.
	// GET returns the message IDs of all children.
	NodeAPIRouteMessageChildren = "/api/v1/messages/%s/children"

	// NodeAPIRouteMessages is the route for getting message IDs or creating new messages.
	// GET with query parameter (mandatory) returns all message IDs that fit these filter criteria (query parameters: "index").
	// POST creates a single new message and returns the new message ID.
	NodeAPIRouteMessages = "/api/v1/messages"

	// NodeAPIRouteMilestone is the route for getting a milestone by it's milestoneIndex.
	// GET returns the milestone.
	NodeAPIRouteMilestone = "/api/v1/milestones/%s"

	// NodeAPIRouteOutput is the route for getting outputs by their outputID (transactionHash + outputIndex).
	// GET returns the output.
	NodeAPIRouteOutput = "/api/v1/outputs/%s"

	// NodeAPIRouteAddressEd25519Balance is the route for getting the total balance of all unspent outputs of an ed25519 address.
	// The ed25519 address must be encoded in hex.
	// GET returns the balance of all unspent outputs of this address.
	NodeAPIRouteAddressEd25519Balance = "/api/v1/addresses/ed25519/%s"

	// NodeAPIRouteAddressEd25519Outputs is the route for getting all output IDs for an ed25519 address.
	// The ed25519 address must be encoded in hex.
	// GET returns the outputIDs for all outputs of this address (optional query parameters: "include-spent").
	NodeAPIRouteAddressEd25519Outputs = "/api/v1/addresses/ed25519/%s/outputs"

	// NodeAPIRouteTreasury is the route for getting the current treasury.
	// GET returns the treasury.
	NodeAPIRouteTreasury = "/api/v1/treasury"

	// NodeAPIRouteReceipts is the route for getting all persisted receipts on a node.
	// GET returns the receipts.
	NodeAPIRouteReceipts = "/api/v1/receipts"

	// NodeAPIRouteReceiptsByMigratedAtIndex is the route for getting all persisted receipts for a given migrated at index on a node.
	// GET returns the receipts for the given migrated at index.
	NodeAPIRouteReceiptsByMigratedAtIndex = "/api/v1/receipts/%s"

	// NodeAPIRoutePeer is the route for getting peers by their peerID.
	// GET returns the peer
	// DELETE deletes the peer.
	NodeAPIRoutePeer = "/api/v1/peers/%s"

	// NodeAPIRoutePeers is the route for getting all peers of the node.
	// GET returns a list of all peers.
	// POST adds a new peer.
	NodeAPIRoutePeers = "/api/v1/peers"
)
View Source
const (
	// Denotes a type of output which is locked by a signature and deposits onto a single address.
	OutputSigLockedSingleOutput OutputType = iota
	// Like OutputSigLockedSingleOutput but it is used to increase the allowance/amount of dust outputs on a given address.
	OutputSigLockedDustAllowanceOutput
	// Denotes the type of the TreasuryOutput.
	OutputTreasuryOutput
	// OutputSigLockedDustAllowanceOutputMinDeposit defines the minimum deposit amount of a SigLockedDustAllowanceOutput.
	OutputSigLockedDustAllowanceOutputMinDeposit uint64 = 1_000_000
)
View Source
const (
	// Defines the Receipt payload's ID.
	ReceiptPayloadTypeID uint32 = 3
	// Defines the minimum amount of MigratedFundsEntry items within a Receipt.
	MinMigratedFundsEntryCount = 1
	// Defines the maximum amount of MigratedFundsEntry items within a Receipt.
	MaxMigratedFundsEntryCount = 127
)
View Source
const (
	// The size of a sig locked dust allowance output containing an Ed25519 address as its deposit address.
	SigLockedDustAllowanceOutputEd25519AddrBytesSize = SmallTypeDenotationByteSize + Ed25519AddressSerializedBytesSize + UInt64ByteSize

	// Defines the minimum size a sig locked dust allowance output must be.
	SigLockedDustAllowanceOutputBytesMinSize = SigLockedDustAllowanceOutputEd25519AddrBytesSize
	// Defines the offset at which the address portion within a sig locked dust allowance begins.
	SigLockedDustAllowanceOutputAddressOffset = SmallTypeDenotationByteSize
)
View Source
const (
	// The size of a sig locked single deposit containing an Ed25519 address as its deposit address.
	SigLockedSingleOutputEd25519AddrBytesSize = SmallTypeDenotationByteSize + Ed25519AddressSerializedBytesSize + UInt64ByteSize

	// Defines the minimum size a sig locked single deposit must be.
	SigLockedSingleOutputBytesMinSize = SigLockedSingleOutputEd25519AddrBytesSize
	// Defines the offset at which the address portion within a sig locked single deposit begins.
	SigLockedSingleOutputAddressOffset = SmallTypeDenotationByteSize
)
View Source
const (
	// Defines the transaction payload's type ID.
	TransactionPayloadTypeID uint32 = 0

	// Defines the length of a Transaction ID.
	TransactionIDLength = blake2b.Size256

	// Defines the minimum size of a serialized Transaction.
	TransactionBinSerializedMinSize = UInt32ByteSize

	// Defines the divisor used to compute the allowed dust outputs on an address.
	// The amount of dust outputs on an address is calculated by:
	//	min(sum(dust_allowance_output_deposit) / DustAllowanceDivisor, dustOutputCountLimit)
	DustAllowanceDivisor int64 = 100_000
	// Defines the maximum amount of dust outputs allowed to "reside" on an address.
	MaxDustOutputsOnAddress = 100
)
View Source
const (
	// Denotes a standard transaction essence.
	TransactionEssenceNormal TransactionEssenceType = iota

	// Defines the minimum size of a TransactionEssence.
	TransactionEssenceMinByteSize = TypeDenotationByteSize + StructArrayLengthByteSize + StructArrayLengthByteSize + PayloadLengthByteSize

	// Defines the maximum amount of inputs within a TransactionEssence.
	MaxInputsCount = 127
	// Defines the minimum amount of inputs within a TransactionEssence.
	MinInputsCount = 1
	// Defines the maximum amount of outputs within a TransactionEssence.
	MaxOutputsCount = 127
	// Defines the minimum amount of inputs within a TransactionEssence.
	MinOutputsCount = 1
)
View Source
const (
	// The length of a TreasuryInput
	TreasuryInputBytesLength = blake2b.Size256
	// The size of a serialized TreasuryInput with its type denoting byte.
	TreasuryInputSerializedBytesSize = SmallTypeDenotationByteSize + TreasuryInputBytesLength
)
View Source
const (
	// Defines the TreasuryTransaction payload's ID.
	TreasuryTransactionPayloadTypeID uint32 = 4
	// Defines the serialized size of a TreasuryTransaction.
	TreasuryTransactionByteSize = TypeDenotationByteSize + TreasuryInputSerializedBytesSize + TreasuryOutputBytesSize
)
View Source
const (
	// Denotes a signature unlock block.
	UnlockBlockSignature UnlockBlockType = iota
	// Denotes a reference unlock block.
	UnlockBlockReference

	// Defines the minimum size of a signature unlock block.
	SignatureUnlockBlockMinSize = SmallTypeDenotationByteSize + Ed25519SignatureSerializedBytesSize
	// Defines the size of a reference unlock block.
	ReferenceUnlockBlockSize = SmallTypeDenotationByteSize + UInt16ByteSize
)
View Source
const (
	// The minimum index of a referenced UTXO.
	RefUTXOIndexMin = 0
	// The maximum index of a referenced UTXO.
	RefUTXOIndexMax = 126

	// The size of a UTXO input: input type + tx id + index
	UTXOInputSize = SmallTypeDenotationByteSize + TransactionIDLength + UInt16ByteSize
)
View Source
const (
	// Defines the minimum amount a MigratedFundEntry must deposit.
	MinMigratedFundsEntryDeposit = 1_000_000
)
View Source
const (
	// Defines the binary serialized size of a TreasuryOutput.
	TreasuryOutputBytesSize = SmallTypeDenotationByteSize + UInt64ByteSize
)

Variables

View Source
var (
	// Returned if the needed keys to sign a message are absent/not mapped.
	ErrAddressKeysNotMapped = errors.New("key(s) for address not mapped")
	// Returned if the specified keys to sign a message for a given address are of the wrong type.
	ErrAddressKeysWrongType = errors.New("key(s) for address are of wrong type")
)
View Source
var (
	// Returned for bytes which are invalid for deserialization.
	ErrInvalidBytes = errors.New("invalid bytes")
	// Returned when a denoted type for a given object is mismatched.
	// For example, while trying to deserialize a signature unlock block, a reference unlock block is seen.
	ErrDeserializationTypeMismatch = errors.New("data type is invalid for deserialization")
	// Returned for unsupported payload types.
	ErrUnsupportedPayloadType = errors.New("unsupported payload type")
	// Returned for unsupported object types.
	ErrUnsupportedObjectType = errors.New("unsupported object type")
	// Returned for unknown payload types.
	ErrUnknownPayloadType = errors.New("unknown payload type")
	// Returned for unknown address types.
	ErrUnknownAddrType = errors.New("unknown address type")
	// Returned for unknown input types.
	ErrUnknownInputType = errors.New("unknown input type")
	// Returned for unknown output types.
	ErrUnknownOutputType = errors.New("unknown output type")
	// Returned for unknown transaction essence types.
	ErrUnknownTransactionEssenceType = errors.New("unknown transaction essence type")
	// Returned for unknown unlock blocks.
	ErrUnknownUnlockBlockType = errors.New("unknown unlock block type")
	// Returned for unknown signature types.
	ErrUnknownSignatureType = errors.New("unknown signature type")
	// Returned for unknown array validation modes.
	ErrUnknownArrayValidationMode = errors.New("unknown array validation mode")
	// Returned if the count of elements is too small.
	ErrArrayValidationMinElementsNotReached = errors.New("min count of elements within the array not reached")
	// Returned if the count of elements is too big.
	ErrArrayValidationMaxElementsExceeded = errors.New("max count of elements within the array exceeded")
	// Returned if the array elements are not unique.
	ErrArrayValidationViolatesUniqueness = errors.New("array elements must be unique")
	// Returned if the array elements are not in lexical order.
	ErrArrayValidationOrderViolatesLexicalOrder = errors.New("array elements must be in their lexical order (byte wise)")
	// Returned if there is not enough data available to deserialize a given object.
	ErrDeserializationNotEnoughData = errors.New("not enough data for deserialization")
	// Returned when a bool value is tried to be read but it is neither 0 or 1.
	ErrDeserializationInvalidBoolValue = errors.New("invalid bool value")
	// Returned if a length denotation exceeds a specified limit.
	ErrDeserializationLengthInvalid = errors.New("length denotation invalid")
	// Returned if not all bytes were consumed during deserialization of a given type.
	ErrDeserializationNotAllConsumed = errors.New("not all data has been consumed but should have been")
)
View Source
var (
	// Returned when an Indexation's index exceeds IndexationIndexMaxLength.
	ErrIndexationIndexExceedsMaxSize = errors.New("index exceeds max size")
	// Returned when an Indexation's index is under IndexationIndexMinLength.
	ErrIndexationIndexUnderMinSize = errors.New("index is below min size")
)
View Source
var (
	// Returned if a to be deserialized Milestone does not contain at least one signature.
	ErrMilestoneTooFewSignatures = errors.New("a milestone must hold at least one signature")
	// Returned if there are less signatures within a Milestone than the min. threshold.
	ErrMilestoneTooFewSignaturesForVerificationThreshold = errors.New("too few signatures for verification")
	// Returned if a to be deserialized Milestone does not contain at least one public key.
	ErrMilestoneTooFewPublicKeys = errors.New("a milestone must hold at least one public key")
	// Returned when a MilestoneSigningFunc produces less signatures than expected.
	ErrMilestoneProducedSignaturesCountMismatch = errors.New("produced and wanted signature count mismatch")
	// Returned when the count of signatures and public keys within a Milestone don't match.
	ErrMilestoneSignaturesPublicKeyCountMismatch = errors.New("milestone signatures and public keys count must be equal")
	// Returned when a Milestone holds more than 255 signatures.
	ErrMilestoneTooManySignatures = fmt.Errorf("a milestone can hold max %d signatures", MaxSignaturesInAMilestone)
	// Returned when an invalid min signatures threshold is given the the verification function.
	ErrMilestoneInvalidMinSignatureThreshold = fmt.Errorf("min threshold must be at least 1")
	// Returned when a Milestone contains a public key which isn't in the applicable public key set.
	ErrMilestoneNonApplicablePublicKey = fmt.Errorf("non applicable public key found")
	// Returned when a min. signature threshold is greater than a given applicable public key set.
	ErrMilestoneSignatureThresholdGreaterThanApplicablePublicKeySet = fmt.Errorf("the min. signature threshold must be less or equal the applicable public key set")
	// Returned when a Milestone's signature is invalid.
	ErrMilestoneInvalidSignature = fmt.Errorf("invalid milestone signature")
	// Returned when a InMemoryEd25519MilestoneSigner is missing a private key.
	ErrMilestoneInMemorySignerPrivateKeyMissing = fmt.Errorf("private key missing")
	// Returned when a Milestone contains duplicated public keys.
	ErrMilestoneDuplicatedPublicKey = fmt.Errorf("milestone contains duplicated public keys")
)
View Source
var (
	// Returned for 400 bad request HTTP responses.
	ErrHTTPBadRequest = errors.New("bad request")
	// Returned for 500 internal server error HTTP responses.
	ErrHTTPInternalServerError = errors.New("internal server error")
	// Returned for 404 not found error HTTP responses.
	ErrHTTPNotFound = errors.New("not found")
	// Returned for 401 unauthorized error HTTP responses.
	ErrHTTPUnauthorized = errors.New("unauthorized")
	// Returned for unknown error HTTP responses.
	ErrHTTPUnknownError = errors.New("unknown error")
	// Returned for 501 not implemented error HTTP responses.
	ErrHTTPNotImplemented = errors.New("operation not implemented/supported/available")
)
View Source
var (
	// Returned when an Ed25519 address and public key do not correspond to each other.
	ErrEd25519PubKeyAndAddrMismatch = errors.New("public key and address do not correspond to each other (Ed25519)")
	// Returned for invalid Ed25519 signatures.
	ErrEd25519SignatureInvalid = errors.New("signature is invalid (Ed25519")
)
View Source
var (
	// Returned if the count of unlock blocks doesn't match the count of inputs.
	ErrUnlockBlocksMustMatchInputCount = errors.New("the count of unlock blocks must match the inputs of the transaction")
	// Returned if the transaction essence within a Transaction is invalid.
	ErrInvalidTransactionEssence = errors.New("transaction essence is invalid")
	// Returned if an UTXO is missing to commence a certain operation.
	ErrMissingUTXO = errors.New("missing utxo")
	// Returned if a transaction does not spend the entirety of the inputs to the outputs.
	ErrInputOutputSumMismatch = errors.New("inputs and outputs do not spend/deposit the same amount")
	// ErrInputSignatureUnlockBlockInvalid returned for errors where an input has a wrong companion signature unlock block.
	ErrInputSignatureUnlockBlockInvalid = errors.New("companion signature unlock block is invalid for input")
	// Returned if an address of an input has a companion signature unlock block with the wrong signature type.
	ErrSignatureAndAddrIncompatible = errors.New("address and signature type are not compatible")
	// Returned for errors where the dust allowance is semantically invalid.
	ErrInvalidDustAllowance = errors.New("invalid dust allowance")
)
View Source
var (
	// Returned if the count of inputs is too small.
	ErrMinInputsNotReached = fmt.Errorf("min %d input(s) are required within a transaction", MinInputsCount)
	// Returned if the count of outputs is too small.
	ErrMinOutputsNotReached = fmt.Errorf("min %d output(s) are required within a transaction", MinOutputsCount)
	// Returned if multiple inputs reference the same UTXO.
	ErrInputUTXORefsNotUnique = errors.New("inputs must each reference a unique UTXO")
	// Returned if multiple outputs deposit to the same address.
	ErrOutputAddrNotUnique = errors.New("outputs must each deposit to a unique address")
	// Returned if the sum of the output deposits exceeds the total supply of tokens.
	ErrOutputsSumExceedsTotalSupply = errors.New("accumulated output balance exceeds total supply")
	// Returned if an output deposits more than the total supply.
	ErrOutputDepositsMoreThanTotalSupply = errors.New("an output can not deposit more than the total supply")
	// Returned if a SigLockedDustAllowanceOutput deposits less than OutputSigLockedDustAllowanceOutputMinDeposit.
	ErrOutputDustAllowanceLessThanMinDeposit = errors.New("dust allowance output deposits less than the minimum required amount")
)
View Source
var (
	// Returned if unlock blocks making part of a transaction aren't unique.
	ErrSigUnlockBlocksNotUnique = errors.New("signature unlock blocks must be unique")
	// Returned if a reference unlock block does not reference a signature unlock block.
	ErrRefUnlockBlockInvalidRef = errors.New("reference unlock block must point to a previous signature unlock block")
	// Returned if a signature unlock block contains a nil signature.
	ErrSigUnlockBlockHasNilSig = errors.New("signature is nil")
)
View Source
var (
	// Returned if the deposit amount of an output is less or equal zero.
	ErrDepositAmountMustBeGreaterThanZero = errors.New("deposit amount must be greater than zero")
)
View Source
var (
	// Returned when invalid JSOn is tried to get parsed.
	ErrInvalidJSON = errors.New("invalid json")
)
View Source
var (
	// Returned when a receipt is invalid
	ErrInvalidReceipt = errors.New("invalid receipt")
)
View Source
var (
	// Returned when a serialized message exceeds MessageBinSerializedMaxSize.
	ErrMessageExceedsMaxSize = errors.New("message exceeds max size")
)
View Source
var (
	// ErrNodeEventAPIClientInactive gets returned when a NodeEventAPIClient is inactive.
	ErrNodeEventAPIClientInactive = errors.New("node event api client is inactive")
)
View Source
var (
	// Returned if a Receipt does not contain a TreasuryTransaction.
	ErrReceiptMustContainATreasuryTransaction = errors.New("receipt must contain a treasury transaction")
)
View Source
var (
	// Returned on invalid UTXO indices.
	ErrRefUTXOIndexInvalid = fmt.Errorf("the referenced UTXO index must be between %d and %d (inclusive)", RefUTXOIndexMin, RefUTXOIndexMax)
)
View Source
var (
	// ErrTransactionBuilderUnsupportedAddress gets returned when an unsupported address type
	// is given for a builder operation.
	ErrTransactionBuilderUnsupportedAddress = errors.New("unsupported address type")
)

Functions

func MessageIDToHexString

func MessageIDToHexString(msgID MessageID) string

MessageIDToHexString converts the given message ID to their hex representation.

func ParseBech32

func ParseBech32(s string) (NetworkPrefix, Address, error)

ParseBech32 decodes a bech32 encoded string.

func ValidateInputs

func ValidateInputs(inputs Serializables, funcs ...InputsValidatorFunc) error

ValidateInputs validates the inputs by running them against the given InputsValidatorFunc.

func ValidateOutputs

func ValidateOutputs(outputs Serializables, funcs ...OutputsValidatorFunc) error

ValidateOutputs validates the outputs by running them against the given OutputsValidatorFunc.

func ValidateReceipt

func ValidateReceipt(receipt *Receipt, prevTreasuryOutput *TreasuryOutput) error

ValidateReceipt validates whether given the following receipt:

  • None of the MigratedFundsEntry objects deposits more than the max supply and deposits at least MinMigratedFundsEntryDeposit tokens.
  • The sum of all migrated fund entries is not bigger than the total supply.
  • The previous unspent TreasuryOutput minus the sum of all migrated funds equals the amount of the new TreasuryOutput.

This function panics if the receipt is nil, the receipt does not include any migrated fund entries or the given treasury output is nil.

func ValidateUnlockBlocks

func ValidateUnlockBlocks(unlockBlocks Serializables, funcs ...UnlockBlockValidatorFunc) error

ValidateUnlockBlocks validates the unlock blocks by running them against the given UnlockBlockValidatorFunc.

Types

type AddPeerRequest

type AddPeerRequest struct {
	// The libp2p multi address of the peer.
	MultiAddress string `json:"multiAddress"`
	// The alias of to iditify the peer.
	Alias *string `json:"alias,omitempty"`
}

AddPeerRequest defines the request for a POST peer REST API call.

type Address

type Address interface {
	Serializable
	fmt.Stringer

	// Type returns the type of the address.
	Type() AddressType

	// Bech32 encodes the address as a bech32 string.
	Bech32(hrp NetworkPrefix) string
}

Address describes a general address.

type AddressBalanceResponse

type AddressBalanceResponse struct {
	// The type of the address.
	AddressType byte `json:"addressType"`
	// The hex encoded address.
	Address string `json:"address"`
	// The balance of the address.
	Balance uint64 `json:"balance"`
}

AddressBalanceResponse defines the response of a GET addresses REST API call.

type AddressKeys

type AddressKeys struct {
	// The target address.
	Address Address `json:"address"`
	// The signing keys.
	Keys interface{} `json:"keys"`
}

AddressKeys pairs an address and its source key(s).

func NewAddressKeysForEd25519Address

func NewAddressKeysForEd25519Address(addr *Ed25519Address, prvKey ed25519.PrivateKey) AddressKeys

NewAddressKeysForEd25519Address returns new AddressKeys for Ed25519Address.

type AddressOutputsResponse

type AddressOutputsResponse struct {
	// The type of the address.
	AddressType byte `json:"addressType"`
	// The hex encoded address.
	Address string `json:"address"`
	// The maximum count of results that are returned by the node.
	MaxResults uint32 `json:"maxResults"`
	// The actual count of results that are returned.
	Count uint32 `json:"count"`
	// The output IDs (transaction ID + output index) of the outputs on this address.
	OutputIDs []OutputIDHex `json:"outputIDs"`
}

AddressOutputsResponse defines the response of a GET outputs by address REST API call.

type AddressSigner

type AddressSigner interface {
	// Sign produces the signature for the given message.
	Sign(addr Address, msg []byte) (signature Serializable, err error)
}

AddressSigner produces signatures for messages which get verified against a given address.

func NewInMemoryAddressSigner

func NewInMemoryAddressSigner(addrKeys ...AddressKeys) AddressSigner

NewInMemoryAddressSigner creates a new InMemoryAddressSigner holding the given AddressKeys.

type AddressSignerFunc

type AddressSignerFunc func(addr Address, msg []byte) (signature Serializable, err error)

AddressSignerFunc implements the AddressSigner interface.

func (AddressSignerFunc) Sign

func (s AddressSignerFunc) Sign(addr Address, msg []byte) (signature Serializable, err error)

type AddressType

type AddressType = byte

Defines the type of addresses.

const (
	// Denotes an Ed25519 address.
	AddressEd25519 AddressType = iota
)

type ArrayOf32Bytes

type ArrayOf32Bytes = [32]byte

ArrayOf32Bytes is an array of 32 bytes.

type ArrayOf49Bytes

type ArrayOf49Bytes = [49]byte

ArrayOf49Bytes is an array of 49 bytes.

type ArrayOf64Bytes

type ArrayOf64Bytes = [64]byte

ArrayOf64Bytes is an array of 64 bytes.

type ArrayRules

type ArrayRules struct {
	// The min array bound.
	Min uint16
	// The max array bound.
	Max uint16
	// The mode of validation.
	ValidationMode ArrayValidationMode
}

ArrayRules defines rules around a to be deserialized array. Min and Max at 0 define an unbounded array.

func (*ArrayRules) CheckBounds

func (ar *ArrayRules) CheckBounds(count uint16) error

CheckBounds checks whether the given count violates the array bounds.

func (*ArrayRules) ElementUniqueValidator

func (ar *ArrayRules) ElementUniqueValidator() ElementValidationFunc

ElementUniqueValidator returns an ElementValidationFunc which returns an error if the given element is not unique.

func (*ArrayRules) ElementValidationFunc

func (ar *ArrayRules) ElementValidationFunc(mode ArrayValidationMode) ElementValidationFunc

ElementValidationFunc returns a new ElementValidationFunc according to the given mode.

func (*ArrayRules) LexicalOrderValidator

func (ar *ArrayRules) LexicalOrderValidator() ElementValidationFunc

LexicalOrderValidator returns an ElementValidationFunc which returns an error if the given byte slices are not ordered lexicographically.

func (*ArrayRules) LexicalOrderWithoutDupsValidator

func (ar *ArrayRules) LexicalOrderWithoutDupsValidator() ElementValidationFunc

LexicalOrderWithoutDupsValidator returns an ElementValidationFunc which returns an error if the given byte slices are not ordered lexicographically or any elements are duplicated.

type ArrayValidationMode

type ArrayValidationMode byte

ArrayValidationMode defines the mode of array validation.

const (
	// Instructs the array validation to perform no validation.
	ArrayValidationModeNone ArrayValidationMode = 0
	// Instructs the array validation to check for duplicates.
	ArrayValidationModeNoDuplicates ArrayValidationMode = 1 << 0
	// Instructs the array validation to check for lexical order.
	ArrayValidationModeLexicalOrdering ArrayValidationMode = 1 << 1
)

func (ArrayValidationMode) HasMode

func (av ArrayValidationMode) HasMode(mode ArrayValidationMode) bool

HasMode checks whether the array element validation mode includes the given mode.

type ChildrenResponse

type ChildrenResponse struct {
	// The hex encoded message ID of the message.
	MessageID string `json:"messageId"`
	// The maximum count of results that are returned by the node.
	MaxResults uint32 `json:"maxResults"`
	// The actual count of results that are returned.
	Count uint32 `json:"count"`
	// The hex encoded message IDs of the children of this message.
	Children []string `json:"childrenMessageIds"`
}

ChildrenResponse defines the response of a GET children REST API call.

type DeSerializationMode

type DeSerializationMode byte

DeSerializationMode defines the mode of de/serialization.

const (
	// Instructs de/serialization to perform no validation.
	DeSeriModeNoValidation DeSerializationMode = 0
	// Instructs de/serialization to perform validation.
	DeSeriModePerformValidation DeSerializationMode = 1 << 0
	// Instructs de/deserialization to perform ordering of certain struct arrays by their lexical serialized form.
	DeSeriModePerformLexicalOrdering DeSerializationMode = 1 << 1
)

func (DeSerializationMode) HasMode

func (sm DeSerializationMode) HasMode(mode DeSerializationMode) bool

HasMode checks whether the de/serialization mode includes the given mode.

type Deserializer

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

Deserializes is a utility to deserialize bytes.

func NewDeserializer

func NewDeserializer(src []byte) *Deserializer

NewDeserializer creates a new Deserializer.

func (*Deserializer) AbortIf

func (d *Deserializer) AbortIf(errProducer ErrProducer) *Deserializer

AbortIf calls the given ErrProducer if the Deserializer did not encounter an error yet. Return nil from the ErrProducer to indicate continuation of the deserialization.

func (*Deserializer) ConsumedAll

func (d *Deserializer) ConsumedAll(errProducer ErrProducerWithLeftOver) *Deserializer

ConsumedAll calls the given ErrProducerWithLeftOver if not all bytes have been consumed from the Deserializer's src.

func (*Deserializer) Do

func (d *Deserializer) Do(f func()) *Deserializer

Do calls f in the Deserializer chain.

func (*Deserializer) Done

func (d *Deserializer) Done() (int, error)

Done finishes the Deserializer by returning the read bytes and occurred errors.

func (*Deserializer) ReadArrayOf32Bytes

func (d *Deserializer) ReadArrayOf32Bytes(arr *ArrayOf32Bytes, errProducer ErrProducer) *Deserializer

ReadArrayOf32Bytes reads an array of 32 bytes.

func (*Deserializer) ReadArrayOf49Bytes

func (d *Deserializer) ReadArrayOf49Bytes(arr *ArrayOf49Bytes, errProducer ErrProducer) *Deserializer

ReadArrayOf49Bytes reads an array of 49 bytes.

func (*Deserializer) ReadArrayOf64Bytes

func (d *Deserializer) ReadArrayOf64Bytes(arr *ArrayOf64Bytes, errProducer ErrProducer) *Deserializer

ReadArrayOf64Bytes reads an array of 64 bytes.

func (*Deserializer) ReadBool

func (d *Deserializer) ReadBool(dest *bool, errProducer ErrProducer) *Deserializer

ReadBool reads a bool into dest.

func (*Deserializer) ReadNum

func (d *Deserializer) ReadNum(dest interface{}, errProducer ErrProducer) *Deserializer

ReadNum reads a number into dest.

func (*Deserializer) ReadObject

ReadObject reads an object, using the given SerializableSelectorFunc.

func (*Deserializer) ReadPayload

func (d *Deserializer) ReadPayload(f ReadObjectConsumerFunc, deSeriMode DeSerializationMode, errProducer ErrProducer, selector ...SerializableSelectorFunc) *Deserializer

ReadPayload reads a payload.

func (*Deserializer) ReadSliceOfArraysOf32Bytes

func (d *Deserializer) ReadSliceOfArraysOf32Bytes(slice *SliceOfArraysOf32Bytes, deSeriMode DeSerializationMode, lenType SeriSliceLengthType, arrayRules *ArrayRules, errProducer ErrProducer) *Deserializer

ReadSliceOfArraysOf32Bytes reads a slice of arrays of 32 bytes.

func (*Deserializer) ReadSliceOfArraysOf64Bytes

func (d *Deserializer) ReadSliceOfArraysOf64Bytes(slice *SliceOfArraysOf64Bytes, deSeriMode DeSerializationMode, lenType SeriSliceLengthType, arrayRules *ArrayRules, errProducer ErrProducer) *Deserializer

ReadSliceOfArraysOf64Bytes reads a slice of arrays of 64 bytes.

func (*Deserializer) ReadSliceOfObjects

func (d *Deserializer) ReadSliceOfObjects(f ReadObjectsConsumerFunc, deSeriMode DeSerializationMode, typeDen TypeDenotationType, serSel SerializableSelectorFunc, arrayRules *ArrayRules, errProducer ErrProducer) *Deserializer

ReadSliceOfObjects reads a slice of objects.

func (*Deserializer) ReadString

func (d *Deserializer) ReadString(s *string, errProducer ErrProducer, maxSize ...uint16) *Deserializer

ReadString reads a string.

func (*Deserializer) ReadVariableByteSlice

func (d *Deserializer) ReadVariableByteSlice(slice *[]byte, lenType SeriSliceLengthType, errProducer ErrProducer, maxRead ...int) *Deserializer

ReadVariableByteSlice reads a variable byte slice which is denoted by the given SeriSliceLengthType.

func (*Deserializer) Skip

func (d *Deserializer) Skip(skip int, errProducer ErrProducer) *Deserializer

Skip skips the number of bytes during deserialization.

type DustAllowanceFunc

type DustAllowanceFunc func(addr Address) (dustAllowanceSum uint64, amountDustOutputs int64, err error)

DustAllowanceFunc returns the deposit sum of dust allowance outputs and amount of dust outputs on the given address.

type Ed25519Address

type Ed25519Address [Ed25519AddressBytesLength]byte

Defines an Ed25519 address.

func AddressFromEd25519PubKey

func AddressFromEd25519PubKey(pubKey ed25519.PublicKey) Ed25519Address

AddressFromEd25519PubKey returns the address belonging to the given Ed25519 public key.

func MustParseEd25519AddressFromHexString

func MustParseEd25519AddressFromHexString(hexAddr string) *Ed25519Address

MustParseEd25519AddressFromHexString parses the given hex string into an Ed25519Address. It panics if the hex address is invalid.

func ParseEd25519AddressFromHexString

func ParseEd25519AddressFromHexString(hexAddr string) (*Ed25519Address, error)

ParseEd25519AddressFromHexString parses the given hex string into an Ed25519Address.

func (*Ed25519Address) Bech32

func (edAddr *Ed25519Address) Bech32(hrp NetworkPrefix) string

func (*Ed25519Address) Deserialize

func (edAddr *Ed25519Address) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*Ed25519Address) MarshalJSON

func (edAddr *Ed25519Address) MarshalJSON() ([]byte, error)

func (*Ed25519Address) Serialize

func (edAddr *Ed25519Address) Serialize(deSeriMode DeSerializationMode) (data []byte, err error)

func (*Ed25519Address) String

func (edAddr *Ed25519Address) String() string

func (*Ed25519Address) Type

func (edAddr *Ed25519Address) Type() AddressType

func (*Ed25519Address) UnmarshalJSON

func (edAddr *Ed25519Address) UnmarshalJSON(bytes []byte) error

type Ed25519Signature

type Ed25519Signature struct {
	// The public key used to verify the given signature.
	PublicKey [ed25519.PublicKeySize]byte
	// The signature.
	Signature [ed25519.SignatureSize]byte
}

Ed25519Signature defines an Ed25519 signature.

func (*Ed25519Signature) Deserialize

func (e *Ed25519Signature) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*Ed25519Signature) MarshalJSON

func (e *Ed25519Signature) MarshalJSON() ([]byte, error)

func (*Ed25519Signature) Serialize

func (e *Ed25519Signature) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*Ed25519Signature) UnmarshalJSON

func (e *Ed25519Signature) UnmarshalJSON(bytes []byte) error

func (*Ed25519Signature) Valid

func (e *Ed25519Signature) Valid(msg []byte, addr *Ed25519Address) error

Valid verifies whether given the message and Ed25519 address, the signature is valid.

type ElementValidationFunc

type ElementValidationFunc func(index int, next []byte) error

ElementValidationFunc is a function which runs during array validation (e.g. lexical ordering).

type ErrProducer

type ErrProducer func(err error) error

ErrProducer produces an error.

type ErrProducerWithLeftOver

type ErrProducerWithLeftOver func(left int, err error) error

ErrProducerWithLeftOver produces an error and is called with the bytes left to read.

type GossipHeartbeat

type GossipHeartbeat struct {
	// The solid milestone of the node.
	SolidMilestoneIndex uint32 `json:"solidMilestoneIndex"`
	// The milestone index at which the node pruned its data.
	PrunedMilestoneIndex uint32 `json:"prunedMilestoneIndex"`
	// The latest known milestone index by the node.
	LatestMilestoneIndex uint32 `json:"latestMilestoneIndex"`
	// The amount of currently connected neighbors.
	ConnectedNeighbors int `json:"connectedNeighbors"`
	// The amount of currently connected neighbors who also
	// are synchronized with the network.
	SyncedNeighbors int `json:"syncedNeighbors"`
}

GossipHeartbeat represents a gossip heartbeat message. Peers send each other this gossip protocol message when their state is updated, such as when:

  • a new milestone was received
  • the solid milestone changed
  • the node performed pruning of data

type GossipInfo

type GossipInfo struct {
	// The last received heartbeat by the given node.
	Heartbeat *GossipHeartbeat `json:"heartbeat"`
	// The metrics about sent and received protocol messages.
	Metrics PeerGossipMetrics `json:"metrics"`
}

GossipInfo represents information about an ongoing gossip protocol.

type HTTPErrorResponseEnvelope

type HTTPErrorResponseEnvelope struct {
	Error struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"error"`
}

defines the error response schema for node API responses.

type HTTPOkResponseEnvelope

type HTTPOkResponseEnvelope struct {
	// The encapsulated json data.
	Data interface{} `json:"data"`
}

defines the ok response schema for node API responses.

type InMemoryAddressSigner

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

InMemoryAddressSigner implements AddressSigner by holding keys simply in-memory.

func (*InMemoryAddressSigner) Sign

func (s *InMemoryAddressSigner) Sign(addr Address, msg []byte) (signature Serializable, err error)

type Indexation

type Indexation struct {
	// The index to use to index the enclosing message and data.
	Index []byte `json:"index"`
	// The data within the payload.
	Data []byte `json:"data"`
}

Indexation is a payload which holds an index and associated data.

func (*Indexation) Deserialize

func (u *Indexation) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*Indexation) MarshalJSON

func (u *Indexation) MarshalJSON() ([]byte, error)

func (*Indexation) Serialize

func (u *Indexation) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*Indexation) UnmarshalJSON

func (u *Indexation) UnmarshalJSON(bytes []byte) error

type InputToOutputMapping

type InputToOutputMapping = map[UTXOInputID]Output

InputToOutputMapping maps inputs to their origin UTXOs.

type InputType

type InputType = byte

Defines the type of inputs.

const (
	// A type of input which references an unspent transaction output.
	InputUTXO InputType = iota
	// A type of input which references a milestone which generated a treasury output.
	InputTreasury
)

type InputsValidatorFunc

type InputsValidatorFunc func(index int, input *UTXOInput) error

InputsValidatorFunc which given the index of an input and the input itself, runs validations and returns an error if any should fail.

func InputsUTXORefIndexBoundsValidator

func InputsUTXORefIndexBoundsValidator() InputsValidatorFunc

InputsUTXORefIndexBoundsValidator returns a validator which checks that the UTXO ref index is within bounds.

func InputsUTXORefsUniqueValidator

func InputsUTXORefsUniqueValidator() InputsValidatorFunc

InputsUTXORefsUniqueValidator returns a validator which checks that every input has a unique UTXO ref.

type JSONObjectEnvelope

type JSONObjectEnvelope struct {
	Type int `json:"type"`
}

JSONObjectEnvelope defines the envelope for looking-ahead an object's type before deserializing it to its actual object.

type JSONSerializable

type JSONSerializable interface {
	// ToSerializable returns the Serializable form of the JSONSerializable.
	ToSerializable() (Serializable, error)
}

JSONSerializable is an object which can return a Serializable.

func DeserializeObjectFromJSON

func DeserializeObjectFromJSON(raw *json.RawMessage, selector JSONSerializableSelectorFunc) (JSONSerializable, error)

DeserializeObjectFromJSON reads out the type of the given raw json message, then selects the appropriate object type and deserializes the given *json.RawMessage into it.

type JSONSerializableSelectorFunc

type JSONSerializableSelectorFunc func(ty int) (JSONSerializable, error)

JSONSerializableSelectorFunc is a function that given a type int, returns an empty instance of the given underlying type. If the type doesn't resolve, an error is returned.

type LegacyTailTransactionHash

type LegacyTailTransactionHash = [49]byte

LegacyTailTransactionHash represents the bytes of a T5B1 encoded legacy tail transaction hash.

type LexicalOrdered32ByteArrays

type LexicalOrdered32ByteArrays [][32]byte

LexicalOrdered32ByteArrays are 32 byte arrays ordered in lexical order.

func (LexicalOrdered32ByteArrays) Len

func (LexicalOrdered32ByteArrays) Less

func (l LexicalOrdered32ByteArrays) Less(i, j int) bool

func (LexicalOrdered32ByteArrays) Swap

func (l LexicalOrdered32ByteArrays) Swap(i, j int)

type LexicalOrderedByteSlices

type LexicalOrderedByteSlices [][]byte

LexicalOrderedByteSlices are byte slices ordered in lexical order.

func (LexicalOrderedByteSlices) Len

func (l LexicalOrderedByteSlices) Len() int

func (LexicalOrderedByteSlices) Less

func (l LexicalOrderedByteSlices) Less(i, j int) bool

func (LexicalOrderedByteSlices) Swap

func (l LexicalOrderedByteSlices) Swap(i, j int)

type Message

type Message struct {
	// The network ID for which this message is meant for.
	NetworkID uint64
	// The parents the message references.
	Parents MessageIDs
	// The inner payload of the message. Can be nil.
	Payload Serializable
	// The nonce which lets this message fulfill the PoW requirements.
	Nonce uint64
}

Message can carry a payload and references two other messages.

func (*Message) Deserialize

func (m *Message) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*Message) ID

func (m *Message) ID() (*MessageID, error)

ID computes the ID of the Message.

func (*Message) MarshalJSON

func (m *Message) MarshalJSON() ([]byte, error)

func (*Message) MustID

func (m *Message) MustID() MessageID

MustID works like ID but panics if the MessageID can't be computed.

func (*Message) POW

func (m *Message) POW() (float64, error)

POW computes the PoW score of the Message.

func (*Message) Serialize

func (m *Message) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(bytes []byte) error

type MessageBuilder

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

MessageBuilder is used to easily build up a Message.

func NewMessageBuilder

func NewMessageBuilder() *MessageBuilder

NewMessageBuilder creates a new MessageBuilder.

func (*MessageBuilder) Build

func (mb *MessageBuilder) Build() (*Message, error)

Build builds the Message or returns any error which occurred during the build steps.

func (*MessageBuilder) NetworkID

func (mb *MessageBuilder) NetworkID(networkID uint64) *MessageBuilder

NetworkID sets the network ID for which this message is meant for.

func (*MessageBuilder) NetworkIDFromString

func (mb *MessageBuilder) NetworkIDFromString(networkIDStr string) *MessageBuilder

NetworkIDFromString sets the network ID for which this message is meant for.

func (*MessageBuilder) Parents

func (mb *MessageBuilder) Parents(parents [][]byte) *MessageBuilder

Parents sets the parents of the message.

func (*MessageBuilder) ParentsMessageIDs

func (mb *MessageBuilder) ParentsMessageIDs(parents MessageIDs) *MessageBuilder

ParentsMessageIDs sets the parents of the message.

func (*MessageBuilder) Payload

func (mb *MessageBuilder) Payload(seri Serializable) *MessageBuilder

Payload sets the payload to embed within the message.

func (*MessageBuilder) ProofOfWork

func (mb *MessageBuilder) ProofOfWork(ctx context.Context, targetScore float64, numWorkers ...int) *MessageBuilder

ProofOfWork does the proof-of-work needed in order to satisfy the given target score. It can be cancelled by cancelling the given context. This function should appear as the last step before Build.

func (*MessageBuilder) Tips

func (mb *MessageBuilder) Tips(nodeAPI *NodeHTTPAPIClient) *MessageBuilder

Tips uses the given NodeHTTPAPIClient to query for parents to use.

type MessageID

type MessageID = [MessageIDLength]byte

MessageID is the ID of a Message.

func MessageIDFromHexString

func MessageIDFromHexString(messageIDHex string) (MessageID, error)

MessageIDFromHexString converts the given message IDs from their hex to MessageID representation.

func MustMessageIDFromHexString

func MustMessageIDFromHexString(messageIDHex string) MessageID

MustMessageIDFromHexString converts the given message IDs from their hex to MessageID representation.

type MessageIDs

type MessageIDs = []MessageID

MessageIDs are IDs of messages.

type MessageIDsByIndexResponse

type MessageIDsByIndexResponse struct {
	// The index of the messages.
	Index string `json:"index"`
	// The maximum count of results that are returned by the node.
	MaxResults uint32 `json:"maxResults"`
	// The actual count of results that are returned.
	Count uint32 `json:"count"`
	// The hex encoded message IDs of the found messages with this index.
	MessageIDs []string `json:"messageIds"`
}

MessageIDsByIndexResponse defines the response of a GET messages REST API call.

type MessageMetadataResponse

type MessageMetadataResponse struct {
	// The hex encoded message ID of the message.
	MessageID string `json:"messageId"`
	// The hex encoded message IDs of the parents the message references.
	Parents []string `json:"parentMessageIds"`
	// Whether the message is solid.
	Solid bool `json:"isSolid"`
	// The milestone index that references this message.
	ReferencedByMilestoneIndex *uint32 `json:"referencedByMilestoneIndex,omitempty"`
	// The ledger inclusion state of the transaction payload.
	LedgerInclusionState *string `json:"ledgerInclusionState,omitempty"`
	// Whether the message should be promoted.
	ShouldPromote *bool `json:"shouldPromote,omitempty"`
	// Whether the message should be reattached.
	ShouldReattach *bool `json:"shouldReattach,omitempty"`
	// The reason why this message is marked as conflicting.
	ConflictReason uint8 `json:"conflictReason,omitempty"`
}

MessageMetadataResponse defines the response of a GET message metadata REST API call.

type MigratedFundsEntry

type MigratedFundsEntry struct {
	// The tail transaction hash of the migration bundle.
	TailTransactionHash LegacyTailTransactionHash
	// The target address of the migrated funds.
	Address Serializable
	// The amount of the deposit.
	Deposit uint64
}

MigratedFundsEntry are funds which were migrated from a legacy network.

func (*MigratedFundsEntry) Deserialize

func (m *MigratedFundsEntry) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*MigratedFundsEntry) MarshalJSON

func (m *MigratedFundsEntry) MarshalJSON() ([]byte, error)

func (*MigratedFundsEntry) Serialize

func (m *MigratedFundsEntry) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*MigratedFundsEntry) UnmarshalJSON

func (m *MigratedFundsEntry) UnmarshalJSON(bytes []byte) error

type Milestone

type Milestone struct {
	// The index of this milestone.
	Index uint32
	// The time at which this milestone was issued.
	Timestamp uint64
	// The parents where this milestone attaches to.
	Parents MilestoneParentMessageIDs
	// The inclusion merkle proof of included/newly confirmed transaction IDs.
	InclusionMerkleProof MilestoneInclusionMerkleProof
	// The public keys validating the signatures of the milestone.
	PublicKeys []MilestonePublicKey
	// The inner payload of the milestone. Can be nil or a Receipt.
	Receipt Serializable
	// The signatures held by the milestone.
	Signatures []MilestoneSignature
}

Milestone represents a special payload which defines the inclusion set of other messages in the Tangle.

func NewMilestone

func NewMilestone(index uint32, timestamp uint64, parents MilestoneParentMessageIDs, inclMerkleProof MilestoneInclusionMerkleProof, pubKeys []MilestonePublicKey) (*Milestone, error)

NewMilestone creates a new Milestone. It automatically orders the given public keys by their byte order.

func (*Milestone) Deserialize

func (m *Milestone) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*Milestone) Essence

func (m *Milestone) Essence() ([]byte, error)

Essence returns the essence bytes (the bytes to be signed) of the Milestone.

func (*Milestone) ID

func (m *Milestone) ID() (*MilestoneID, error)

ID computes the ID of the Milestone.

func (*Milestone) MarshalJSON

func (m *Milestone) MarshalJSON() ([]byte, error)

func (*Milestone) Serialize

func (m *Milestone) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*Milestone) Sign

func (m *Milestone) Sign(signingFunc MilestoneSigningFunc) error

Sign produces the signatures with the given envelope message and updates the Signatures field of the Milestone with the resulting signatures of the given MilestoneSigningFunc.

func (*Milestone) UnmarshalJSON

func (m *Milestone) UnmarshalJSON(bytes []byte) error

func (*Milestone) VerifySignatures

func (m *Milestone) VerifySignatures(minSigThreshold int, applicablePubKeys MilestonePublicKeySet) error

VerifySignatures verifies that min. minSigThreshold signatures occur in the Milestone and that all signatures within it are valid with respect to the given applicable public key set. The public key set must only contain keys applicable for the given Milestone index. The caller must only call this function on a Milestone which was deserialized with validation.

type MilestoneID

type MilestoneID = [MilestoneIDLength]byte

MilestoneID is the ID of a Milestone.

type MilestoneInclusionMerkleProof

type MilestoneInclusionMerkleProof = [MilestoneInclusionMerkleProofLength]byte

MilestoneInclusionMerkleProof is the inclusion merkle proof data of a milestone.

type MilestoneParentMessageID

type MilestoneParentMessageID = MessageID

MilestoneParentMessageID is a reference to a parent message.

type MilestoneParentMessageIDs

type MilestoneParentMessageIDs = []MilestoneParentMessageID

MilestoneParentMessageIDs are references to parent messages.

type MilestonePointer

type MilestonePointer struct {
	Index     uint32 `json:"index"`
	Timestamp uint64 `json:"timestamp"`
}

MilestonePointer is an informative struct holding a milestone index and timestamp.

type MilestonePublicKey

type MilestonePublicKey = [MilestonePublicKeyLength]byte

MilestonePublicKey is a public key within a Milestone.

type MilestonePublicKeyMapping

type MilestonePublicKeyMapping = map[MilestonePublicKey]ed25519.PrivateKey

MilestonePublicKeyMapping is a mapping from a public key to a private key.

type MilestonePublicKeySet

type MilestonePublicKeySet = map[MilestonePublicKey]struct{}

MilestonePublicKeySet is a set of unique MilestonePublicKey.

type MilestoneResponse

type MilestoneResponse struct {
	// The index of the milestone.
	Index uint32 `json:"index"`
	// The hex encoded message ID of the message.
	MessageID string `json:"messageId"`
	// The unix time of the milestone payload.
	Time int64 `json:"timestamp"`
}

MilestoneResponse defines the response of a GET milestones REST API call.

type MilestoneSignature

type MilestoneSignature = [MilestoneSignatureLength]byte

MilestoneSignature is a signature within a Milestone.

type MilestoneSigningFunc

type MilestoneSigningFunc func(pubKeys []MilestonePublicKey, msEssence []byte) ([]MilestoneSignature, error)

MilestoneSigningFunc is a function which produces a set of signatures for the given Milestone essence data. The given public keys dictate in which order the returned signatures must occur.

func InMemoryEd25519MilestoneSigner

func InMemoryEd25519MilestoneSigner(prvKeys MilestonePublicKeyMapping) MilestoneSigningFunc

InMemoryEd25519MilestoneSigner is a function which uses the provided Ed25519 MilestonePublicKeyMapping to produce signatures for the Milestone essence data.

func InsecureRemoteEd25519MilestoneSigner

func InsecureRemoteEd25519MilestoneSigner(remoteEndpoint string) MilestoneSigningFunc

InsecureRemoteEd25519MilestoneSigner is a function which uses a remote RPC server via an insecure connection to produce signatures for the Milestone essence data. You must only use this function if the remote lives on the same host as the caller.

type NetworkID

type NetworkID = uint64

NetworkID defines the ID of the network on which entities operate on.

func NetworkIDFromString

func NetworkIDFromString(networkIDStr string) NetworkID

NetworkIDFromString returns the network ID string's numerical representation.

type NetworkPrefix

type NetworkPrefix string

NetworkPrefix denotes the different network prefixes.

const (
	PrefixMainnet NetworkPrefix = "iota"
	PrefixTestnet NetworkPrefix = "atoi"
)

Network prefixes.

type NodeEventAPIClient

type NodeEventAPIClient struct {
	MQTTClient mqtt.Client
	// The context over the EventChannelsHandle.
	Ctx context.Context
	// A channel up on which errors are returned from within subscriptions or when the connection is lost.
	// It is the instantiater's job to ensure that the respective connection handlers are linked to this error channel
	// if the client was created without NewNodeEventAPIClient.
	// Errors are dropped silently if no receiver is listening for them or can consume them fast enough.
	Errors chan error
}

NodeEventAPIClient represents a handle to retrieve channels for node events. Any registration will panic if the NodeEventAPIClient.Ctx is done or the client isn't connected. Multiple calls to the same channel registration will override the previously created channel.

func NewNodeEventAPIClient

func NewNodeEventAPIClient(brokerURI string) *NodeEventAPIClient

NewNodeEventAPIClient creates a new NodeEventAPIClient using the given broker URI and default MQTT client options.

func (*NodeEventAPIClient) AddressOutputs

func (neac *NodeEventAPIClient) AddressOutputs(addr Address, netPrefix NetworkPrefix) <-chan *NodeOutputResponse

AddressOutputs returns a channel of newly created or spent outputs on the given address.

func (*NodeEventAPIClient) Close

func (neac *NodeEventAPIClient) Close()

Close disconnects the underlying MQTT client. Call this function to clean up any registered channels.

func (*NodeEventAPIClient) ConfirmedMilestoneMessages

func (neac *NodeEventAPIClient) ConfirmedMilestoneMessages(nodeHTTPAPIClient *NodeHTTPAPIClient) <-chan *Message

ConfirmedMilestoneMessages returns a channel of newly confirmed milestones messages.

func (*NodeEventAPIClient) ConfirmedMilestones

func (neac *NodeEventAPIClient) ConfirmedMilestones() <-chan *MilestonePointer

ConfirmedMilestones returns a channel of newly confirmed milestones.

func (*NodeEventAPIClient) Connect

func (neac *NodeEventAPIClient) Connect(ctx context.Context) error

Connect connects the NodeEventAPIClient to the specified brokers. The NodeEventAPIClient remains active as long as the given context isn't done/cancelled.

func (*NodeEventAPIClient) Ed25519AddressOutputs

func (neac *NodeEventAPIClient) Ed25519AddressOutputs(addr *Ed25519Address) <-chan *NodeOutputResponse

Ed25519AddressOutputs returns a channel of newly created or spent outputs on the given ed25519 address.

func (*NodeEventAPIClient) LatestMilestoneMessages

func (neac *NodeEventAPIClient) LatestMilestoneMessages(nodeHTTPAPIClient *NodeHTTPAPIClient) <-chan *Message

LatestMilestoneMessages returns a channel of newly seen latest milestones messages.

func (*NodeEventAPIClient) LatestMilestones

func (neac *NodeEventAPIClient) LatestMilestones() <-chan *MilestonePointer

LatestMilestones returns a channel of newly seen latest milestones.

func (*NodeEventAPIClient) MessageMetadataChange

func (neac *NodeEventAPIClient) MessageMetadataChange(msgID MessageID) <-chan *MessageMetadataResponse

MessageMetadataChange returns a channel of MessageMetadataResponse each time the given message's state changes.

func (*NodeEventAPIClient) Messages

func (neac *NodeEventAPIClient) Messages() <-chan *Message

Messages returns a channel of newly received messages.

func (*NodeEventAPIClient) MessagesWithIndex

func (neac *NodeEventAPIClient) MessagesWithIndex(index string) <-chan *Message

MessagesWithIndex returns a channel of newly received messages with the given index.

func (*NodeEventAPIClient) Output

func (neac *NodeEventAPIClient) Output(outputID UTXOInputID) <-chan *NodeOutputResponse

Output returns a channel which immediately returns the output with the given ID and afterwards when its state changes.

func (*NodeEventAPIClient) Receipts

func (neac *NodeEventAPIClient) Receipts() <-chan *Receipt

Receipts returns a channel which returns newly applied receipts.

func (*NodeEventAPIClient) ReferencedMessages

func (neac *NodeEventAPIClient) ReferencedMessages(nodeHTTPAPIClient *NodeHTTPAPIClient) <-chan *Message

ReferencedMessages returns a channel of newly referenced messages.

func (*NodeEventAPIClient) ReferencedMessagesMetadata

func (neac *NodeEventAPIClient) ReferencedMessagesMetadata() <-chan *MessageMetadataResponse

ReferencedMessagesMetadata returns a channel of message metadata of newly referenced messages.

func (*NodeEventAPIClient) TransactionIncludedMessage

func (neac *NodeEventAPIClient) TransactionIncludedMessage(txID TransactionID) <-chan *Message

TransactionIncludedMessage returns a channel of the included message which carries the transaction with the given ID.

type NodeHTTPAPIClient

type NodeHTTPAPIClient struct {
	// The base URL for all API calls.
	BaseURL string
	// contains filtered or unexported fields
}

NodeHTTPAPIClient is a client for node HTTP REST API endpoints.

func NewNodeHTTPAPIClient

func NewNodeHTTPAPIClient(baseURL string, opts ...NodeHTTPAPIClientOption) *NodeHTTPAPIClient

NewNodeHTTPAPIClient returns a new NodeHTTPAPIClient with the given BaseURL.

func (*NodeHTTPAPIClient) AddPeer

func (api *NodeHTTPAPIClient) AddPeer(multiAddress string, alias ...string) (*PeerResponse, error)

AddPeer adds a new peer by libp2p multi address with optional alias.

func (*NodeHTTPAPIClient) BalanceByEd25519Address

func (api *NodeHTTPAPIClient) BalanceByEd25519Address(addr *Ed25519Address) (*AddressBalanceResponse, error)

BalanceByEd25519Address returns the balance of an Ed25519 address.

func (*NodeHTTPAPIClient) ChildrenByMessageID

func (api *NodeHTTPAPIClient) ChildrenByMessageID(msgID MessageID) (*ChildrenResponse, error)

MessageByMessageID get a message by it's message ID from the node.

func (*NodeHTTPAPIClient) Do

func (api *NodeHTTPAPIClient) Do(method string, route string, reqObj interface{}, resObj interface{}) (*http.Response, error)

func (*NodeHTTPAPIClient) Health

func (api *NodeHTTPAPIClient) Health() (bool, error)

Health returns whether the given node is healthy.

func (*NodeHTTPAPIClient) Info

func (api *NodeHTTPAPIClient) Info() (*NodeInfoResponse, error)

Info gets the info of the node.

func (*NodeHTTPAPIClient) MessageByMessageID

func (api *NodeHTTPAPIClient) MessageByMessageID(msgID MessageID) (*Message, error)

MessageByMessageID get a message by it's message ID from the node.

func (*NodeHTTPAPIClient) MessageIDsByIndex

func (api *NodeHTTPAPIClient) MessageIDsByIndex(index []byte) (*MessageIDsByIndexResponse, error)

MessageIDsByIndex gets message IDs filtered by index from the node.

func (*NodeHTTPAPIClient) MessageMetadataByMessageID

func (api *NodeHTTPAPIClient) MessageMetadataByMessageID(msgID MessageID) (*MessageMetadataResponse, error)

MessageByMessageID gets the metadata of a message by it's message ID from the node.

func (*NodeHTTPAPIClient) MilestoneByIndex

func (api *NodeHTTPAPIClient) MilestoneByIndex(index uint32) (*MilestoneResponse, error)

MilestoneByIndex gets a milestone by its index.

func (*NodeHTTPAPIClient) OutputByID

func (api *NodeHTTPAPIClient) OutputByID(utxoID UTXOInputID) (*NodeOutputResponse, error)

OutputByID gets an outputs by its ID from the node.

func (*NodeHTTPAPIClient) OutputIDsByEd25519Address

func (api *NodeHTTPAPIClient) OutputIDsByEd25519Address(addr *Ed25519Address, includeSpentOutputs bool) (*AddressOutputsResponse, error)

OutputIDsByEd25519Address gets outputs IDs by ed25519 addresses from the node. Per default only unspent outputs IDs are returned. Set includeSpentOutputs to true to also returned spent outputs IDs.

func (*NodeHTTPAPIClient) OutputsByEd25519Address

func (api *NodeHTTPAPIClient) OutputsByEd25519Address(addr *Ed25519Address, includeSpentOutputs bool) (*AddressOutputsResponse, map[*UTXOInput]Output, error)

OutputsByEd25519Address gets the outputs by the ed25519 address from the node. Per default only unspent outputs are returned. Set includeSpentOutputs to true to also returned spent outputs.

func (*NodeHTTPAPIClient) PeerByID

func (api *NodeHTTPAPIClient) PeerByID(id string) (*PeerResponse, error)

PeerByID gets a peer by its identifier.

func (*NodeHTTPAPIClient) Peers

func (api *NodeHTTPAPIClient) Peers() ([]*PeerResponse, error)

Peers returns a list of all peers.

func (*NodeHTTPAPIClient) Receipts

func (api *NodeHTTPAPIClient) Receipts() ([]*ReceiptTuple, error)

Receipts gets all receipts persisted on the node.

func (*NodeHTTPAPIClient) ReceiptsByMigratedAtIndex

func (api *NodeHTTPAPIClient) ReceiptsByMigratedAtIndex(index uint32) ([]*ReceiptTuple, error)

Receipts gets all receipts for the given migrated at index persisted on the node.

func (*NodeHTTPAPIClient) RemovePeerByID

func (api *NodeHTTPAPIClient) RemovePeerByID(id string) error

RemovePeerByID removes a peer by its identifier.

func (*NodeHTTPAPIClient) SubmitMessage

func (api *NodeHTTPAPIClient) SubmitMessage(m *Message) (*Message, error)

SubmitMessage submits the given Message to the node. The node will take care of filling missing information. This function returns the finalized message created by the node.

func (*NodeHTTPAPIClient) Tips

func (api *NodeHTTPAPIClient) Tips() (*NodeTipsResponse, error)

Tips gets the two tips from the node.

func (*NodeHTTPAPIClient) Treasury

func (api *NodeHTTPAPIClient) Treasury() (*TreasuryResponse, error)

Treasury gets the current treasury.

type NodeHTTPAPIClientOption

type NodeHTTPAPIClientOption func(opts *NodeHTTPAPIClientOptions)

NodeHTTPAPIClientOption is a function setting a NodeHTTPAPIClient option.

func WithNodeHTTPAPIClientHTTPClient

func WithNodeHTTPAPIClientHTTPClient(httpClient *http.Client) NodeHTTPAPIClientOption

WithNodeHTTPAPIClientHTTPClient sets the used HTTP Client.

func WithNodeHTTPAPIClientUserInfo

func WithNodeHTTPAPIClientUserInfo(userInfo *url.Userinfo) NodeHTTPAPIClientOption

WithNodeHTTPAPIClientUserInfo sets the Userinfo used to add basic auth "Authorization" headers to the requests.

type NodeHTTPAPIClientOptions

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

NodeHTTPAPIClientOptions define options for the NodeHTTPAPIClient.

type NodeInfoResponse

type NodeInfoResponse struct {
	// The name of the node software.
	Name string `json:"name"`
	// The semver version of the node software.
	Version string `json:"version"`
	// Whether the node is healthy.
	IsHealthy bool `json:"isHealthy"`
	// The human friendly name of the network ID on which the node operates on.
	NetworkID string `json:"networkId"`
	// The HRP prefix used for Bech32 addresses in the node's network.
	Bech32HRP string `json:"bech32HRP"`
	// The minimum pow score of the network.
	MinPowScore float64 `json:"minPowScore"`
	// The latest known milestone index.
	LatestMilestoneIndex uint32 `json:"latestMilestoneIndex"`
	// The current confirmed milestone's index.
	ConfirmedMilestoneIndex uint32 `json:"confirmedMilestoneIndex"`
	// The milestone index at which the last pruning commenced.
	PruningIndex uint32 `json:"pruningIndex"`
	// The features this node exposes.
	Features []string `json:"features"`
}

NodeInfoResponse defines the response of a GET info REST API call.

type NodeOutputResponse

type NodeOutputResponse struct {
	// The hex encoded message ID of the message.
	MessageID string `json:"messageId"`
	// The hex encoded transaction id from which this output originated.
	TransactionID string `json:"transactionId"`
	// The index of the output.
	OutputIndex uint16 `json:"outputIndex"`
	// Whether this output is spent.
	Spent bool `json:"isSpent"`
	// The output in its serialized form.
	RawOutput *json.RawMessage `json:"output"`
}

NodeOutputResponse defines the response of a GET outputs REST API call.

func (*NodeOutputResponse) Output

func (nor *NodeOutputResponse) Output() (Output, error)

Output deserializes the RawOutput to an Output.

func (*NodeOutputResponse) TxID

func (nor *NodeOutputResponse) TxID() (*TransactionID, error)

TxID returns the TransactionID.

type NodeTipsResponse

type NodeTipsResponse struct {
	// The hex encoded message IDs of the tips.
	TipsHex []string `json:"tipMessageIds"`
}

NodeTipsResponse defines the response of a GET tips REST API call.

func (*NodeTipsResponse) Tips

func (ntr *NodeTipsResponse) Tips() (MessageIDs, error)

Tips returns the hex encoded tips as MessageIDs.

type Output

type Output interface {
	Serializable
	// Deposit returns the amount this Output deposits.
	Deposit() (uint64, error)
	// Target returns the target of the deposit.
	// If the type of output does not have/support a target, nil is returned.
	Target() (Serializable, error)
	// Type returns the type of the output.
	Type() OutputType
}

Output defines the deposit of funds.

type OutputIDHex

type OutputIDHex string

OutputIDHex is the hex representation of an output ID.

func (OutputIDHex) AsUTXOInput

func (oih OutputIDHex) AsUTXOInput() (*UTXOInput, error)

AsUTXOInput converts the hex output ID to a UTXOInput.

func (OutputIDHex) MustAsUTXOInput

func (oih OutputIDHex) MustAsUTXOInput() *UTXOInput

MustAsUTXOInput converts the hex output ID to a UTXOInput. It panics if the hex output ID is invalid.

func (OutputIDHex) MustSplitParts

func (oih OutputIDHex) MustSplitParts() (*TransactionID, uint16)

MustSplitParts returns the transaction ID and output index parts of the hex output ID. It panics if the hex output ID is invalid.

func (OutputIDHex) SplitParts

func (oih OutputIDHex) SplitParts() (*TransactionID, uint16, error)

SplitParts returns the transaction ID and output index parts of the hex output ID.

type OutputType

type OutputType = byte

Defines the type of outputs.

type Outputs

type Outputs []Output

Outputs is a slice of Output.

type OutputsValidatorFunc

type OutputsValidatorFunc func(index int, output Output) error

OutputsValidatorFunc which given the index of an output and the output itself, runs validations and returns an error if any should fail.

func OutputsAddrUniqueValidator

func OutputsAddrUniqueValidator() OutputsValidatorFunc

OutputsAddrUniqueValidator returns a validator which checks that all addresses are unique per OutputType.

func OutputsDepositAmountValidator

func OutputsDepositAmountValidator() OutputsValidatorFunc

OutputsDepositAmountValidator returns a validator which checks that:

  1. every output deposits more than zero
  2. every output deposits less than the total supply
  3. the sum of deposits does not exceed the total supply
  4. SigLockedDustAllowanceOutput deposits at least OutputSigLockedDustAllowanceOutputMinDeposit.

If -1 is passed to the validator func, then the sum is not aggregated over multiple calls.

type PeerGossipMetrics

type PeerGossipMetrics struct {
	// The total amount of received new messages.
	NewMessages uint32 `json:"newMessages"`
	// The total amount of received known messages.
	KnownMessages uint32 `json:"knownMessages"`
	// The total amount of received messages.
	ReceivedMessages uint32 `json:"receivedMessages"`
	// The total amount of received message requests.
	ReceivedMessageRequests uint32 `json:"receivedMessageRequests"`
	// The total amount of received milestone requests.
	ReceivedMilestoneRequests uint32 `json:"receivedMilestoneRequests"`
	// The total amount of received heartbeats.
	ReceivedHeartbeats uint32 `json:"receivedHeartbeats"`
	// The total amount of sent messages.
	SentMessages uint32 `json:"sentMessages"`
	// The total amount of sent message request.
	SentMessageRequests uint32 `json:"sentMessageRequests"`
	// The total amount of sent milestone request.
	SentMilestoneRequests uint32 `json:"sentMilestoneRequests"`
	// The total amount of sent heartbeats.
	SentHeartbeats uint32 `json:"sentHeartbeats"`
	// The total amount of packets which couldn't be sent.
	DroppedPackets uint32 `json:"droppedPackets"`
}

PeerGossipMetrics defines the peer gossip metrics.

type PeerResponse

type PeerResponse struct {
	// The libp2p identifier of the peer.
	ID string `json:"id"`
	// The libp2p multi addresses of the peer.
	MultiAddresses []string `json:"multiAddresses"`
	// The alias to identify the peer.
	Alias *string `json:"alias,omitempty"`
	// The relation (static, autopeered) of the peer.
	Relation string `json:"relation"`
	// Whether the peer is connected.
	Connected bool `json:"connected"`
	// The gossip related information about this peer.
	Gossip *GossipInfo `json:"gossip,omitempty"`
}

PeerResponse defines the response of a GET peer REST API call.

type RawDataEnvelope

type RawDataEnvelope struct {
	// The encapsulated binary data.
	Data []byte
}

RawDataEnvelope is used internally to encapsulate binary data.

type ReadObjectConsumerFunc

type ReadObjectConsumerFunc func(seri Serializable)

ReadObjectConsumerFunc gets called after an object has been deserialized from a Deserializer.

type ReadObjectsConsumerFunc

type ReadObjectsConsumerFunc func(seri Serializables)

ReadObjectsConsumerFunc gets called after objects have been deserialized from a Deserializer.

type Receipt

type Receipt struct {
	// The milestone index at which the funds were migrated in the legacy network.
	MigratedAt uint32
	// Whether this Receipt is the final one for a given migrated at index.
	Final bool
	// The funds which were migrated with this Receipt.
	Funds Serializables
	// The TreasuryTransaction used to fund the funds.
	Transaction Serializable
}

Receipt is a listing of migrated funds.

func (*Receipt) Deserialize

func (r *Receipt) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*Receipt) MarshalJSON

func (r *Receipt) MarshalJSON() ([]byte, error)

func (*Receipt) Serialize

func (r *Receipt) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*Receipt) SortFunds

func (r *Receipt) SortFunds()

SortFunds sorts the funds within the receipt after their serialized binary form in lexical order.

func (*Receipt) Sum

func (r *Receipt) Sum() uint64

Sum returns the sum of all MigratedFundsEntry items within the Receipt.

func (*Receipt) Treasury

func (r *Receipt) Treasury() *TreasuryTransaction

Treasury returns the TreasuryTransaction within the receipt or nil if none is contained. This function panics if the Receipt.Transaction is not nil and not a TreasuryTransaction.

func (*Receipt) UnmarshalJSON

func (r *Receipt) UnmarshalJSON(bytes []byte) error

type ReceiptBuilder

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

ReceiptBuilder is used to easily build up a Receipt.

func NewReceiptBuilder

func NewReceiptBuilder(migratedAt uint32) *ReceiptBuilder

NewReceiptBuilder creates a new ReceiptBuilder.

func (*ReceiptBuilder) AddEntry

func (rb *ReceiptBuilder) AddEntry(entry *MigratedFundsEntry) *ReceiptBuilder

AddEntry adds the given MigratedFundsEntry to the receipt.

func (*ReceiptBuilder) AddTreasuryTransaction

func (rb *ReceiptBuilder) AddTreasuryTransaction(tx *TreasuryTransaction) *ReceiptBuilder

AddTreasuryTransaction adds the given TreasuryTransaction to the receipt. This function overrides the previously added TreasuryTransaction.

func (*ReceiptBuilder) Build

func (rb *ReceiptBuilder) Build() (*Receipt, error)

Build builds the Receipt.

type ReceiptTuple

type ReceiptTuple struct {
	Receipt        *Receipt `json:"receipt"`
	MilestoneIndex uint32   `json:"milestoneIndex"`
}

ReceiptTuple represents a receipt and the milestone index in which it was contained.

type ReceiptsResponse

type ReceiptsResponse struct {
	Receipts []*ReceiptTuple `json:"receipts"`
}

ReceiptsResponse defines the response of for receipts GET related REST API calls.

type ReferenceUnlockBlock

type ReferenceUnlockBlock struct {
	// The other unlock block this reference unlock block references to.
	Reference uint16 `json:"reference"`
}

ReferenceUnlockBlock is an unlock block which references a previous unlock block.

func (*ReferenceUnlockBlock) Deserialize

func (r *ReferenceUnlockBlock) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*ReferenceUnlockBlock) MarshalJSON

func (r *ReferenceUnlockBlock) MarshalJSON() ([]byte, error)

func (*ReferenceUnlockBlock) Serialize

func (r *ReferenceUnlockBlock) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*ReferenceUnlockBlock) UnmarshalJSON

func (r *ReferenceUnlockBlock) UnmarshalJSON(bytes []byte) error

type SemanticValidationFunc

type SemanticValidationFunc = func(t *Transaction, utxos InputToOutputMapping) error

SemanticValidationFunc is a function which when called tells whether the transaction is passing a specific semantic validation rule or not.

func NewDustSemanticValidation

func NewDustSemanticValidation(div int64, dustOutputsCountLimit int64, dustAllowanceFunc DustAllowanceFunc) SemanticValidationFunc

NewDustSemanticValidation returns a SemanticValidationFunc which verifies whether a transaction fulfils the semantics regarding dust outputs:

A transaction:
	- consuming a SigLockedDustAllowanceOutput on address A or
	- creating a SigLockedSingleOutput with deposit amount < OutputSigLockedDustAllowanceOutputMinDeposit (dust output)
is only semantically valid, if after the transaction is booked, the number of dust outputs on address A does not exceed the allowed
threshold of the sum of min(S / div, dustOutputsCountLimit). Where S is the sum of deposits of all dust allowance outputs on address A.

type SeriSliceLengthType

type SeriSliceLengthType byte

SeriSliceLengthType defines the type of the value denoting a slice's length.

const (
	// SeriSliceLengthAsByte defines a slice length to be denoted by a byte.
	SeriSliceLengthAsByte SeriSliceLengthType = iota
	// SeriSliceLengthAsUint16 defines a slice length to be denoted by a uint16.
	SeriSliceLengthAsUint16
	// SeriSliceLengthAsUint32 defines a slice length to be denoted by a uint32.
	SeriSliceLengthAsUint32
)

type Serializable

type Serializable interface {
	json.Marshaler
	json.Unmarshaler
	// Deserialize deserializes the given data (by copying) into the object and returns the amount of bytes consumed from data.
	// If the passed data is not big enough for deserialization, an error must be returned.
	// During deserialization additional validation may be performed if the given modes are set.
	Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)
	// Serialize returns a serialized byte representation.
	// This function does not check the serialized data for validity.
	// During serialization additional validation may be performed if the given modes are set.
	Serialize(deSeriMode DeSerializationMode) ([]byte, error)
}

Serializable is something which knows how to serialize/deserialize itself from/into bytes. This is almost analogous to BinaryMarshaler/BinaryUnmarshaler.

func AddressSelector

func AddressSelector(addressType uint32) (Serializable, error)

AddressSelector implements SerializableSelectorFunc for address types.

func InputSelector

func InputSelector(inputType uint32) (Serializable, error)

InputSelector implements SerializableSelectorFunc for input types.

func OutputSelector

func OutputSelector(outputType uint32) (Serializable, error)

OutputSelector implements SerializableSelectorFunc for output types.

func PayloadSelector

func PayloadSelector(payloadType uint32) (Serializable, error)

PayloadSelector implements SerializableSelectorFunc for payload types.

func SignatureSelector

func SignatureSelector(sigType uint32) (Serializable, error)

SignatureSelector implements SerializableSelectorFunc for signature types.

func TransactionEssenceSelector

func TransactionEssenceSelector(txType uint32) (Serializable, error)

TransactionEssenceSelector implements SerializableSelectorFunc for transaction essence types.

func UnlockBlockSelector

func UnlockBlockSelector(unlockBlockType uint32) (Serializable, error)

UnlockBlockSelector implements SerializableSelectorFunc for unlock block types.

type SerializableSelectorFunc

type SerializableSelectorFunc func(ty uint32) (Serializable, error)

SerializableSelectorFunc is a function that given a type byte, returns an empty instance of the given underlying type. If the type doesn't resolve, an error is returned.

type Serializables

type Serializables []Serializable

Serializables is a slice of Serializable.

type Serializer

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

Serializer is a utility to serialize bytes.

func NewSerializer

func NewSerializer() *Serializer

NewSerializer creates a new Serializer.

func (*Serializer) AbortIf

func (s *Serializer) AbortIf(errProducer ErrProducer) *Serializer

AbortIf calls the given ErrProducer if the Serializer did not encounter an error yet. Return nil from the ErrProducer to indicate continuation of the serialization.

func (*Serializer) Do

func (s *Serializer) Do(f func()) *Serializer

Do calls f in the Serializer chain.

func (*Serializer) Serialize

func (s *Serializer) Serialize() ([]byte, error)

Serialize finishes the serialization by returning the serialized bytes or an error if any intermediate step created one.

func (*Serializer) Write32BytesArraySlice

func (s *Serializer) Write32BytesArraySlice(data SliceOfArraysOf32Bytes, deSeriMode DeSerializationMode, lenType SeriSliceLengthType, arrayRules *ArrayRules, errProducer ErrProducer) *Serializer

Write32BytesArraySlice writes a slice of arrays of 32 bytes to the Serializer.

func (*Serializer) Write64BytesArraySlice

func (s *Serializer) Write64BytesArraySlice(data SliceOfArraysOf64Bytes, deSeriMode DeSerializationMode, lenType SeriSliceLengthType, arrayRules *ArrayRules, errProducer ErrProducer) *Serializer

Write64BytesArraySlice writes a slice of arrays of 64 bytes to the Serializer.

func (*Serializer) WriteBool

func (s *Serializer) WriteBool(v bool, errProducer ErrProducer) *Serializer

WriteBool writes the given bool to the Serializer.

func (*Serializer) WriteBytes

func (s *Serializer) WriteBytes(data []byte, errProducer ErrProducer) *Serializer

WriteBytes writes the given byte slice to the Serializer. Use this function only to write fixed size slices/arrays, otherwise use WriteVariableByteSlice instead.

func (*Serializer) WriteNum

func (s *Serializer) WriteNum(v interface{}, errProducer ErrProducer) *Serializer

WriteNum writes the given num v to the Serializer.

func (*Serializer) WriteObject

func (s *Serializer) WriteObject(seri Serializable, deSeriMode DeSerializationMode, errProducer ErrProducer) *Serializer

WriteObject writes the given Serializable to the Serializer.

func (*Serializer) WritePayload

func (s *Serializer) WritePayload(payload Serializable, deSeriMode DeSerializationMode, errProducer ErrProducer) *Serializer

WritePayload writes the given payload Serializable into the Serializer. This is different to WriteObject as it also writes the length denotation of the payload.

func (*Serializer) WriteSliceOfObjects

func (s *Serializer) WriteSliceOfObjects(seris Serializables, deSeriMode DeSerializationMode, woc WrittenObjectConsumer, errProducer ErrProducer) *Serializer

WriteSliceOfObjects writes Serializables into the Serializer. For every written Serializable, the given WrittenObjectConsumer is called if it isn't nil.

func (*Serializer) WriteString

func (s *Serializer) WriteString(str string, errProducer ErrProducer) *Serializer

WriteString writes the given string to the Serializer.

func (*Serializer) WriteVariableByteSlice

func (s *Serializer) WriteVariableByteSlice(data []byte, lenType SeriSliceLengthType, errProducer ErrProducer) *Serializer

WriteVariableByteSlice writes the given slice with its length to the Serializer.

func (*Serializer) Written

func (s *Serializer) Written() int

Written returns the amount of bytes written into the Serializer.

type SigLockedDustAllowanceOutput

type SigLockedDustAllowanceOutput struct {
	// The actual address.
	Address Serializable `json:"address"`
	// The amount to deposit.
	Amount uint64 `json:"amount"`
}

SigLockedDustAllowanceOutput functions like a SigLockedSingleOutput but as a special property it is used to increase the allowance/amount of dust outputs on a given address.

func (*SigLockedDustAllowanceOutput) Deposit

func (s *SigLockedDustAllowanceOutput) Deposit() (uint64, error)

func (*SigLockedDustAllowanceOutput) Deserialize

func (s *SigLockedDustAllowanceOutput) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*SigLockedDustAllowanceOutput) MarshalJSON

func (s *SigLockedDustAllowanceOutput) MarshalJSON() ([]byte, error)

func (*SigLockedDustAllowanceOutput) Serialize

func (s *SigLockedDustAllowanceOutput) Serialize(deSeriMode DeSerializationMode) (data []byte, err error)

func (*SigLockedDustAllowanceOutput) Target

func (*SigLockedDustAllowanceOutput) Type

func (*SigLockedDustAllowanceOutput) UnmarshalJSON

func (s *SigLockedDustAllowanceOutput) UnmarshalJSON(bytes []byte) error

type SigLockedSingleOutput

type SigLockedSingleOutput struct {
	// The actual address.
	Address Serializable `json:"address"`
	// The amount to deposit.
	Amount uint64 `json:"amount"`
}

SigLockedSingleOutput is an output type which can be unlocked via a signature. It deposits onto one single address.

func (*SigLockedSingleOutput) Deposit

func (s *SigLockedSingleOutput) Deposit() (uint64, error)

func (*SigLockedSingleOutput) Deserialize

func (s *SigLockedSingleOutput) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*SigLockedSingleOutput) MarshalJSON

func (s *SigLockedSingleOutput) MarshalJSON() ([]byte, error)

func (*SigLockedSingleOutput) Serialize

func (s *SigLockedSingleOutput) Serialize(deSeriMode DeSerializationMode) (data []byte, err error)

func (*SigLockedSingleOutput) Target

func (s *SigLockedSingleOutput) Target() (Serializable, error)

func (*SigLockedSingleOutput) Type

func (*SigLockedSingleOutput) UnmarshalJSON

func (s *SigLockedSingleOutput) UnmarshalJSON(bytes []byte) error

type SigValidationFunc

type SigValidationFunc = func() error

SigValidationFunc is a function which when called tells whether its signature verification computation was successful or not.

type SignatureType

type SignatureType = byte

Defines the type of signature.

const (
	// Denotes an Ed25519 signature.
	SignatureEd25519 SignatureType = iota

	// The size of a serialized Ed25519 signature with its type denoting byte and public key.
	Ed25519SignatureSerializedBytesSize = SmallTypeDenotationByteSize + ed25519.PublicKeySize + ed25519.SignatureSize
)

type SignatureUnlockBlock

type SignatureUnlockBlock struct {
	// The signature of this unlock block.
	Signature Serializable `json:"signature"`
}

SignatureUnlockBlock holds a signature which unlocks inputs.

func (*SignatureUnlockBlock) Deserialize

func (s *SignatureUnlockBlock) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*SignatureUnlockBlock) MarshalJSON

func (s *SignatureUnlockBlock) MarshalJSON() ([]byte, error)

func (*SignatureUnlockBlock) Serialize

func (s *SignatureUnlockBlock) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*SignatureUnlockBlock) UnmarshalJSON

func (s *SignatureUnlockBlock) UnmarshalJSON(bytes []byte) error

type SliceOfArraysOf32Bytes

type SliceOfArraysOf32Bytes = []ArrayOf32Bytes

SliceOfArraysOf32Bytes is a slice of arrays of which each is 32 bytes.

func RemoveDupsAndSortByLexicalOrderArrayOf32Bytes

func RemoveDupsAndSortByLexicalOrderArrayOf32Bytes(slice SliceOfArraysOf32Bytes) SliceOfArraysOf32Bytes

RemoveDupsAndSortByLexicalOrderArrayOf32Bytes returns a new SliceOfArraysOf32Bytes sorted by lexical order and without duplicates.

type SliceOfArraysOf64Bytes

type SliceOfArraysOf64Bytes = []ArrayOf64Bytes

SliceOfArraysOf64Bytes is a slice of arrays of which each is 64 bytes.

type SortedSerializables

type SortedSerializables Serializables

SortedSerializables are Serializables sorted by their serialized form.

func (SortedSerializables) Len

func (ss SortedSerializables) Len() int

func (SortedSerializables) Less

func (ss SortedSerializables) Less(i, j int) bool

func (SortedSerializables) Swap

func (ss SortedSerializables) Swap(i, j int)

type ToBeSignedUTXOInput

type ToBeSignedUTXOInput struct {
	// The address to which this input belongs to.
	Address Address `json:"address"`
	// The actual UTXO input.
	Input *UTXOInput `json:"input"`
}

ToBeSignedUTXOInput defines a UTXO input which needs to be signed.

type Transaction

type Transaction struct {
	// The transaction essence, respectively the transfer part of a Transaction.
	Essence Serializable
	// The unlock blocks defining the unlocking data for the inputs within the Essence.
	UnlockBlocks Serializables
}

Transaction is a transaction with its inputs, outputs and unlock blocks.

func (*Transaction) Deserialize

func (t *Transaction) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*Transaction) ID

func (t *Transaction) ID() (*TransactionID, error)

ID computes the ID of the Transaction.

func (*Transaction) MarshalJSON

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

func (*Transaction) SemanticallyValidate

func (t *Transaction) SemanticallyValidate(utxos InputToOutputMapping, semValFuncs ...SemanticValidationFunc) error

SemanticallyValidate semantically validates the Transaction by checking that the given input UTXOs are spent entirely and the signatures provided are valid. SyntacticallyValidate() should be called before SemanticallyValidate() to ensure that the essence part of the transaction is syntactically valid.

func (*Transaction) SemanticallyValidateInputs

func (t *Transaction) SemanticallyValidateInputs(utxos InputToOutputMapping, transaction *TransactionEssence, txEssenceBytes []byte) (uint64, []SigValidationFunc, error)

SemanticallyValidateInputs checks that every referenced UTXO is available, computes the input sum and returns functions which can be called to verify the signatures. This function should only be called from SemanticallyValidate().

func (*Transaction) SemanticallyValidateOutputs

func (t *Transaction) SemanticallyValidateOutputs(transaction *TransactionEssence) (uint64, error)

SemanticallyValidateOutputs accumulates the sum of all outputs. This function should only be called from SemanticallyValidate().

func (*Transaction) Serialize

func (t *Transaction) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*Transaction) SyntacticallyValidate

func (t *Transaction) SyntacticallyValidate() error

SyntacticallyValidate syntactically validates the Transaction:

  1. The TransactionEssence isn't nil
  2. syntactic validation on the TransactionEssence
  3. input and unlock blocks count must match
  4. signatures are unique and ref. unlock blocks reference a previous unlock block.

func (*Transaction) UnmarshalJSON

func (t *Transaction) UnmarshalJSON(bytes []byte) error

type TransactionBuilder

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

TransactionBuilder is used to easily build up a Transaction.

func NewTransactionBuilder

func NewTransactionBuilder() *TransactionBuilder

NewTransactionBuilder creates a new TransactionBuilder.

func (*TransactionBuilder) AddIndexationPayload

func (b *TransactionBuilder) AddIndexationPayload(payload *Indexation) *TransactionBuilder

AddIndexationPayload adds the given Indexation as the inner payload.

func (*TransactionBuilder) AddInput

AddInput adds the given input to the builder.

func (*TransactionBuilder) AddInputsViaNodeQuery

func (b *TransactionBuilder) AddInputsViaNodeQuery(addr Address, nodeHTTPAPIClient *NodeHTTPAPIClient, filter TransactionBuilderInputFilter) *TransactionBuilder

AddInputsViaNodeQuery adds any unspent outputs by the given address as an input to the built transaction if it passes the filter function. It is the caller's job to ensure that the limit of returned outputs on the queried node is enough high for the application's purpose. filter can be nil.

func (*TransactionBuilder) AddOutput

func (b *TransactionBuilder) AddOutput(output Output) *TransactionBuilder

AddOutput adds the given output to the builder.

func (*TransactionBuilder) Build

func (b *TransactionBuilder) Build(signer AddressSigner) (*Transaction, error)

Build sings the inputs with the given signer and returns the built payload.

func (*TransactionBuilder) BuildAndSwapToMessageBuilder

func (b *TransactionBuilder) BuildAndSwapToMessageBuilder(signer AddressSigner, txFunc TransactionFunc) *MessageBuilder

BuildAndSwapToMessageBuilder builds the transaction and then swaps to a MessageBuilder with the transaction set as its payload. txFunc can be nil.

type TransactionBuilderInputFilter

type TransactionBuilderInputFilter func(utxoInput *UTXOInput, input Output) bool

TransactionBuilderInputFilter is a filter function which determines whether an input should be used or not. (returning true = pass). The filter can also be used to accumulate data over the set of inputs, i.e. the input sum etc.

type TransactionEssence

type TransactionEssence struct {
	// The inputs of this transaction.
	Inputs Serializables `json:"inputs"`
	// The outputs of this transaction.
	Outputs Serializables `json:"outputs"`
	// The optional embedded payload.
	Payload Serializable `json:"payload"`
}

TransactionEssence is the essence part of a Transaction.

func (*TransactionEssence) Deserialize

func (u *TransactionEssence) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*TransactionEssence) MarshalJSON

func (u *TransactionEssence) MarshalJSON() ([]byte, error)

func (*TransactionEssence) Serialize

func (u *TransactionEssence) Serialize(deSeriMode DeSerializationMode) (data []byte, err error)

func (*TransactionEssence) SigningMessage

func (u *TransactionEssence) SigningMessage() ([]byte, error)

SigningMessage returns the to be signed message.

func (*TransactionEssence) SortInputsOutputs

func (u *TransactionEssence) SortInputsOutputs()

SortInputsOuputs sorts the inputs and outputs according to their serialized lexical representation. Usually an implicit call to SortInputsOutputs() should be done by instructing serialization to use DeSeriModePerformLexicalOrdering.

func (*TransactionEssence) SyntacticallyValidate

func (u *TransactionEssence) SyntacticallyValidate() error

SyntacticallyValidate checks whether the transaction essence is syntactically valid by checking whether:

  1. every input references a unique UTXO and has valid UTXO index bounds
  2. every output (per type) deposits to a unique address and deposits more than zero
  3. the accumulated deposit output is not over the total supply
  4. SigLockedDustAllowanceOutput deposits at least OutputSigLockedDustAllowanceOutputMinDeposit.

The function does not syntactically validate the input or outputs themselves.

func (*TransactionEssence) UnmarshalJSON

func (u *TransactionEssence) UnmarshalJSON(bytes []byte) error

type TransactionEssenceType

type TransactionEssenceType = byte

Defines the type of transaction.

type TransactionFunc

type TransactionFunc func(tx *Transaction)

TransactionFunc is a function which receives a Transaction as its parameter.

type TransactionID

type TransactionID = [TransactionIDLength]byte

TransactionID is the ID of a Transaction.

type TransactionIDs

type TransactionIDs []TransactionID

TransactionIDs are IDs of transactions.

type TreasuryInput

type TreasuryInput [32]byte

TreasuryInput is an input which references a milestone which generated a TreasuryOutput.

func (*TreasuryInput) Deserialize

func (ti *TreasuryInput) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*TreasuryInput) MarshalJSON

func (ti *TreasuryInput) MarshalJSON() ([]byte, error)

func (*TreasuryInput) Serialize

func (ti *TreasuryInput) Serialize(deSeriMode DeSerializationMode) (data []byte, err error)

func (*TreasuryInput) UnmarshalJSON

func (ti *TreasuryInput) UnmarshalJSON(bytes []byte) error

type TreasuryOutput

type TreasuryOutput struct {
	// The currently residing funds in the treasury.
	Amount uint64 `json:"deposit"`
}

TreasuryOutput is an output which holds the treasury of a network.

func (*TreasuryOutput) Deserialize

func (t *TreasuryOutput) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*TreasuryOutput) MarshalJSON

func (t *TreasuryOutput) MarshalJSON() ([]byte, error)

func (*TreasuryOutput) Serialize

func (t *TreasuryOutput) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*TreasuryOutput) UnmarshalJSON

func (t *TreasuryOutput) UnmarshalJSON(bytes []byte) error

type TreasuryResponse

type TreasuryResponse struct {
	MilestoneID string `json:"milestoneId"`
	Amount      uint64 `json:"amount"`
}

TreasuryResponse defines the response of a GET treasury REST API call.

type TreasuryTransaction

type TreasuryTransaction struct {
	// The input of this transaction.
	Input Serializable `json:"input"`
	// The output of this transaction.
	Output Serializable `json:"output"`
}

TreasuryTransaction represents a transaction which moves funds from the treasury.

func (*TreasuryTransaction) Deserialize

func (t *TreasuryTransaction) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*TreasuryTransaction) MarshalJSON

func (t *TreasuryTransaction) MarshalJSON() ([]byte, error)

func (*TreasuryTransaction) Serialize

func (t *TreasuryTransaction) Serialize(deSeriMode DeSerializationMode) ([]byte, error)

func (*TreasuryTransaction) UnmarshalJSON

func (t *TreasuryTransaction) UnmarshalJSON(bytes []byte) error

type TypeDenotationType

type TypeDenotationType byte
const (
	// Defines a denotation which defines a type ID by a uint32.
	TypeDenotationUint32 TypeDenotationType = iota
	// Defines a denotation which defines a type ID by a byte.
	TypeDenotationByte
	// Defines that there is no type denotation.
	TypeDenotationNone
)

type UTXOInput

type UTXOInput struct {
	// The transaction ID of the referenced transaction.
	TransactionID [TransactionIDLength]byte
	// The output index of the output on the referenced transaction.
	TransactionOutputIndex uint16
}

UTXOInput references an unspent transaction output by the Transaction's ID and the corresponding index of the output.

func (*UTXOInput) Deserialize

func (u *UTXOInput) Deserialize(data []byte, deSeriMode DeSerializationMode) (int, error)

func (*UTXOInput) ID

func (u *UTXOInput) ID() UTXOInputID

ID returns the UTXOInputID.

func (*UTXOInput) MarshalJSON

func (u *UTXOInput) MarshalJSON() ([]byte, error)

func (*UTXOInput) Serialize

func (u *UTXOInput) Serialize(deSeriMode DeSerializationMode) (data []byte, err error)

func (*UTXOInput) UnmarshalJSON

func (u *UTXOInput) UnmarshalJSON(bytes []byte) error

type UTXOInputID

UTXOInputID defines the identifier for an UTXO input which consists out of the referenced transaction ID and the given output index.

func (UTXOInputID) ToHex

func (utxoInputID UTXOInputID) ToHex() string

ToHex converts the UTXOInputID to its hex representation.

type UTXOInputIDs

type UTXOInputIDs []UTXOInputID

UTXOInputIDs is a slice of UTXOInputID.

func (UTXOInputIDs) ToHex

func (utxoInputIDs UTXOInputIDs) ToHex() []string

ToHex converts all UTXOInput to their hex string representation.

type UnlockBlockType

type UnlockBlockType = byte

Defines a type of unlock block.

type UnlockBlockValidatorFunc

type UnlockBlockValidatorFunc func(index int, unlockBlock Serializable) error

UnlockBlockValidatorFunc which given the index of an unlock block and the unlock block itself, runs validations and returns an error if any should fail.

func UnlockBlocksSigUniqueAndRefValidator

func UnlockBlocksSigUniqueAndRefValidator() UnlockBlockValidatorFunc

UnlockBlocksSigUniqueAndRefValidator returns a validator which checks that:

  1. signature unlock blocks are unique
  2. reference unlock blocks reference a previous signature unlock block

type WrittenObjectConsumer

type WrittenObjectConsumer func(index int, written []byte) error

WrittenObjectConsumer gets called after an object has been serialized into a Serializer.

Directories

Path Synopsis
Package bech32 implements bech32 encoding and decoding.
Package bech32 implements bech32 encoding and decoding.
internal/base32
Package base32 implements the conversion for bytes (base256) to base32.
Package base32 implements the conversion for bytes (base256) to base32.
Package ed25519 implements the Ed25519 signature algorithm.
Package ed25519 implements the Ed25519 signature algorithm.
Package pow implements the Curl-based proof of work for arbitrary binary data.
Package pow implements the Curl-based proof of work for arbitrary binary data.
Package units provides functions for converting different units of IOTAs.
Package units provides functions for converting different units of IOTAs.

Jump to

Keyboard shortcuts

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