Back to godoc.org
github.com/onflow/flow-go-sdk

Package flow

v0.11.0
Latest Go to latest

The latest major version is .

Published: Oct 5, 2020 | License: Apache-2.0 | Module: github.com/onflow/flow-go-sdk

Overview

Package flow provides libraries and tools for building Go applications on Flow.

Index

Examples

Constants

const (
	EventAccountCreated string = "flow.AccountCreated"
	EventAccountUpdated string = "flow.AccountUpdated"
)

List of built-in account event types.

const AccountKeyWeightThreshold int = 1000

AccountKeyWeightThreshold is the total key weight required to authorize access to an account.

const AddressLength = (linearCodeN + 7) >> 3

AddressLength is the size of an account address in bytes.

Variables

var EmptyAddress = Address{}

EmptyAddress is the empty address (0x0000000000000000).

var EmptyID = Identifier{}

EmptyID is the empty identifier.

var TransactionDomainTag = paddedDomainTag("FLOW-V0.0-transaction")

TransactionDomainTag is the prefix of all signed transaction payloads.

A domain tag is encoded as UTF-8 bytes, right padded to a total length of 32 bytes.

var UserDomainTag = paddedDomainTag("FLOW-V0.0-user")

UserDomainTag is the prefix of all signed user space payloads.

A domain tag is encoded as UTF-8 bytes, right padded to a total length of 32 bytes.

func SignUserMessage

func SignUserMessage(signer crypto.Signer, message []byte) ([]byte, error)

SignUserMessage signs a message in the user domain.

User messages are distinct from other signed messages (i.e. transactions), and can be verified directly in on-chain Cadence code.

type Account

type Account struct {
	Address Address
	Balance uint64
	Code    []byte
	Keys    []*AccountKey
}

An Account is an account on the Flow network.

type AccountCreatedEvent

type AccountCreatedEvent Event

An AccountCreatedEvent is emitted when a transaction creates a new Flow account.

This event contains the following fields: - Address: Address

func (AccountCreatedEvent) Address

func (evt AccountCreatedEvent) Address() Address

Address returns the address of the newly-created account.

type AccountKey

type AccountKey struct {
	Index          int
	PublicKey      crypto.PublicKey
	SigAlgo        crypto.SignatureAlgorithm
	HashAlgo       crypto.HashAlgorithm
	Weight         int
	SequenceNumber uint64
	Revoked        bool
}

An AccountKey is a public key associated with an account.

func DecodeAccountKey

func DecodeAccountKey(b []byte) (*AccountKey, error)

DecodeAccountKey decodes the RLP byte representation of an account key.

func NewAccountKey

func NewAccountKey() *AccountKey

NewAccountKey returns an empty account key.

func (AccountKey) Encode

func (a AccountKey) Encode() []byte

Encode returns the canonical RLP byte representation of this account key.

func (*AccountKey) FromPrivateKey

func (a *AccountKey) FromPrivateKey(privKey crypto.PrivateKey) *AccountKey

FromPrivateKey sets the public key and signature algorithm based on the provided private key.

func (*AccountKey) SetHashAlgo

func (a *AccountKey) SetHashAlgo(hashAlgo crypto.HashAlgorithm) *AccountKey

SetHashAlgo sets the hash algorithm for this account key.

func (*AccountKey) SetPublicKey

func (a *AccountKey) SetPublicKey(pubKey crypto.PublicKey) *AccountKey

SetPublicKey sets the public key for this account key.

func (*AccountKey) SetSigAlgo

func (a *AccountKey) SetSigAlgo(sigAlgo crypto.SignatureAlgorithm) *AccountKey

SetSigAlgo sets the signature algorithm for this account key.

func (*AccountKey) SetWeight

func (a *AccountKey) SetWeight(weight int) *AccountKey

SetWeight sets the weight for this account key.

func (AccountKey) Validate

func (a AccountKey) Validate() error

Validate returns an error if this account key is invalid.

An account key can be invalid for the following reasons: - It specifies an incompatible signature/hash algorithm pairing - (TODO) It specifies a negative key weight

type Address

type Address [AddressLength]byte

Address represents the 8 byte address of an account.

func BytesToAddress

func BytesToAddress(b []byte) Address

BytesToAddress returns Address with value b.

If b is larger than 8, b will be cropped from the left. If b is smaller than 8, b will be appended by zeroes at the front.

func HexToAddress

func HexToAddress(h string) Address

HexToAddress converts a hex string to an Address.

func ServiceAddress

func ServiceAddress(chain ChainID) Address

ServiceAddress is the first generated account address.

func (Address) Bytes

func (a Address) Bytes() []byte

Bytes returns the byte representation of the address.

func (Address) Hex

func (a Address) Hex() string

Hex returns the hex string representation of the address.

func (*Address) IsValid

func (a *Address) IsValid(chain ChainID) bool

IsValid returns true if a given address is a valid account address, and false otherwise.

This is an off-chain check that only tells whether the address format is valid. If the function returns true, this does not mean a Flow account with this address has been generated. Such a test would require an on-chain check.

func (Address) MarshalJSON

func (a Address) MarshalJSON() ([]byte, error)

func (Address) String

func (a Address) String() string

String returns the string representation of the address.

func (*Address) UnmarshalJSON

func (a *Address) UnmarshalJSON(data []byte) error

type AddressGenerator

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

An AddressGenerator uses a deterministic algorithm to generate Flow addresses.

func NewAddressGenerator

func NewAddressGenerator(chainID ChainID) *AddressGenerator

NewAddressGenerator creates a new address generator for the given chain ID, starting from the zero address state.

Addresses are generated for a specific network (Flow mainnet, testnet, etc).

Each addressing state is mapped to exactly one address, meaning there are as many addresses as states. State values are incremented from 0 to 2^k-1.

func (*AddressGenerator) Address

func (gen *AddressGenerator) Address() Address

Address generates an account address at the current addressing state.

func (*AddressGenerator) Next

func (gen *AddressGenerator) Next() *AddressGenerator

Next increments the addressing state.

State values are incremented from 0 to 2^k-1.

func (*AddressGenerator) NextAddress

func (gen *AddressGenerator) NextAddress() Address

NextAddress increments the addressing state and generates an account address.

func (*AddressGenerator) SetIndex

func (gen *AddressGenerator) SetIndex(i uint) *AddressGenerator

SetIndex fast-forwards or rewinds the addressing state to the given index.

type Block

type Block struct {
	BlockHeader
	BlockPayload
}

Block is a set of state mutations applied to the Flow blockchain.

type BlockHeader

type BlockHeader struct {
	ID        Identifier
	ParentID  Identifier
	Height    uint64
	Timestamp time.Time
}

BlockHeader is a summary of a full block.

type BlockPayload

type BlockPayload struct {
	CollectionGuarantees []*CollectionGuarantee
	Seals                []*BlockSeal
}

BlockPayload is the full contents of a block.

A payload contains the collection guarantees and seals for a block.

type BlockSeal

type BlockSeal struct{}

TODO: define block seal struct

type ChainID

type ChainID string

A ChainID is a unique identifier for a specific Flow network instance.

Chain IDs are used used to prevent replay attacks and to support network-specific address generation.

const Emulator ChainID = "flow-emulator"

Emulator is the chain ID for the emulated node chain.

const Mainnet ChainID = "flow-mainnet"

Mainnet is the chain ID for the mainnet node chain.

const Testnet ChainID = "flow-testnet"

Testnet is the chain ID for the testnet node chain.

func (ChainID) String

func (id ChainID) String() string

type Collection

type Collection struct {
	TransactionIDs []Identifier
}

A Collection is a list of transactions bundled together for inclusion in a block.

func (Collection) Encode

func (c Collection) Encode() []byte

Encode returns the canonical RLP byte representation of this collection.

func (Collection) ID

func (c Collection) ID() Identifier

ID returns the canonical SHA3-256 hash of this collection.

type CollectionGuarantee

type CollectionGuarantee struct {
	CollectionID Identifier
}

A CollectionGuarantee is an attestation signed by the nodes that have guaranteed a collection.

type Event

type Event struct {
	// Type is the qualified event type.
	Type string
	// TransactionID is the ID of the transaction this event was emitted from.
	TransactionID Identifier
	// TransactionIndex is the index of the transaction this event was emitted from, within its containing block.
	TransactionIndex int
	// EventIndex is the index of the event within the transaction it was emitted from.
	EventIndex int
	// Value contains the event data.
	Value cadence.Event
}

func (Event) Encode

func (e Event) Encode() []byte

Encode returns the canonical RLP byte representation of this event.

func (Event) ID

func (e Event) ID() string

ID returns the canonical SHA3-256 hash of this event.

func (Event) String

func (e Event) String() string

String returns the string representation of this event.

type Identifier

type Identifier [32]byte

An Identifier is a 32-byte unique identifier for an entity.

func BytesToID

func BytesToID(b []byte) Identifier

BytesToID constructs an identifier from a byte slice.

func HashToID

func HashToID(hash []byte) Identifier

HashToID constructs an identifier from a 32-byte hash.

func HexToID

func HexToID(h string) Identifier

HexToID constructs an identifier from a hexadecimal string.

func (Identifier) Bytes

func (i Identifier) Bytes() []byte

Bytes returns the bytes representation of this identifier.

func (Identifier) Hex

func (i Identifier) Hex() string

Hex returns the hexadecimal string representation of this identifier.

func (Identifier) String

func (i Identifier) String() string

String returns the string representation of this identifier.

type ProposalKey

type ProposalKey struct {
	Address        Address
	KeyIndex       int
	SequenceNumber uint64
}

A ProposalKey is the key that specifies the proposal key and sequence number for a transaction.

type Transaction

type Transaction struct {
	// Script is the UTF-8 encoded Cadence source code that defines the execution logic for this transaction.
	Script []byte

	// Arguments is a list of Cadence values passed into this transaction.
	//
	// Each argument is encoded as JSON-CDC bytes.
	Arguments [][]byte

	// ReferenceBlockID is a reference to the block used to calculate the expiry of this transaction.
	//
	// A transaction is considered expired if it is submitted to Flow after refBlock + N, where N
	// is a constant defined by the network.
	//
	// For example, if a transaction references a block with height of X and the network limit is 10,
	// a block with height X+10 is the last block that is allowed to include this transaction.
	ReferenceBlockID Identifier

	// GasLimit is the maximum number of computational units that can be used to execute this transaction.
	GasLimit uint64

	// ProposalKey is the account key used to propose this transaction.
	//
	// A proposal key references a specific key on an account, along with an up-to-date
	// sequence number for that key. This sequence number is used to prevent replay attacks.
	//
	// You can find more information about sequence numbers here: https://docs.onflow.org/concepts/transaction-signing/#sequence-numbers
	ProposalKey ProposalKey

	// Payer is the account that pays the fee for this transaction.
	//
	// You can find more information about the payer role here: https://docs.onflow.org/concepts/transaction-signing/#signer-roles
	Payer Address

	// Authorizers is a list of the accounts that are authorizing this transaction to
	// mutate to their on-chain account state.
	//
	// You can find more information about the authorizer role here: https://docs.onflow.org/concepts/transaction-signing/#signer-roles
	Authorizers []Address

	// PayloadSignatures is a list of signatures generated by the proposer and authorizer roles.
	//
	// A payload signature is generated over the inner portion of the transaction (payload).
	//
	// You can find more information about transaction signatures here: https://docs.onflow.org/concepts/transaction-signing/#anatomy-of-a-transaction
	PayloadSignatures []TransactionSignature

	// EnvelopeSignatures is a list of signatures generated by the payer role.
	//
	// A payload signature is generated over the outer portion of the transaction (payload + payloadSignatures).
	//
	// You can find more information about transaction signatures here: https://docs.onflow.org/concepts/transaction-signing/#anatomy-of-a-transaction
	EnvelopeSignatures []TransactionSignature
}

A Transaction is a full transaction object containing a payload and signatures.

Example

Code:

addresses := test.AddressGenerator()

// Mock user accounts

adrianLaptopKey := &flow.AccountKey{
	Index:          3,
	SequenceNumber: 42,
}

adrianPhoneKey := &flow.AccountKey{Index: 2}
addressA := addresses.New()

adrian := flow.Account{
	Address: addressA,
	Keys: []*flow.AccountKey{
		adrianLaptopKey,
		adrianPhoneKey,
	},
}

blaineHardwareKey := &flow.AccountKey{Index: 7}
addressB := addresses.New()

blaine := flow.Account{
	Address: addressB,
	Keys: []*flow.AccountKey{
		blaineHardwareKey,
	},
}

// Transaction preparation

tx := flow.NewTransaction().
	SetScript([]byte(`transaction { execute { log("Hello, World!") } }`)).
	SetReferenceBlockID(flow.Identifier{0x01, 0x02}).
	SetGasLimit(42).
	SetProposalKey(adrian.Address, adrianLaptopKey.Index, adrianLaptopKey.SequenceNumber).
	SetPayer(blaine.Address).
	AddAuthorizer(adrian.Address)

fmt.Printf("Transaction ID (before signing): %s\n\n", tx.ID())

// Signing

err := tx.SignPayload(adrian.Address, adrianLaptopKey.Index, test.MockSigner([]byte{1}))
if err != nil {
	panic(err)
}

err = tx.SignPayload(adrian.Address, adrianPhoneKey.Index, test.MockSigner([]byte{2}))
if err != nil {
	panic(err)
}

err = tx.SignEnvelope(blaine.Address, blaineHardwareKey.Index, test.MockSigner([]byte{3}))
if err != nil {
	panic(err)
}

fmt.Println("Payload signatures:")
for _, sig := range tx.PayloadSignatures {
	fmt.Printf(
		"Address: %s, Key Index: %d, Signature: %x\n",
		sig.Address,
		sig.KeyIndex,
		sig.Signature,
	)
}
fmt.Println()

fmt.Println("Envelope signatures:")
for _, sig := range tx.EnvelopeSignatures {
	fmt.Printf(
		"Address: %s, Key Index: %d, Signature: %x\n",
		sig.Address,
		sig.KeyIndex,
		sig.Signature,
	)
}
fmt.Println()

fmt.Printf("Transaction ID (after signing): %s\n", tx.ID())
Transaction ID (before signing): 8c362dd8b7553d48284cecc94d2ab545d513b29f930555632390fff5ca9772ee

Payload signatures:
Address: f8d6e0586b0a20c7, Key Index: 2, Signature: 02
Address: f8d6e0586b0a20c7, Key Index: 3, Signature: 01

Envelope signatures:
Address: ee82856bf20e2aa6, Key Index: 7, Signature: 03

Transaction ID (after signing): d1a2c58aebfce1050a32edf3568ec3b69cb8637ae090b5f7444ca6b2a8de8f8b

func NewTransaction

func NewTransaction() *Transaction

NewTransaction initializes and returns an empty transaction.

func (*Transaction) AddArgument

func (t *Transaction) AddArgument(arg cadence.Value) error

AddArgument adds a Cadence argument to this transaction.

func (*Transaction) AddAuthorizer

func (t *Transaction) AddAuthorizer(address Address) *Transaction

AddAuthorizer adds an authorizer account to this transaction.

func (*Transaction) AddEnvelopeSignature

func (t *Transaction) AddEnvelopeSignature(address Address, keyIndex int, sig []byte) *Transaction

AddEnvelopeSignature adds an envelope signature to the transaction for the given address and key index.

func (*Transaction) AddPayloadSignature

func (t *Transaction) AddPayloadSignature(address Address, keyIndex int, sig []byte) *Transaction

AddPayloadSignature adds a payload signature to the transaction for the given address and key index.

func (*Transaction) AddRawArgument

func (t *Transaction) AddRawArgument(arg []byte) *Transaction

AddRawArgument adds a raw JSON-CDC encoded argument to this transaction.

func (*Transaction) Argument

func (t *Transaction) Argument(i int) (cadence.Value, error)

Argument returns the decoded argument at the given index.

func (*Transaction) Encode

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

Encode serializes the full transaction data including the payload and all signatures.

func (*Transaction) EnvelopeMessage

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

EnvelopeMessage returns the signable message for the transaction envelope.

This message is only signed by the payer account.

func (*Transaction) ID

func (t *Transaction) ID() Identifier

ID returns the canonical SHA3-256 hash of this transaction.

func (*Transaction) PayloadMessage

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

func (*Transaction) SetGasLimit

func (t *Transaction) SetGasLimit(limit uint64) *Transaction

SetGasLimit sets the gas limit for this transaction.

func (*Transaction) SetPayer

func (t *Transaction) SetPayer(address Address) *Transaction

SetPayer sets the payer account for this transaction.

func (*Transaction) SetProposalKey

func (t *Transaction) SetProposalKey(address Address, keyIndex int, sequenceNum uint64) *Transaction

SetProposalKey sets the proposal key and sequence number for this transaction.

The first two arguments specify the account key to be used, and the last argument is the sequence number being declared.

func (*Transaction) SetReferenceBlockID

func (t *Transaction) SetReferenceBlockID(blockID Identifier) *Transaction

SetReferenceBlockID sets the reference block ID for this transaction.

A transaction is considered expired if it is submitted to Flow after refBlock + N, where N is a constant defined by the network.

For example, if a transaction references a block with height of X and the network limit is 10, a block with height X+10 is the last block that is allowed to include this transaction.

func (*Transaction) SetScript

func (t *Transaction) SetScript(script []byte) *Transaction

SetScript sets the Cadence script for this transaction.

The script is the UTF-8 encoded Cadence source code.

func (*Transaction) SignEnvelope

func (t *Transaction) SignEnvelope(address Address, keyIndex int, signer crypto.Signer) error

SignEnvelope signs the full transaction (payload + payload signatures) with the specified account key.

The resulting signature is combined with the account address and key index before being added to the transaction.

This function returns an error if the signature cannot be generated.

func (*Transaction) SignPayload

func (t *Transaction) SignPayload(address Address, keyIndex int, signer crypto.Signer) error

SignPayload signs the transaction payload with the specified account key.

The resulting signature is combined with the account address and key index before being added to the transaction.

This function returns an error if the signature cannot be generated.

type TransactionResult

type TransactionResult struct {
	Status TransactionStatus
	Error  error
	Events []Event
}

type TransactionSignature

type TransactionSignature struct {
	Address     Address
	SignerIndex int
	KeyIndex    int
	Signature   []byte
}

A TransactionSignature is a signature associated with a specific account key.

type TransactionStatus

type TransactionStatus int

TransactionStatus represents the status of a transaction.

const (
	// TransactionStatusUnknown indicates that the transaction status is not known.
	TransactionStatusUnknown TransactionStatus = iota
	// TransactionStatusPending is the status of a pending transaction.
	TransactionStatusPending
	// TransactionStatusFinalized is the status of a finalized transaction.
	TransactionStatusFinalized
	// TransactionStatusExecuted is the status of an executed transaction.
	TransactionStatusExecuted
	// TransactionStatusSealed is the status of a sealed transaction.
	TransactionStatusSealed
	// TransactionStatusExpired is the status of an expired transaction.
	TransactionStatusExpired
)

func (TransactionStatus) String

func (s TransactionStatus) String() string

String returns the string representation of a transaction status.

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier