stc

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2022 License: Apache-2.0, GPL-3.0-or-later Imports: 26 Imported by: 1

README

Stellar transaction compiler

stc is a library and command-line tool for creating, editing, and manipulating transactions for the Stellar blockchain. It supports translating back and forth between human-readable txrep format and Stellar's native binary XDR representation, as well submitting transactions to the network, querying account status, and more. The library makes it easy to build and submit transactions programmatically from go applications.

Installing stc for non-developers

To install or upgrade this software if you don't plan to hack on it, run the following:

GOPROXY=direct go install github.com/xdrpp/stc/...@latest

The GOPROXY environment variable requests the latest version of the software from github, instead of calling home to Google's module proxy and allowing Google to supply an incorrect or stale version of the software (which unfortunately happened to the author).

Once this command completes, put the ~/go/bin directory on your path and you should be able to run stc.

For most purposes you can simply depend on the latest release. However, if you wish to install the latest development version from within a go module (a directory with a go.mod file), you will need to specify the go1 branch to get autogenerated files that are not available on the master branch. Do so by running:

rm -rf ~/go/src/github.com/xdrpp/stc
GOPROXY=direct go get github.com/xdrpp/stc/...@go1

Assuming your GOPATH is in the default location of ~/go, the rm command is necessary when upgrading because some go get limitation leaves your tree in a detached state, so that go get -u cannot pull from the remote go1 branch.

Using stc

See the stc(1) man page for the command-line tool. There's also a video of a presentation and demo of stc at the 2020 Stellar Meridian conference.

See the godoc documentation for the library. Because stc contains auto-generated source files that are not on the master branch in git, you may wish to view the documentation locally, rather than through on-line godoc viewers that may not show you the correct branch. To view godoc, after installing stc with go get as described above, start a local godoc server and open it in your browser as follows:

godoc -index -http localhost:6060 &
xdg-open http://localhost:6060/pkg/github.com/xdrpp/stc

On MacOS computers, run open instead of xdg-open, or just paste the URL into your browser.

Building stc for developers

Because stc requires autogenerated files, the master branch is not meant to be compiled under $GOPATH, but rather in a standalone directory with make.

Furthermore, to build stc from the master branch, you also need to have the goxdr compiler. Because stc is codeveloped with goxdr, you may want to use a development version of goxdr, which you can do by placing a the goxdr source tree (or a symbolic link to it) in cmd/goxdr. If you don't want to do this, but are okay just using a snapshot of goxdr, you can run:

make depend

Once you have goxdr, you can build stc by running:

make

To install stc, you will also need pandoc to format the man page.

Building stc for experimental protocol versions

To build a version of stc supporting changes to the transaction format that have not yet been merged into stellar-core, you can fetch alternate XDR files with either of the commands:

./make-xdr BRANCH

./make-xdr REPO BRANCH

Here REPO is the git repository from which to pull the non-standard version of stellar-core (default https://github.com/stellar/stellar-core.git), and BRANCH is either a branch name in the remote repository or a github pull request number. To revert to the standard XDR, simply run ./make-xdr with no arguments.

Disclaimer

There is no warranty for the program, to the extent permitted by applicable law. Except when otherwise stated in writing the copyright holders and/or other parties provide the program "as is" without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of the program is with you. Should the program prove defective, you assume the cost of all necessary servicing, repair or correction.

In no event unless required by applicable law or agreed to in writing will any copyright holder, or any other party who modifies and/or conveys the program as permitted above, be liable to you for damages, including any general, special, incidental or consequential damages arising out of the use or inability to use the program (including but not limited to loss of data or data being rendered inaccurate or losses sustained by you or third parties or a failure of the program to operate with any other programs), even if such holder or other party has been advised of the possibility of such damages.

Documentation

Overview

Stellar transaction compiler library. Provides functions for manipulating Stellar transactions, translating them back and forth between txrep format, and posting them.

Example (PostTransaction)
var mykey PrivateKey
fmt.Sscan("SDWHLWL24OTENLATXABXY5RXBG6QFPLQU7VMKFH4RZ7EWZD2B7YRAYFS",
	&mykey)

var yourkey PublicKey
fmt.Sscan("GATPALHEEUERWYW275QDBNBMCM4KEHYJU34OPIZ6LKJAXK6B4IJ73V4L",
	&yourkey)

// Fetch account entry to get sequence number
myacct, err := DefaultStellarNet("test").GetAccountEntry(
	mykey.Public().String())
if err != nil {
	panic(err)
}

// Build a transaction
txe := NewTransactionEnvelope()
txe.SetSourceAccount(mykey.Public())
txe.V1().Tx.SeqNum = myacct.NextSeq()
txe.V1().Tx.Memo = MemoText("Hello")
txe.Append(nil, SetOptions{
	SetFlags:      NewUint(uint32(stx.AUTH_REQUIRED_FLAG)),
	LowThreshold:  NewUint(2),
	MedThreshold:  NewUint(2),
	HighThreshold: NewUint(2),
	Signer:        NewSignerKey(yourkey, 1),
})

net := DefaultStellarNet("test")

// Pay the median per-operation fee of recent ledgers
fees, err := net.GetFeeStats()
if err != nil {
	panic(err)
}
txe.SetFee(fees.Percentile(50))

// Sign and post the transaction
net.SignTx(&mykey, txe)
result, err := net.Post(txe)
if err != nil {
	panic(err)
}

fmt.Println(result)
Output:

Example (Txrep)
var mykey PrivateKey
fmt.Sscan("SDWHLWL24OTENLATXABXY5RXBG6QFPLQU7VMKFH4RZ7EWZD2B7YRAYFS",
	&mykey)

var yourkey PublicKey
fmt.Sscan("GATPALHEEUERWYW275QDBNBMCM4KEHYJU34OPIZ6LKJAXK6B4IJ73V4L",
	&yourkey)

// Build a transaction
txe := NewTransactionEnvelope()
txe.SetSourceAccount(mykey.Public())
txe.V1().Tx.SeqNum = 3319833626148865
txe.V1().Tx.Memo = MemoText("Hello")
txe.Append(nil, Payment{
	Destination: *yourkey.ToMuxedAccount(),
	Asset:       NativeAsset(),
	Amount:      20000000,
})
// ... Can keep appending operations with txe.Append
txe.SetFee(100)

net := DefaultStellarNet("main")
// Sign the transaction
net.SignTx(&mykey, txe)

// Print the transaction in multi-line human-readable "txrep" form
fmt.Print(net.TxToRep(txe))
Output:

type: ENVELOPE_TYPE_TX
tx.sourceAccount: GDFR4HZMNZCNHFEIBWDQCC4JZVFQUGXUQ473EJ4SUPFOJ3XBG5DUCS2G
tx.fee: 100
tx.seqNum: 3319833626148865
tx.cond.type: PRECOND_NONE
tx.memo.type: MEMO_TEXT
tx.memo.text: "Hello"
tx.operations.len: 1
tx.operations[0].sourceAccount._present: false
tx.operations[0].body.type: PAYMENT
tx.operations[0].body.paymentOp.destination: GATPALHEEUERWYW275QDBNBMCM4KEHYJU34OPIZ6LKJAXK6B4IJ73V4L
tx.operations[0].body.paymentOp.asset: XLM
tx.operations[0].body.paymentOp.amount: 20000000 (2e7)
tx.ext.v: 0
signatures.len: 1
signatures[0].hint: e1374741 (bad signature/unknown key/main is wrong network)
signatures[0].signature: 3bf96c29ab95730775612b5a9a0ec630d779846ab31b2e07de8d24de927961f8667604091a3942e756e0dc14dd94465e2b6132880481e403055ec33905429502

Index

Examples

Constants

View Source
const MaxInt64 = 0x7fffffffffffffff

Largest 64-bit signed integer (9223372036854775807).

Variables

View Source
var DefaultGlobalConfigContents = []byte(
	`# Default Stellar network configurations for stc.

[net "main"]
network-id = "Public Global Stellar Network ; September 2015"
horizon = https://horizon.stellar.org/
native-asset = XLM

[net "test"]
horizon = https://horizon-testnet.stellar.org/
native-asset = TestXLM

[net "standalone"]
network-id = "Standalone Network ; February 2017"
horizon = http://localhost:8000/
native-asset = StandaloneXLM

`)

When a user does not have an stc.conf configuration file, the library searches for one in $STCDIR/stc.conf, then /etc/stc.conf, then ../share/stc.conf (relative to the executable path). If none of those paths exists, then it uses the built-in contents specified by this variable.

View Source
var ErrInvalidNetName = errors.New("Invalid or missing Stellar network name")
View Source
var ErrNoNetworkId = errors.New("Cannot obtain Stellar network-id")
View Source
var InvalidKeyFile = errors.New("Invalid private key file")
View Source
var InvalidPassphrase = errors.New("Invalid passphrase")

Functions

func ConfigPath

func ConfigPath(components ...string) string

Return the path to a file under the user's configuration directory. The configuration directory is found based on environment variables. From highest to lowest precedence tries $STCDIR, UserConfigDir() (i.e., on Unix $XDG_CONFIG_HOME/.stc or $HOME/.config/stc), or ./.stc, using the first one with for which the environment variable exists. If the configuration directory doesn't exist, it gets created, but the underlying path requested will not be created.

func IsTemporary

func IsTemporary(err error) bool

Try to determine whether a request to Horizon indicates the operation is worth retrying. Specifically, this function repeatedly unwraps errors and returns true if either A) one of the errors has a Temporary() method that returns true, or B) one of the errors is a net.OpError for Op "dial" and that is not wrapping a DNS error. The logic here is that if the DNS name of a horizon server does not exist (permanent DNS error), there is likely some misconfiguration. However, if the horizon server is refusing TCP connections, it may be undergoing maintenance.

func MemoHash

func MemoHash(arg [32]uint8) (ret stx.Memo)

Helper function for initializing a Memo with Type == MEMO_HASH

func MemoId

func MemoId(arg uint64) (ret stx.Memo)

Helper function for initializing a Memo with Type == MEMO_ID

func MemoNone

func MemoNone() stx.Memo

Helper function for initializing a Memo with Type == MEMO_NONE

func MemoReturn

func MemoReturn(arg [32]uint8) (ret stx.Memo)

Helper function for initializing a Memo with Type == MEMO_RETURN

func MemoText

func MemoText(arg string) (ret stx.Memo)

Helper function for initializing a Memo with Type == MEMO_TEXT

func MkAsset

func MkAsset(acc AccountID, code string) stx.Asset

func MkAssetCode added in v0.1.3

func MkAssetCode(code string) stx.AssetCode

func NativeAsset

func NativeAsset() stx.Asset

func NewHyper

func NewHyper(v int64) *int64

Allocate an int64 when initializing types that take an XDR hyper*.

func NewSignerHashX

func NewSignerHashX(x stx.Hash, weight uint32) *stx.Signer

Create a signer that requires the hash pre-image of some hash value x

func NewSignerKey

func NewSignerKey(pk PublicKey, weight uint32) *stx.Signer

Create a signer for a particular public key and weight

func NewString

func NewString(v string) *string

Allocate a string when initializing types that take an XDR *string<>.

func NewUhyper

func NewUhyper(v uint64) *uint64

Allocate a uint64 when initializing types that take an XDR unsigned hyper*.

func NewUint

func NewUint(v uint32) *uint32

Allocate a uint32 when initializing types that take an XDR int*.

func ParseConfigFiles

func ParseConfigFiles(sink ini.IniSink, paths ...string) error

Parse a series of INI configuration files specified by paths, followed by the global or built-in stc.conf file.

func Set

func Set(t xdr.XdrType, fieldValues ...interface{})

Assign a set of values to successive fields of an XDR structure in a type-safe way, flattening out nested structures. For example, given the following XDR:

union Asset switch (AssetType type) {
case ASSET_TYPE_NATIVE: // Not credit
	void;

case ASSET_TYPE_CREDIT_ALPHANUM4:
	struct {
		opaque assetCode[4]; // 1 to 4 characters
		AccountID issuer;
	} alphaNum4;

case ASSET_TYPE_CREDIT_ALPHANUM12:
	struct {
		opaque assetCode[12]; // 5 to 12 characters
		AccountID issuer;
	} alphaNum12;
};

You can initalize it with the following:

var asset Asset
Set(&asset, ASSET_TYPE_CREDIT_ALPHANUM12, "Asset Code", AccountID{})

Fixed-length arrays of size n must be assigned from n successive arguments passed to Set and cannot be passed as an array. Slices, by contrast, must be assigned from slices. The one exception is fixed-size array of bytes opaque[n], which can be initialized from a string, a slice []byte, or an array [n]byte. The string or slice may be shorter than n (in which case the remainig bytes are filled with 0), but a byte array must be exactly the same length. (If you really must assign from a shorter fixed-length byte array, just slice the array.)

Note that aggregates can be passed as arguments to assign, in which case Set will take fewer arguments. The recursive traversal of structures stops when it is possible to assign the next value to the current aggregate. For example, it is valid to say:

var asset Asset
Set(&asset, ASSET_TYPE_CREDIT_ALPHANUM12, otherAsset.AlphaNum12)

func TxToBase64

func TxToBase64(tx *TransactionEnvelope) string

Convert a TransactionEnvelope to base64-encoded binary XDR format.

func ValidNetName

func ValidNetName(name string) bool

Types

type AccountHints

type AccountHints map[string]string

Set of annotations to show as comments when showing Stellar AccountID values.

func (AccountHints) String

func (h AccountHints) String() string

Renders an account hint as the AccountID in StrKey format, a space, and the comment (if any).

type AccountID

type AccountID = stx.AccountID

func DemuxAcct

func DemuxAcct(macct *MuxedAccount) (*AccountID, *uint64)

Break a MuxedAccount into its consituent parts. Note that the second return value of type *uint64 may be nil for MuxedAccounts that don't include an embedded identifier.

func NewAccountID

func NewAccountID(id AccountID) *AccountID

Return a pointer to an account ID

type AccountMerge

type AccountMerge stx.MuxedAccount

AccountMerge is a type with the same fields as stx.MuxedAccount that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == ACCOUNT_MERGE and *Body.Destination() initialized from the fields of the AccountMerge.

func (AccountMerge) To_Operation_Body

func (arg AccountMerge) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type AllowTrust

type AllowTrust stx.AllowTrustOp

AllowTrust is a type with the same fields as stx.AllowTrustOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == ALLOW_TRUST and *Body.AllowTrustOp() initialized from the fields of the AllowTrust.

func (AllowTrust) To_Operation_Body

func (arg AllowTrust) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type BeginSponsoringFutureReserves

type BeginSponsoringFutureReserves stx.BeginSponsoringFutureReservesOp

BeginSponsoringFutureReserves is a type with the same fields as stx.BeginSponsoringFutureReservesOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == BEGIN_SPONSORING_FUTURE_RESERVES and *Body.BeginSponsoringFutureReservesOp() initialized from the fields of the BeginSponsoringFutureReserves.

func (BeginSponsoringFutureReserves) To_Operation_Body

func (arg BeginSponsoringFutureReserves) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type BumpSequence

type BumpSequence stx.BumpSequenceOp

BumpSequence is a type with the same fields as stx.BumpSequenceOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == BUMP_SEQUENCE and *Body.BumpSequenceOp() initialized from the fields of the BumpSequence.

func (BumpSequence) To_Operation_Body

func (arg BumpSequence) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type ChangeTrust

type ChangeTrust stx.ChangeTrustOp

ChangeTrust is a type with the same fields as stx.ChangeTrustOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == CHANGE_TRUST and *Body.ChangeTrustOp() initialized from the fields of the ChangeTrust.

func (ChangeTrust) To_Operation_Body

func (arg ChangeTrust) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type ClaimClaimableBalance

type ClaimClaimableBalance stx.ClaimClaimableBalanceOp

ClaimClaimableBalance is a type with the same fields as stx.ClaimClaimableBalanceOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == CLAIM_CLAIMABLE_BALANCE and *Body.ClaimClaimableBalanceOp() initialized from the fields of the ClaimClaimableBalance.

func (ClaimClaimableBalance) To_Operation_Body

func (arg ClaimClaimableBalance) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type Clawback added in v0.1.3

type Clawback stx.ClawbackOp

Clawback is a type with the same fields as stx.ClawbackOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == CLAWBACK and *Body.ClawbackOp() initialized from the fields of the Clawback.

func (Clawback) To_Operation_Body added in v0.1.3

func (arg Clawback) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type ClawbackClaimableBalance added in v0.1.4

type ClawbackClaimableBalance stx.ClawbackClaimableBalanceOp

ClawbackClaimableBalance is a type with the same fields as stx.ClawbackClaimableBalanceOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == CLAWBACK_CLAIMABLE_BALANCE and *Body.ClawbackClaimableBalanceOp() initialized from the fields of the ClawbackClaimableBalance.

func (ClawbackClaimableBalance) To_Operation_Body added in v0.1.4

func (arg ClawbackClaimableBalance) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type CreateAccount

type CreateAccount stx.CreateAccountOp

CreateAccount is a type with the same fields as stx.CreateAccountOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == CREATE_ACCOUNT and *Body.CreateAccountOp() initialized from the fields of the CreateAccount.

func (CreateAccount) To_Operation_Body

func (arg CreateAccount) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type CreateClaimableBalance

type CreateClaimableBalance stx.CreateClaimableBalanceOp

CreateClaimableBalance is a type with the same fields as stx.CreateClaimableBalanceOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == CREATE_CLAIMABLE_BALANCE and *Body.CreateClaimableBalanceOp() initialized from the fields of the CreateClaimableBalance.

func (CreateClaimableBalance) To_Operation_Body

func (arg CreateClaimableBalance) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type CreatePassiveSellOffer

type CreatePassiveSellOffer stx.CreatePassiveSellOfferOp

CreatePassiveSellOffer is a type with the same fields as stx.CreatePassiveSellOfferOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == CREATE_PASSIVE_SELL_OFFER and *Body.CreatePassiveSellOfferOp() initialized from the fields of the CreatePassiveSellOffer.

func (CreatePassiveSellOffer) To_Operation_Body

func (arg CreatePassiveSellOffer) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type EndSponsoringFutureReserves

type EndSponsoringFutureReserves struct{}

EndSponsoringFutureReserves is an empty type that can be passed to TransactionEnvelope.Append() to append a new Operation with Body.Type == END_SPONSORING_FUTURE_RESERVES.

func (EndSponsoringFutureReserves) To_Operation_Body

func (EndSponsoringFutureReserves) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type ErrEventStream

type ErrEventStream string

func (ErrEventStream) Error

func (e ErrEventStream) Error() string

type FeeDist

type FeeDist struct {
	Max         FeeVal
	Min         FeeVal
	Mode        FeeVal
	Percentiles []FeePercentile
}

Distribution of offered or charged fees.

func (*FeeDist) Percentile

func (fd *FeeDist) Percentile(target int) FeeVal

Conservatively returns a fee that is a known fee for the target or the closest higher known percentile. Does not interpolate--e.g., if you ask for the 51st percentile but only the 50th and 60th are known, returns the 60th percentile. Never returns a value less than the base fee.

func (*FeeDist) UnmarshalJSON

func (fd *FeeDist) UnmarshalJSON(data []byte) error

type FeePercentile

type FeePercentile = struct {
	Percentile int
	Fee        FeeVal
}

type FeeStats

type FeeStats struct {
	Last_ledger           uint64
	Last_ledger_base_fee  uint32
	Ledger_capacity_usage float64
	Charged               FeeDist
	Offered               FeeDist
}

Go representation of the Horizon Fee Stats structure response. The fees are per operation in a transaction, and the individual fields are documented here: https://www.stellar.org/developers/horizon/reference/endpoints/fee-stats.html

func (*FeeStats) Percentile

func (fs *FeeStats) Percentile(target int) FeeVal

Conservatively a known offered fee for the target or a higher percentile. Never returns a value less than the base fee.

func (FeeStats) String

func (fs FeeStats) String() string

func (*FeeStats) UnmarshalJSON

func (fs *FeeStats) UnmarshalJSON(data []byte) error

type FeeVal

type FeeVal = uint32

A Fee Value is currently 32 bits, but could become 64 bits if CAP-0015 is adopted.

type HorizonAccountEntry

type HorizonAccountEntry struct {
	Net                   *StellarNet `json:"-"`
	Sequence              stcdetail.JsonInt64
	Balance               stcdetail.JsonInt64e7
	Subentry_count        uint32
	Inflation_destination *AccountID
	Home_domain           string
	Last_modified_ledger  uint32
	Flags                 HorizonFlags
	Thresholds            HorizonThresholds
	Balances              []HorizonBalance
	Signers               []HorizonSigner
	Data                  map[string]string
}

Structure into which you can unmarshal JSON returned by a query to horizon for an account endpoint

func (*HorizonAccountEntry) NextSeq

func (ae *HorizonAccountEntry) NextSeq() stx.SequenceNumber

Return the next sequence number (1 + Sequence) as an int64 (or 0 if an invalid sequence number was returned by horizon).

func (*HorizonAccountEntry) String

func (hs *HorizonAccountEntry) String() string

func (*HorizonAccountEntry) UnmarshalJSON

func (ae *HorizonAccountEntry) UnmarshalJSON(data []byte) error

type HorizonBalance

type HorizonBalance struct {
	Balance             stcdetail.JsonInt64e7
	Buying_liabilities  stcdetail.JsonInt64e7
	Selling_liabilities stcdetail.JsonInt64e7
	Limit               stcdetail.JsonInt64e7
	Asset               stx.Asset `json:"-"`
}

func (*HorizonBalance) UnmarshalJSON

func (hb *HorizonBalance) UnmarshalJSON(data []byte) error

type HorizonFlags

type HorizonFlags struct {
	Auth_required  bool
	Auth_revocable bool
	Auth_immutable bool
}

type HorizonSigner

type HorizonSigner struct {
	Key    SignerKey
	Weight uint32
}

type HorizonThresholds

type HorizonThresholds struct {
	Low_threshold  uint8
	Med_threshold  uint8
	High_threshold uint8
}

type HorizonTxResult

type HorizonTxResult struct {
	Net    *StellarNet
	Txhash stx.Hash
	Ledger uint32
	Time   time.Time
	Env    stx.TransactionEnvelope
	Result stx.TransactionResult
	StellarMetas
	PagingToken string
}

func (HorizonTxResult) String

func (r HorizonTxResult) String() string

func (*HorizonTxResult) Success

func (r *HorizonTxResult) Success() bool

func (*HorizonTxResult) UnmarshalJSON

func (r *HorizonTxResult) UnmarshalJSON(data []byte) error

type Inflation

type Inflation struct{}

Inflation is an empty type that can be passed to TransactionEnvelope.Append() to append a new Operation with Body.Type == INFLATION.

func (Inflation) To_Operation_Body

func (Inflation) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type LedgerHeader

type LedgerHeader = stx.LedgerHeader

type LiquidityPoolDeposit added in v0.1.6

type LiquidityPoolDeposit stx.LiquidityPoolDepositOp

LiquidityPoolDeposit is a type with the same fields as stx.LiquidityPoolDepositOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == LIQUIDITY_POOL_DEPOSIT and *Body.LiquidityPoolDepositOp() initialized from the fields of the LiquidityPoolDeposit.

func (LiquidityPoolDeposit) To_Operation_Body added in v0.1.6

func (arg LiquidityPoolDeposit) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type LiquidityPoolWithdraw added in v0.1.6

type LiquidityPoolWithdraw stx.LiquidityPoolWithdrawOp

LiquidityPoolWithdraw is a type with the same fields as stx.LiquidityPoolWithdrawOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == LIQUIDITY_POOL_WITHDRAW and *Body.LiquidityPoolWithdrawOp() initialized from the fields of the LiquidityPoolWithdraw.

func (LiquidityPoolWithdraw) To_Operation_Body added in v0.1.6

func (arg LiquidityPoolWithdraw) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type ManageBuyOffer

type ManageBuyOffer stx.ManageBuyOfferOp

ManageBuyOffer is a type with the same fields as stx.ManageBuyOfferOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == MANAGE_BUY_OFFER and *Body.ManageBuyOfferOp() initialized from the fields of the ManageBuyOffer.

func (ManageBuyOffer) To_Operation_Body

func (arg ManageBuyOffer) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type ManageData

type ManageData stx.ManageDataOp

ManageData is a type with the same fields as stx.ManageDataOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == MANAGE_DATA and *Body.ManageDataOp() initialized from the fields of the ManageData.

func (ManageData) To_Operation_Body

func (arg ManageData) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type ManageSellOffer

type ManageSellOffer stx.ManageSellOfferOp

ManageSellOffer is a type with the same fields as stx.ManageSellOfferOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == MANAGE_SELL_OFFER and *Body.ManageSellOfferOp() initialized from the fields of the ManageSellOffer.

func (ManageSellOffer) To_Operation_Body

func (arg ManageSellOffer) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type MuxedAccount

type MuxedAccount = stx.MuxedAccount

func MuxAcct

func MuxAcct(acct *AccountID, id *uint64) *MuxedAccount

Created a MuxedAccount from its consituent parts. id may be nil to indicate there is no embedded identifier.

type OperationBody

type OperationBody interface {
	To_Operation_Body() stx.XdrAnon_Operation_Body
}

Interface for placeholder types that are named by camel-cased versions of the OperationType enum and can be transformed into the body of an Operation

type PathPaymentStrictReceive

type PathPaymentStrictReceive stx.PathPaymentStrictReceiveOp

PathPaymentStrictReceive is a type with the same fields as stx.PathPaymentStrictReceiveOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == PATH_PAYMENT_STRICT_RECEIVE and *Body.PathPaymentStrictReceiveOp() initialized from the fields of the PathPaymentStrictReceive.

func (PathPaymentStrictReceive) To_Operation_Body

func (arg PathPaymentStrictReceive) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type PathPaymentStrictSend

type PathPaymentStrictSend stx.PathPaymentStrictSendOp

PathPaymentStrictSend is a type with the same fields as stx.PathPaymentStrictSendOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == PATH_PAYMENT_STRICT_SEND and *Body.PathPaymentStrictSendOp() initialized from the fields of the PathPaymentStrictSend.

func (PathPaymentStrictSend) To_Operation_Body

func (arg PathPaymentStrictSend) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type Payment

type Payment stx.PaymentOp

Payment is a type with the same fields as stx.PaymentOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == PAYMENT and *Body.PaymentOp() initialized from the fields of the Payment.

func (Payment) To_Operation_Body

func (arg Payment) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type PrivateKey

type PrivateKey struct {
	stcdetail.PrivateKeyInterface
}

Abstract type representing a Stellar private key. Prints and scans in StrKey format.

func InputPrivateKey

func InputPrivateKey(prompt string) (PrivateKey, error)

Reads a private key from standard input. If standard input is a terminal, disables echo and prints prompt to standard error.

func LoadPrivateKey

func LoadPrivateKey(file string) (PrivateKey, error)

Reads a private key from a file, prompting for a passphrase if the key is in ASCII-armored symmetrically-encrypted GPG format.

func NewPrivateKey

func NewPrivateKey(pkt stx.PublicKeyType) PrivateKey

Generates a new Stellar keypair and returns the PrivateKey. Currently the only valid value for pkt is stx.PUBLIC_KEY_TYPE_ED25519.

func (PrivateKey) Save

func (sk PrivateKey) Save(file string, passphrase []byte) error

Writes the a private key to a file in strkey format. If passphrase has non-zero length, then the key is symmetrically encrypted in ASCII-armored GPG format.

func (*PrivateKey) Scan

func (sec *PrivateKey) Scan(ss fmt.ScanState, _ rune) error

func (PrivateKey) Valid

func (sec PrivateKey) Valid() bool

type PublicKey

type PublicKey = stx.PublicKey

type RevokeSponsorship

type RevokeSponsorship stx.RevokeSponsorshipOp

RevokeSponsorship is a type with the same fields as stx.RevokeSponsorshipOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == REVOKE_SPONSORSHIP and *Body.RevokeSponsorshipOp() initialized from the fields of the RevokeSponsorship.

func (RevokeSponsorship) To_Operation_Body

func (arg RevokeSponsorship) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type SetOptions

type SetOptions stx.SetOptionsOp

SetOptions is a type with the same fields as stx.SetOptionsOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == SET_OPTIONS and *Body.SetOptionsOp() initialized from the fields of the SetOptions.

func (SetOptions) To_Operation_Body

func (arg SetOptions) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type SetTrustLineFlags added in v0.1.4

type SetTrustLineFlags stx.SetTrustLineFlagsOp

SetTrustLineFlags is a type with the same fields as stx.SetTrustLineFlagsOp that can be passed to TransactionEnvelope.Append() to append a new operation with Body.Type == SET_TRUST_LINE_FLAGS and *Body.SetTrustLineFlagsOp() initialized from the fields of the SetTrustLineFlags.

func (SetTrustLineFlags) To_Operation_Body added in v0.1.4

func (arg SetTrustLineFlags) To_Operation_Body() (ret stx.XdrAnon_Operation_Body)

type Signature

type Signature = stx.Signature

type SignerCache

type SignerCache map[stx.SignatureHint][]SignerKeyInfo

A SignerCache contains a set of possible Stellar signers. Because a TransactionEnvelope contains an array of signatures without public keys, it is not possible to verify the signatures without having the Signers. The signatures in a TransactionEnvelope envelope are, however, accompanied by a 4-byte SignatureHint, making it efficient to look up signers if they are in a SignerCache.

func (SignerCache) Add

func (c SignerCache) Add(strkey, comment string) error

Adds a signer to a SignerCache if the signer is not already in the cache. If the signer is already in the cache, the comment is left unchanged.

func (SignerCache) Del

func (c SignerCache) Del(strkey string) error

Deletes a signer from the cache.

func (SignerCache) Lookup

Finds the signer in a SignerCache that corresponds to a particular signature on a transaction.

func (SignerCache) LookupComment

func (c SignerCache) LookupComment(key *stx.SignerKey) string

func (SignerCache) String

func (c SignerCache) String() string

Renders SignerCache as a a set of SignerKeyInfo structures, one per line, suitable for saving to a file.

type SignerKey

type SignerKey = stx.SignerKey

type SignerKeyInfo

type SignerKeyInfo struct {
	Key     stx.SignerKey
	Comment string
}

An annotated SignerKey that can be used to authenticate transactions. Prints and Scans as a StrKey-format SignerKey, a space, and then the comment.

func (*SignerKeyInfo) Scan

func (ski *SignerKeyInfo) Scan(ss fmt.ScanState, c rune) error

func (SignerKeyInfo) String

func (ski SignerKeyInfo) String() string

type StellarMetas

type StellarMetas struct {
	FeeMeta    stx.LedgerEntryChanges
	ResultMeta stx.TransactionMeta
}

Ledger entries changed by a transaction.

type StellarNet

type StellarNet struct {
	// Short name for network (used only in error messages).
	Name string

	// Network password used for hashing and signing transactions.
	NetworkId string

	// Name to use for native asset
	NativeAsset string

	// Base URL of horizon (including trailing slash).
	Horizon string

	// Set of signers to recognize when checking signatures on
	// transactions and annotations to show when printing signers.
	Signers SignerCache

	// Annotations to show on particular accounts when rendering them
	// in human-readable txrep format.
	Accounts AccountHints

	// Changes will be saved to this file.
	SavePath string

	// Changes to be applied by Save().
	Edits ini.IniEdits

	// Cache of fee stats
	FeeCache     *FeeStats
	FeeCacheTime time.Time
}

func DefaultStellarNet

func DefaultStellarNet(name string) *StellarNet

Load a network from under the ConfigPath() ($STCDIR) directory. If name is "", then it will look at the $STCNET environment variable and if that is unset load a default network. Returns nil if the network name does not exist. After loading the netname.net file, also parses $STCDIR/global.conf.

Two pre-defined names are "main" and "test", with "main" being the default. Other networks can be created under ConfigPath(), or can be pre-specified (and created on demand) in stc.conf.

func LoadStellarNet

func LoadStellarNet(name string, paths ...string) (*StellarNet, error)

Load a Stellar network from an INI files. If path[0] does not exist but name is valid, the path will be created and net.name will be set to name. Otherwise the name argument is ignored. After all files in paths are parsed, the global stc.conf file will be parsed. After that, there must be a valid NetworkId or the function will return nil.

func (*StellarNet) AccountDelta

func (net *StellarNet) AccountDelta(
	m *StellarMetas, acct *AccountID, prefix string) string

func (*StellarNet) AccountIDNote

func (net *StellarNet) AccountIDNote(acct string) string

func (*StellarNet) AddHint

func (net *StellarNet) AddHint(acct string, hint string)

func (*StellarNet) AddSigner

func (net *StellarNet) AddSigner(signer, comment string)

func (*StellarNet) Get

func (net *StellarNet) Get(query string) ([]byte, error)

Send an HTTP request to horizon

func (*StellarNet) GetAccountEntry

func (net *StellarNet) GetAccountEntry(acct string) (
	*HorizonAccountEntry, error)

Fetch the sequence number and signers of an account over the network.

func (*StellarNet) GetFeeCache

func (net *StellarNet) GetFeeCache() (*FeeStats, error)

Like GetFeeStats but a version cached for 1 minute

func (*StellarNet) GetFeeStats

func (net *StellarNet) GetFeeStats() (*FeeStats, error)

Queries the network for the latest fee statistics.

func (*StellarNet) GetJSON

func (net *StellarNet) GetJSON(query string, out interface{}) error

Send an HTTP request to horizon and perse the result as JSON

func (*StellarNet) GetLedgerHeader

func (net *StellarNet) GetLedgerHeader() (*LedgerHeader, error)

Fetch the latest ledger header over the network.

func (*StellarNet) GetNativeAsset

func (net *StellarNet) GetNativeAsset() string

func (*StellarNet) GetNetworkId

func (net *StellarNet) GetNetworkId() string

Returns the network ID, a string that is hashed into transaction IDs to ensure that signature are not valid across networks (e.g., a testnet signature cannot work on the public network). If the network ID is not cached in the StellarNet structure itself, then this function fetches it from the network.

Note StellarMainNet already contains the network ID, while StellarTestNet requires fetching the network ID since the Stellar test network is periodically reset.

func (*StellarNet) GetTxResult

func (net *StellarNet) GetTxResult(txid string) (*HorizonTxResult, error)

func (*StellarNet) HashTx

func (net *StellarNet) HashTx(tx stx.Signable) *stx.Hash

Return a transaction hash (which in Stellar is defined as the hash of the constant ENVELOPE_TYPE_TX, the NetworkID, and the marshaled XDR of the Transaction).

func (*StellarNet) IniSink

func (net *StellarNet) IniSink() ini.IniSink

func (*StellarNet) IterateJSON

func (net *StellarNet) IterateJSON(
	ctx context.Context, query string, cb interface{}) error

Send a request to horizon and iterate through a series of embedded records in the response, continuing to fetch more records until zero records are returned. cb is a callback function which must have type func(obj *T)error or func(obj *T), where *T is a type into which JSON can be unmarshalled. Returns if there is an error or the ctx argument is Done.

func (*StellarNet) NewSignerPreauth

func (net *StellarNet) NewSignerPreauth(tx stx.Signable,
	weight uint32) *stx.Signer

Create a pre-signed transaction from a transaction and weight.

func (*StellarNet) Post

Post a new transaction to the network. In the event that the transaction is successfully submitted to horizon but rejected by the Stellar network, the error will be of type TxFailure, which contains the transaction result.

func (*StellarNet) Save

func (net *StellarNet) Save() error

Save any changes to to SavePath. Equivalent to SavePerm(0666).

func (*StellarNet) SavePerm

func (net *StellarNet) SavePerm(perm os.FileMode) error

Save any changes to SavePath. If SavePath does not exist, then create it with permissions Perm (subject to umask, of course).

func (*StellarNet) SigNote

func (*StellarNet) SignTx

Sign a transaction and append the signature to the TransactionEnvelope.

func (*StellarNet) SignerNote

func (net *StellarNet) SignerNote(key *stx.SignerKey) string

func (*StellarNet) StreamJSON

func (net *StellarNet) StreamJSON(
	ctx context.Context, query string, cb interface{}) error

Stream a series of events. cb is a callback function which must have type func(obj *T)error or func(obj *T), where *T is a type into which JSON can be unmarshalled. Returns if there is an error or the ctx argument is Done. You likely want to call this in a goroutine, and might want to call it in a loop to try again after errors.

func (*StellarNet) ToRep

func (net *StellarNet) ToRep(txe xdr.XdrType) string

Convert an arbitrary XDR data structure to human-readable Txrep format.

func (*StellarNet) TxToRep

func (net *StellarNet) TxToRep(txe *TransactionEnvelope) string

Convert a TransactionEnvelope to human-readable Txrep format.

func (*StellarNet) Validate

func (net *StellarNet) Validate() error

func (*StellarNet) VerifySig

func (net *StellarNet) VerifySig(
	pk *SignerKey, tx stx.Signable, sig Signature) bool

Returns true only if sig is a valid signature on e for public key pk.

func (*StellarNet) WriteRep

func (net *StellarNet) WriteRep(out io.Writer, name string, txe xdr.XdrType)

Write the human-readable Txrep of an XDR structure to a Writer.

type TransactionEnvelope

type TransactionEnvelope struct {
	*stx.TransactionEnvelope
	Help map[string]struct{}
}

This is a wrapper around the XDR TransactionEnvelope structure. The wrapper allows transactions to be built up more easily via the Append() method and various helper types. When parsing and generating Txrep format, it also keeps track of which enums were followed by '?' indicating a request for help.

func NewTransactionEnvelope

func NewTransactionEnvelope() *TransactionEnvelope

func TxFromBase64

func TxFromBase64(input string) (*TransactionEnvelope, error)

Parse a TransactionEnvelope from base64-encoded binary XDR format.

func TxFromRep

func TxFromRep(rep string) (*TransactionEnvelope, error)

Parse a transaction in human-readable Txrep format into a TransactionEnvelope.

func (*TransactionEnvelope) Append

func (txe *TransactionEnvelope) Append(
	sourceAccount *stx.MuxedAccount,
	body OperationBody)

Append an operation to a transaction envelope. To facilitate initialization of the transaction body (which is a union and so doesn't support direct initialization), a suite of helper types have the same fields as each of the operation types. The helper types are named after camel-cased versions of the OperationType constants. E.g., to append an operation of type CREATE_ACCOUNT, use type type CreateAccount:

txe.Append(nil, CreateAccount{
	Destination: myNewAccountID,
	StartingBalance: 15000000,
})

The helper types are:

type CreateAccount stx.CreateAccountOp
type Payment stx.PaymentOp
type PathPaymentStrictReceive stx.PathPaymentStrictReceiveOp
type ManageSellOffer stx.ManageSellOfferOp
type CreatePassiveSellOffer stx.CreatePassiveSellOfferOp
type SetOptions stx.SetOptionsOp
type ChangeTrust stx.ChangeTrustOp
type AllowTrust stx.AllowTrustOp
type AccountMerge stx.PublicKey
type Inflation struct{}
type ManageData stx.ManageDataOp
type BumpSequence stx.BumpSequenceOp
type ManageBuyOffer stx.ManageBuyOfferOp
type PathPaymentStrictSend stx.PathPaymentStrictSendOp

func (*TransactionEnvelope) GetHelp

func (txe *TransactionEnvelope) GetHelp(name string) bool

func (*TransactionEnvelope) SetFee

func (txe *TransactionEnvelope) SetFee(baseFee uint32)

Set the fee of a transaction to baseFee times the number of operations. If the result would exceed the maximum fee of 0xffffffff (~430 XLM), then just set the fee to 0xffffffff. (Obviously only call this once you have finished adding operations to the transaction with Append.)

func (*TransactionEnvelope) SetHelp

func (txe *TransactionEnvelope) SetHelp(name string)

func (*TransactionEnvelope) SetSourceAccount

func (txe *TransactionEnvelope) SetSourceAccount(m0 stx.IsAccount)

func (*TransactionEnvelope) SourceAccount

func (txe *TransactionEnvelope) SourceAccount() *stx.MuxedAccount

type TransactionResult

type TransactionResult = stx.TransactionResult

type TxFailure

type TxFailure struct {
	*TransactionResult
}

An error representing the failure of a transaction submitted to the Stellar network, and from which you can extract the full TransactionResult.

func (TxFailure) Error

func (e TxFailure) Error() string

Directories

Path Synopsis
cmd
stc
Please see the stc.1 man page for complete documentation of this command.
Please see the stc.1 man page for complete documentation of this command.
Ini file parser library.
Ini file parser library.
Internal functions for the stc library.
Internal functions for the stc library.
The stx package provides a compiled go representation of Stellar's XDR data structures.
The stx package provides a compiled go representation of Stellar's XDR data structures.

Jump to

Keyboard shortcuts

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