iotago

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2021 License: MIT Imports: 21 Imported by: 58

README

iota.go

Official Go library.

This library allows you to do the following:

  • Create messages with indexation and transaction payloads
  • Get messages and outputs
  • Sign transactions
  • Generate addresses
  • Interact with an IOTA node
  • Act as a foundation for Go based node software

If you need to have more sophisticated account management, have a look at wallet.rs for which we also provide bindings in Python and JavaScript.

Requirements

This library was mainly tested with Go version 1.16.x

To use the library, we recommend you update Go to the latest stable version.

Using the library

Using the library is easy, just go get it as any other dependency:

go get github.com/iotaledger/iota.go/v2

API reference

You can read the API reference here.

Joining the discussion

If you want to get involved in the community, need help with setting up, have any issues or just want to discuss IOTA with other people, feel free to join our Discord in the #clients-dev and #clients-discussion channels.

License

The MIT license can be found here.

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 (
	// Ed25519AddressBytesLength is the length of an Ed25519 address.
	Ed25519AddressBytesLength = blake2b.Size256
	// Ed25519AddressSerializedBytesSize is the size of a serialized Ed25519 address with its type denoting byte.
	Ed25519AddressSerializedBytesSize = serializer.SmallTypeDenotationByteSize + Ed25519AddressBytesLength
)
View Source
const (
	// IndexationPayloadTypeID defines the indexation payload's ID.
	IndexationPayloadTypeID uint32 = 2
	// IndexationBinSerializedMinSize is the minimum size of an Indexation.
	// 	type bytes + index prefix + one char + data length
	IndexationBinSerializedMinSize = serializer.TypeDenotationByteSize + serializer.UInt16ByteSize + serializer.OneByte + serializer.UInt32ByteSize
	// IndexationIndexMaxLength defines the max length of the index within an Indexation.
	IndexationIndexMaxLength = 64
	// IndexationIndexMinLength defines the min length of the index within an Indexation.
	IndexationIndexMinLength = 1
)
View Source
const (
	// MessageIDLength defines the length of a message ID.
	MessageIDLength = blake2b.Size256
	// MessageNetworkIDLength defines the length of the network ID in bytes.
	MessageNetworkIDLength = serializer.UInt64ByteSize
	// MessageBinSerializedMinSize defines the minimum size of a message: network ID + parent count + 1 parent + uint16 payload length + nonce
	MessageBinSerializedMinSize = MessageNetworkIDLength + serializer.OneByte + MessageIDLength + serializer.UInt32ByteSize + serializer.UInt64ByteSize
	// MessageBinSerializedMaxSize defines the maximum size of a message.
	MessageBinSerializedMaxSize = 32768
	// MinParentsInAMessage defines the minimum amount of parents in a message.
	MinParentsInAMessage = 1
	// MaxParentsInAMessage defines the maximum amount of parents in a message.
	MaxParentsInAMessage = 8
)
View Source
const (
	// MilestonePayloadTypeID defines the Milestone payload's ID.
	MilestonePayloadTypeID uint32 = 1
	// MilestoneInclusionMerkleProofLength defines the length of the inclusion merkle proof within a milestone payload.
	MilestoneInclusionMerkleProofLength = blake2b.Size256
	// MilestoneSignatureLength defines the length of the milestone signature.
	MilestoneSignatureLength = ed25519.SignatureSize
	// MilestoneIDLength defines the length of a Milestone ID.
	MilestoneIDLength = blake2b.Size256
	// MilestonePublicKeyLength defines the length of a public key within a milestone.
	MilestonePublicKeyLength = ed25519.PublicKeySize
	// MilestoneBinSerializedMinSize 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 = serializer.TypeDenotationByteSize + serializer.UInt32ByteSize + serializer.UInt64ByteSize + serializer.OneByte + MessageIDLength +
		MilestoneInclusionMerkleProofLength + serializer.OneByte + ed25519.PublicKeySize + serializer.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 (
	// 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 its 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 its 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 its 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 its milestoneIndex.
	// GET returns the milestone.
	NodeAPIRouteMilestone = "/api/v1/milestones/%s"

	// NodeAPIRouteMilestoneUTXOChanges is the route for getting all UTXO changes of a milestone by its milestoneIndex.
	// GET returns the output IDs of all UTXO changes.
	NodeAPIRouteMilestoneUTXOChanges = "/api/v1/milestones/%s/utxo-changes"

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

	// NodeAPIRouteAddressBech32Balance is the route for getting the total balance of all unspent outputs of a Bech32 address.
	// GET returns the balance of all unspent outputs of this address.
	NodeAPIRouteAddressBech32Balance = "/api/v1/addresses/%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"

	// NodeAPIRouteAddressBech32Outputs is the route for getting all output IDs for a Bech32 address.
	// GET returns the outputIDs for all outputs of this address (optional query parameters: "include-spent").
	NodeAPIRouteAddressBech32Outputs = "/api/v1/addresses/%s/outputs"

	// 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 (
	// OutputSigLockedSingleOutput denotes a type of output which is locked by a signature and deposits onto a single address.
	OutputSigLockedSingleOutput OutputType = iota
	// OutputSigLockedDustAllowanceOutput is like OutputSigLockedSingleOutput but it is used to increase the allowance/amount of dust outputs on a given address.
	OutputSigLockedDustAllowanceOutput
	// OutputTreasuryOutput denotes the type of the TreasuryOutput.
	OutputTreasuryOutput
	// OutputSigLockedDustAllowanceOutputMinDeposit defines the minimum deposit amount of a SigLockedDustAllowanceOutput.
	OutputSigLockedDustAllowanceOutputMinDeposit uint64 = 1_000_000
)
View Source
const (
	// ReceiptPayloadTypeID defines the Receipt payload's ID.
	ReceiptPayloadTypeID uint32 = 3
	// MinMigratedFundsEntryCount defines the minimum amount of MigratedFundsEntry items within a Receipt.
	MinMigratedFundsEntryCount = 1
	// MaxMigratedFundsEntryCount defines the maximum amount of MigratedFundsEntry items within a Receipt.
	MaxMigratedFundsEntryCount = 127
)
View Source
const (
	// SigLockedDustAllowanceOutputEd25519AddrBytesSize is the size of a SigLockedDustAllowanceOutput containing an Ed25519Address as its deposit address.
	SigLockedDustAllowanceOutputEd25519AddrBytesSize = serializer.SmallTypeDenotationByteSize + Ed25519AddressSerializedBytesSize + serializer.UInt64ByteSize

	// SigLockedDustAllowanceOutputBytesMinSize defines the minimum size of a SigLockedDustAllowanceOutput.
	SigLockedDustAllowanceOutputBytesMinSize = SigLockedDustAllowanceOutputEd25519AddrBytesSize
	// SigLockedDustAllowanceOutputAddressOffset defines the offset at which the address portion within a SigLockedDustAllowanceOutput begins.
	SigLockedDustAllowanceOutputAddressOffset = serializer.SmallTypeDenotationByteSize
)
View Source
const (
	// SigLockedSingleOutputEd25519AddrBytesSize defines the size of a SigLockedSingleOutput containing an Ed25519Address as its deposit address.
	SigLockedSingleOutputEd25519AddrBytesSize = serializer.SmallTypeDenotationByteSize + Ed25519AddressSerializedBytesSize + serializer.UInt64ByteSize

	// SigLockedSingleOutputBytesMinSize defines the minimum size a SigLockedSingleOutput.
	SigLockedSingleOutputBytesMinSize = SigLockedSingleOutputEd25519AddrBytesSize
	// SigLockedSingleOutputAddressOffset defines the offset at which the address portion within a SigLockedSingleOutput begins.
	SigLockedSingleOutputAddressOffset = serializer.SmallTypeDenotationByteSize
)
View Source
const (
	// TransactionPayloadTypeID defines the transaction payload's type ID.
	TransactionPayloadTypeID uint32 = 0

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

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

	// DustAllowanceDivisor 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
	// MaxDustOutputsOnAddress defines the maximum amount of dust outputs allowed to "reside" on an address.
	MaxDustOutputsOnAddress = 100
)
View Source
const (
	// TransactionEssenceNormal denotes a standard transaction essence.
	TransactionEssenceNormal TransactionEssenceType = iota

	// TransactionEssenceMinByteSize defines the minimum size of a TransactionEssence.
	TransactionEssenceMinByteSize = serializer.TypeDenotationByteSize + serializer.UInt16ByteSize + serializer.UInt16ByteSize + serializer.PayloadLengthByteSize

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

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

	// UTXOInputSize is the size of a UTXO input: input type + tx id + index
	UTXOInputSize = serializer.SmallTypeDenotationByteSize + TransactionIDLength + serializer.UInt16ByteSize
)
View Source
const (
	// MinMigratedFundsEntryDeposit defines the minimum amount a MigratedFundsEntry must deposit.
	MinMigratedFundsEntryDeposit = 1_000_000
)
View Source
const (
	// TokenSupply is the IOTA token supply.
	TokenSupply = 2_779_530_283_277_761
)
View Source
const (
	// TreasuryOutputBytesSize defines the binary serialized size of a TreasuryOutput.
	TreasuryOutputBytesSize = serializer.SmallTypeDenotationByteSize + serializer.UInt64ByteSize
)

Variables

View Source
var (
	// ErrAddressKeysNotMapped gets returned if the needed keys to sign a message are absent/not mapped.
	ErrAddressKeysNotMapped = errors.New("key(s) for address not mapped")
	// ErrAddressKeysWrongType gets 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 (
	// ErrUnsupportedPayloadType gets returned for unsupported payload types.
	ErrUnsupportedPayloadType = errors.New("unsupported payload type")
	// ErrUnsupportedObjectType gets returned for unsupported object types.
	ErrUnsupportedObjectType = errors.New("unsupported object type")
	// ErrUnknownPayloadType gets returned for unknown payload types.
	ErrUnknownPayloadType = errors.New("unknown payload type")
	// ErrUnknownAddrType gets returned for unknown address types.
	ErrUnknownAddrType = errors.New("unknown address type")
	// ErrUnknownInputType gets returned for unknown input types.
	ErrUnknownInputType = errors.New("unknown input type")
	// ErrUnknownOutputType gets returned for unknown output types.
	ErrUnknownOutputType = errors.New("unknown output type")
	// ErrUnknownTransactionEssenceType gets returned for unknown transaction essence types.
	ErrUnknownTransactionEssenceType = errors.New("unknown transaction essence type")
	// ErrUnknownUnlockBlockType gets returned for unknown unlock blocks.
	ErrUnknownUnlockBlockType = errors.New("unknown unlock block type")
	// ErrUnknownSignatureType gets returned for unknown signature types.
	ErrUnknownSignatureType = errors.New("unknown signature type")
)
View Source
var (
	// ErrIndexationIndexExceedsMaxSize gets returned when an Indexation's index exceeds IndexationIndexMaxLength.
	ErrIndexationIndexExceedsMaxSize = errors.New("index exceeds max size")
	// ErrIndexationIndexUnderMinSize gets returned when an Indexation's index is under IndexationIndexMinLength.
	ErrIndexationIndexUnderMinSize = errors.New("index is below min size")
)
View Source
var (
	// ErrMilestoneTooFewSignatures gets 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")
	// ErrMilestoneTooFewSignaturesForVerificationThreshold gets returned if there are less signatures within a Milestone than the min. threshold.
	ErrMilestoneTooFewSignaturesForVerificationThreshold = errors.New("too few signatures for verification")
	// ErrMilestoneTooFewPublicKeys gets 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")
	// ErrMilestoneProducedSignaturesCountMismatch gets returned when a MilestoneSigningFunc produces less signatures than expected.
	ErrMilestoneProducedSignaturesCountMismatch = errors.New("produced and wanted signature count mismatch")
	// ErrMilestoneSignaturesPublicKeyCountMismatch gets 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")
	// ErrMilestoneTooManySignatures gets returned when a Milestone holds more than 255 signatures.
	ErrMilestoneTooManySignatures = fmt.Errorf("a milestone can hold max %d signatures", MaxSignaturesInAMilestone)
	// ErrMilestoneInvalidMinSignatureThreshold gets returned when an invalid min signatures threshold is given to the verification function.
	ErrMilestoneInvalidMinSignatureThreshold = fmt.Errorf("min threshold must be at least 1")
	// ErrMilestoneNonApplicablePublicKey gets 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")
	// ErrMilestoneSignatureThresholdGreaterThanApplicablePublicKeySet gets 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")
	// ErrMilestoneInvalidSignature gets returned when a Milestone's signature is invalid.
	ErrMilestoneInvalidSignature = fmt.Errorf("invalid milestone signature")
	// ErrMilestoneInMemorySignerPrivateKeyMissing gets returned when an InMemoryEd25519MilestoneSigner is missing a private key.
	ErrMilestoneInMemorySignerPrivateKeyMissing = fmt.Errorf("private key missing")
	// ErrMilestoneDuplicatedPublicKey gets returned when a Milestone contains duplicated public keys.
	ErrMilestoneDuplicatedPublicKey = fmt.Errorf("milestone contains duplicated public keys")
	// ErrMilestoneInvalidMinPoWScoreValues gets returned when the min. PoW score fields are invalid.
	ErrMilestoneInvalidMinPoWScoreValues = fmt.Errorf("invalid milestone min pow score values")
)
View Source
var (
	// ErrHTTPBadRequest gets returned for 400 bad request HTTP responses.
	ErrHTTPBadRequest = errors.New("bad request")
	// ErrHTTPInternalServerError gets returned for 500 internal server error HTTP responses.
	ErrHTTPInternalServerError = errors.New("internal server error")
	// ErrHTTPNotFound gets returned for 404 not found error HTTP responses.
	ErrHTTPNotFound = errors.New("not found")
	// ErrHTTPUnauthorized gets returned for 401 unauthorized error HTTP responses.
	ErrHTTPUnauthorized = errors.New("unauthorized")
	// ErrHTTPUnknownError gets returned for unknown error HTTP responses.
	ErrHTTPUnknownError = errors.New("unknown error")
	// ErrHTTPNotImplemented gets returned for 501 not implemented error HTTP responses.
	ErrHTTPNotImplemented = errors.New("operation not implemented/supported/available")
)
View Source
var (
	// ErrEd25519PubKeyAndAddrMismatch gets returned when an Ed25519Address and public key do not correspond to each other.
	ErrEd25519PubKeyAndAddrMismatch = errors.New("public key and address do not correspond to each other (Ed25519)")
	// ErrEd25519SignatureInvalid gets returned for invalid an Ed25519Signature.
	ErrEd25519SignatureInvalid = errors.New("signature is invalid (Ed25519")
)
View Source
var (
	// ErrUnlockBlocksMustMatchInputCount gets 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")
	// ErrInvalidTransactionEssence gets returned if the transaction essence within a Transaction is invalid.
	ErrInvalidTransactionEssence = errors.New("transaction essence is invalid")
	// ErrMissingUTXO gets returned if an UTXO is missing to commence a certain operation.
	ErrMissingUTXO = errors.New("missing utxo")
	// ErrInputOutputSumMismatch gets 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 gets returned for errors where an input has a wrong companion signature unlock block.
	ErrInputSignatureUnlockBlockInvalid = errors.New("companion signature unlock block is invalid for input")
	// ErrSignatureAndAddrIncompatible gets 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")
	// ErrInvalidDustAllowance gets returned for errors where the dust allowance is semantically invalid.
	ErrInvalidDustAllowance = errors.New("invalid dust allowance")
)
View Source
var (
	// ErrMinInputsNotReached gets returned if the count of inputs is too small.
	ErrMinInputsNotReached = fmt.Errorf("min %d input(s) are required within a transaction", MinInputsCount)
	// ErrMinOutputsNotReached gets returned if the count of outputs is too small.
	ErrMinOutputsNotReached = fmt.Errorf("min %d output(s) are required within a transaction", MinOutputsCount)
	// ErrInputUTXORefsNotUnique gets returned if multiple inputs reference the same UTXO.
	ErrInputUTXORefsNotUnique = errors.New("inputs must each reference a unique UTXO")
	// ErrOutputAddrNotUnique gets returned if multiple outputs deposit to the same address.
	ErrOutputAddrNotUnique = errors.New("outputs must each deposit to a unique address")
	// ErrOutputsSumExceedsTotalSupply gets returned if the sum of the output deposits exceeds the total supply of tokens.
	ErrOutputsSumExceedsTotalSupply = errors.New("accumulated output balance exceeds total supply")
	// ErrOutputDepositsMoreThanTotalSupply gets returned if an output deposits more than the total supply.
	ErrOutputDepositsMoreThanTotalSupply = errors.New("an output can not deposit more than the total supply")
	// ErrOutputDustAllowanceLessThanMinDeposit gets returned if a SigLockedDustAllowanceOutput deposits less than OutputSigLockedDustAllowanceOutputMinDeposit.
	ErrOutputDustAllowanceLessThanMinDeposit = errors.New("dust allowance output deposits less than the minimum required amount")
)
View Source
var (
	// ErrSigUnlockBlocksNotUnique gets returned if unlock blocks making part of a transaction aren't unique.
	ErrSigUnlockBlocksNotUnique = errors.New("signature unlock blocks must be unique")
	// ErrRefUnlockBlockInvalidRef gets 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")
	// ErrSigUnlockBlockHasNilSig gets returned if a signature unlock block contains a nil signature.
	ErrSigUnlockBlockHasNilSig = errors.New("signature is nil")
)
View Source
var (
	// ErrDepositAmountMustBeGreaterThanZero 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 (
	// ErrInvalidJSON gets returned when invalid JSON is tried to get parsed.
	ErrInvalidJSON = errors.New("invalid json")
)
View Source
var (
	// ErrInvalidReceipt gets returned when a receipt is invalid.
	ErrInvalidReceipt = errors.New("invalid receipt")
)
View Source
var (
	// ErrMessageExceedsMaxSize gets returned when a serialized message exceeds MessageBinSerializedMaxSize.
	ErrMessageExceedsMaxSize = errors.New("message exceeds max size")
)
View Source
var (
	// ErrReceiptMustContainATreasuryTransaction gets returned if a Receipt does not contain a TreasuryTransaction.
	ErrReceiptMustContainATreasuryTransaction = errors.New("receipt must contain a treasury transaction")
)
View Source
var (
	// ErrRefUTXOIndexInvalid gets 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 AddressSelector

func AddressSelector(addressType uint32) (serializer.Serializable, error)

AddressSelector implements SerializableSelectorFunc for address types.

func InputSelector

func InputSelector(inputType uint32) (serializer.Serializable, error)

InputSelector implements SerializableSelectorFunc for input types.

func MessageIDToHexString

func MessageIDToHexString(msgID MessageID) string

MessageIDToHexString converts the given message ID to their hex representation.

func OutputSelector

func OutputSelector(outputType uint32) (serializer.Serializable, error)

OutputSelector implements SerializableSelectorFunc for output types.

func ParseBech32

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

ParseBech32 decodes a bech32 encoded string.

func PayloadSelector

func PayloadSelector(payloadType uint32) (serializer.Serializable, error)

PayloadSelector implements SerializableSelectorFunc for payload types.

func SignatureSelector

func SignatureSelector(sigType uint32) (serializer.Serializable, error)

SignatureSelector implements SerializableSelectorFunc for signature types.

func TransactionEssenceSelector

func TransactionEssenceSelector(txType uint32) (serializer.Serializable, error)

TransactionEssenceSelector implements SerializableSelectorFunc for transaction essence types.

func UnlockBlockSelector

func UnlockBlockSelector(unlockBlockType uint32) (serializer.Serializable, error)

UnlockBlockSelector implements SerializableSelectorFunc for unlock block types.

func ValidateInputs

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

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

func ValidateOutputs

func ValidateOutputs(outputs serializer.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 serializer.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 {
	serializer.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"`
	// Indicates if dust is allowed on this address.
	DustAllowed bool `json:"dustAllowed"`
	// The ledger index at which this balance was queried at.
	LedgerIndex uint64 `json:"ledgerIndex"`
}

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"`
	// The ledger index at which these outputs where available at.
	LedgerIndex uint64 `json:"ledgerIndex"`
}

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 serializer.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 serializer.Serializable, err error)

AddressSignerFunc implements the AddressSigner interface.

func (AddressSignerFunc) Sign

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

type AddressType

type AddressType = byte

AddressType defines the type of addresses.

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

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 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

Ed25519Address defines an Ed25519 address. An Ed25519Address is the Blake2b-256 hash of a Ed25519 public key.

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 serializer.DeSerializationMode) (int, error)

func (*Ed25519Address) MarshalJSON

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

func (*Ed25519Address) Serialize

func (edAddr *Ed25519Address) Serialize(deSeriMode serializer.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 serializer.DeSerializationMode) (int, error)

func (*Ed25519Signature) MarshalJSON

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

func (*Ed25519Signature) Serialize

func (e *Ed25519Signature) Serialize(deSeriMode serializer.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 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"`
}

HTTPErrorResponseEnvelope defines the error response schema for node API responses.

type HTTPOkResponseEnvelope

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

HTTPOkResponseEnvelope 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 serializer.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 serializer.DeSerializationMode) (int, error)

func (*Indexation) MarshalJSON

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

func (*Indexation) Serialize

func (u *Indexation) Serialize(deSeriMode serializer.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

InputType defines the type of inputs.

const (
	// InputUTXO is a type of input which references an unspent transaction output.
	InputUTXO InputType = iota
	// InputTreasury is 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() (serializer.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 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 serializer.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 serializer.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 serializer.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

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

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"`
	// If this message represents a milestone this is the milestone index
	MilestoneIndex *uint32 `json:"milestoneIndex,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 serializer.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 serializer.DeSerializationMode) (int, error)

func (*MigratedFundsEntry) MarshalJSON

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

func (*MigratedFundsEntry) Serialize

func (m *MigratedFundsEntry) Serialize(deSeriMode serializer.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 next minimum PoW score to use after NextPoWScoreMilestoneIndex is hit.
	NextPoWScore uint32
	// The milestone index at which the PoW score changes to NextPoWScore.
	NextPoWScoreMilestoneIndex uint32
	// The public keys validating the signatures of the milestone.
	PublicKeys []MilestonePublicKey
	// The inner payload of the milestone. Can be nil or a Receipt.
	Receipt serializer.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 serializer.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 serializer.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 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 MilestoneUTXOChangesResponse

type MilestoneUTXOChangesResponse struct {
	// The index of the milestone.
	Index uint32 `json:"index"`
	// The output IDs (transaction hash + output index) of the newly created outputs.
	CreatedOutputs []string `json:"createdOutputs"`
	// The output IDs (transaction hash + output index) of the consumed (spent) outputs.
	ConsumedOutputs []string `json:"consumedOutputs"`
}

MilestoneUTXOChangesResponse defines the response of a GET milestone UTXO changes REST API call.

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 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(ctx context.Context, multiAddress string, alias ...string) (*PeerResponse, error)

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

func (*NodeHTTPAPIClient) BalanceByBech32Address

func (api *NodeHTTPAPIClient) BalanceByBech32Address(ctx context.Context, bech32Addr string) (*AddressBalanceResponse, error)

BalanceByBech32Address returns the balance of the given Bech32 address.

func (*NodeHTTPAPIClient) BalanceByEd25519Address

func (api *NodeHTTPAPIClient) BalanceByEd25519Address(ctx context.Context, addr *Ed25519Address) (*AddressBalanceResponse, error)

BalanceByEd25519Address returns the balance of an Ed25519 address.

func (*NodeHTTPAPIClient) ChildrenByMessageID

func (api *NodeHTTPAPIClient) ChildrenByMessageID(ctx context.Context, msgID MessageID) (*ChildrenResponse, error)

ChildrenByMessageID get a message by its message ID from the node.

func (*NodeHTTPAPIClient) Do

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

func (*NodeHTTPAPIClient) Health

func (api *NodeHTTPAPIClient) Health(ctx context.Context) (bool, error)

Health returns whether the given node is healthy.

func (*NodeHTTPAPIClient) Info

Info gets the info of the node.

func (*NodeHTTPAPIClient) MessageByMessageID

func (api *NodeHTTPAPIClient) MessageByMessageID(ctx context.Context, msgID MessageID) (*Message, error)

MessageByMessageID get a message by its message ID from the node.

func (*NodeHTTPAPIClient) MessageIDsByIndex

func (api *NodeHTTPAPIClient) MessageIDsByIndex(ctx context.Context, index []byte) (*MessageIDsByIndexResponse, error)

MessageIDsByIndex gets message IDs filtered by index from the node.

func (*NodeHTTPAPIClient) MessageMetadataByMessageID

func (api *NodeHTTPAPIClient) MessageMetadataByMessageID(ctx context.Context, msgID MessageID) (*MessageMetadataResponse, error)

MessageMetadataByMessageID gets the metadata of a message by its message ID from the node.

func (*NodeHTTPAPIClient) MilestoneByIndex

func (api *NodeHTTPAPIClient) MilestoneByIndex(ctx context.Context, index uint32) (*MilestoneResponse, error)

MilestoneByIndex gets a milestone by its index.

func (*NodeHTTPAPIClient) MilestoneUTXOChangesByIndex

func (api *NodeHTTPAPIClient) MilestoneUTXOChangesByIndex(ctx context.Context, index uint32) (*MilestoneUTXOChangesResponse, error)

MilestoneUTXOChangesByIndex returns all UTXO changes of a milestone by its milestoneIndex.

func (*NodeHTTPAPIClient) OutputByID

func (api *NodeHTTPAPIClient) OutputByID(ctx context.Context, utxoID UTXOInputID) (*NodeOutputResponse, error)

OutputByID gets an outputs by its ID from the node.

func (*NodeHTTPAPIClient) OutputIDsByBech32Address

func (api *NodeHTTPAPIClient) OutputIDsByBech32Address(ctx context.Context, bech32Addr string, includeSpentOutputs bool) (*AddressOutputsResponse, error)

OutputIDsByBech32Address gets output IDs of outputs residing on the given Bech32 address. Per default only unspent outputs IDs are returned. Set includeSpentOutputs to true to also return spent output IDs.

func (*NodeHTTPAPIClient) OutputIDsByEd25519Address

func (api *NodeHTTPAPIClient) OutputIDsByEd25519Address(ctx context.Context, addr *Ed25519Address, includeSpentOutputs bool) (*AddressOutputsResponse, error)

OutputIDsByEd25519Address gets output IDs of outputs residing on the given Ed25519Address. Per default only unspent output IDs are returned. Set includeSpentOutputs to true to also return spent output IDs.

func (*NodeHTTPAPIClient) OutputsByBech32Address

func (api *NodeHTTPAPIClient) OutputsByBech32Address(ctx context.Context, bech32Addr string, includeSpentOutputs bool) (*AddressOutputsResponse, map[*UTXOInput]Output, error)

OutputsByBech32Address gets the outputs residing on the given Bech32 address. Per default only unspent outputs are returned. Set includeSpentOutputs to true to also return spent outputs.

func (*NodeHTTPAPIClient) OutputsByEd25519Address

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

OutputsByEd25519Address gets the outputs residing on the given Ed25519Address. Per default only unspent outputs are returned. Set includeSpentOutputs to true to also return spent outputs.

func (*NodeHTTPAPIClient) PeerByID

func (api *NodeHTTPAPIClient) PeerByID(ctx context.Context, id string) (*PeerResponse, error)

PeerByID gets a peer by its identifier.

func (*NodeHTTPAPIClient) Peers

func (api *NodeHTTPAPIClient) Peers(ctx context.Context) ([]*PeerResponse, error)

Peers returns a list of all peers.

func (*NodeHTTPAPIClient) Receipts

func (api *NodeHTTPAPIClient) Receipts(ctx context.Context) ([]*ReceiptTuple, error)

Receipts gets all receipts persisted on the node.

func (*NodeHTTPAPIClient) ReceiptsByMigratedAtIndex

func (api *NodeHTTPAPIClient) ReceiptsByMigratedAtIndex(ctx context.Context, index uint32) ([]*ReceiptTuple, error)

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

func (*NodeHTTPAPIClient) RemovePeerByID

func (api *NodeHTTPAPIClient) RemovePeerByID(ctx context.Context, id string) error

RemovePeerByID removes a peer by its identifier.

func (*NodeHTTPAPIClient) SubmitMessage

func (api *NodeHTTPAPIClient) SubmitMessage(ctx context.Context, 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

Tips gets the two tips from the node.

func (*NodeHTTPAPIClient) Treasury

func (api *NodeHTTPAPIClient) Treasury(ctx context.Context) (*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 current rate of new messages per second.
	MessagesPerSecond float64 `json:"messagesPerSecond"`
	// The current rate of referenced messages per second.
	ReferencedMessagesPerSecond float64 `json:"referencedMessagesPerSecond"`
	// The ratio of referenced messages in relation to new messages of the last confirmed milestone.
	ReferencedRate float64 `json:"referencedRate"`
	// The timestamp of the latest known milestone.
	LatestMilestoneTimestamp int64 `json:"latestMilestoneTimestamp"`
	// 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 ledger index at which this output was available at.
	LedgerIndex uint64 `json:"ledgerIndex"`
	// 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 {
	serializer.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() (serializer.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

OutputType 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 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 serializer.Serializables
	// The TreasuryTransaction used to fund the funds.
	Transaction serializer.Serializable
}

Receipt is a listing of migrated funds.

func (*Receipt) Deserialize

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

func (*Receipt) MarshalJSON

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

func (*Receipt) Serialize

func (r *Receipt) Serialize(deSeriMode serializer.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 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 serializer.DeSerializationMode) (int, error)

func (*ReferenceUnlockBlock) MarshalJSON

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

func (*ReferenceUnlockBlock) Serialize

func (r *ReferenceUnlockBlock) Serialize(deSeriMode serializer.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 SigLockedDustAllowanceOutput

type SigLockedDustAllowanceOutput struct {
	// The actual address.
	Address serializer.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 serializer.DeSerializationMode) (int, error)

func (*SigLockedDustAllowanceOutput) MarshalJSON

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

func (*SigLockedDustAllowanceOutput) Serialize

func (s *SigLockedDustAllowanceOutput) Serialize(deSeriMode serializer.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 serializer.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 serializer.DeSerializationMode) (int, error)

func (*SigLockedSingleOutput) MarshalJSON

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

func (*SigLockedSingleOutput) Serialize

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

func (*SigLockedSingleOutput) Target

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

SignatureType defines the type of signature.

const (
	// SignatureEd25519 denotes an Ed25519Signature.
	SignatureEd25519 SignatureType = iota

	// Ed25519SignatureSerializedBytesSize defines the size of a serialized Ed25519Signature with its type denoting byte and public key.
	Ed25519SignatureSerializedBytesSize = serializer.SmallTypeDenotationByteSize + ed25519.PublicKeySize + ed25519.SignatureSize
)

type SignatureUnlockBlock

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

SignatureUnlockBlock holds a signature which unlocks inputs.

func (*SignatureUnlockBlock) Deserialize

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

func (*SignatureUnlockBlock) MarshalJSON

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

func (*SignatureUnlockBlock) Serialize

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

func (*SignatureUnlockBlock) UnmarshalJSON

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

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 serializer.Serializable
	// The unlock blocks defining the unlocking data for the inputs within the Essence.
	UnlockBlocks serializer.Serializables
}

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

func (*Transaction) Deserialize

func (t *Transaction) Deserialize(data []byte, deSeriMode serializer.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 serializer.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(ctx context.Context, 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 serializer.Serializables `json:"inputs"`
	// The outputs of this transaction.
	Outputs serializer.Serializables `json:"outputs"`
	// The optional embedded payload.
	Payload serializer.Serializable `json:"payload"`
}

TransactionEssence is the essence part of a Transaction.

func (*TransactionEssence) Deserialize

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

func (*TransactionEssence) MarshalJSON

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

func (*TransactionEssence) Serialize

func (u *TransactionEssence) Serialize(deSeriMode serializer.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()

SortInputsOutputs 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

TransactionEssenceType 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 serializer.DeSerializationMode) (int, error)

func (*TreasuryInput) MarshalJSON

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

func (*TreasuryInput) Serialize

func (ti *TreasuryInput) Serialize(deSeriMode serializer.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 serializer.DeSerializationMode) (int, error)

func (*TreasuryOutput) MarshalJSON

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

func (*TreasuryOutput) Serialize

func (t *TreasuryOutput) Serialize(deSeriMode serializer.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 serializer.Serializable `json:"input"`
	// The output of this transaction.
	Output serializer.Serializable `json:"output"`
}

TreasuryTransaction represents a transaction which moves funds from the treasury.

func (*TreasuryTransaction) Deserialize

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

func (*TreasuryTransaction) MarshalJSON

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

func (*TreasuryTransaction) Serialize

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

func (*TreasuryTransaction) UnmarshalJSON

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

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 serializer.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 serializer.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

UnlockBlockType defines a type of unlock block.

type UnlockBlockValidatorFunc

type UnlockBlockValidatorFunc func(index int, unlockBlock serializer.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

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.
x
Package iotagox provides experimental APIs which are not stable.
Package iotagox provides experimental APIs which are not stable.

Jump to

Keyboard shortcuts

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