stcdetail

package
v0.0.0-...-057f3bb Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2021 License: Apache-2.0, GPL-3.0-or-later Imports: 22 Imported by: 0

Documentation

Overview

Internal functions for the stc library. These functions are exported because they may be useful to application code, but relegated to a separate package to avoid cluttering the main stc documentation.

Index

Examples

Constants

This section is empty.

Variables

View Source
var PassphraseFile io.Reader = os.Stdin

PassphraseFile is the io.Reader from which passphrases should be read. If set to a terminal, then a prompt will be displayed and echo will be disabled while the user types the passphrase. The default is os.Stdin. If set to nil, then GetPass will attempt to open /dev/tty. Set it to io.MultiReader() (i.e., an io.Reader that always returns EOF) to assume an empty passphrase every time GetPass is called.

View Source
var PassphrasePrompt io.Writer = os.Stderr

If PassphraseFile is a terminal, then the user will be prompted for a password, and this is the terminal to which the prompt should be written. The default is os.Stderr.

Functions

func FileChanged

func FileChanged(a, b os.FileInfo) bool

Return true if a file may have been changed between the times that the two FileInfo structures were read. Note that it modifies the two arguments to set the atimes to zero before doing a deep compare of all fields. (This ensures files will be considered changed if their ctimes differ, even if the mtimes are the same.)

func ForEachXdr

func ForEachXdr(t xdr.XdrType, fn func(xdr.XdrType) bool)

Calls fn, recursively, on every value inside an XdrType. Prunes the recursion if fn returns true.

func ForEachXdrType

func ForEachXdrType(a xdr.XdrType, fn interface{})

Calls fn on each instance of a type encountered while traversing a data structure. fn should be of type func(*T) or func(*T)bool where T is an XDR structure. By default, the traversal does not recurse into T. In the case that T is part of a linked list (or otherwise contains a pointer to T internally), if the function returns false then fields within T will continue to be examined recursively.

func GetLedgerEntryKey

func GetLedgerEntryKey(e *stx.LedgerEntry) stx.LedgerKey

func GetPass

func GetPass(prompt string) []byte

Read a passphrase from PassphraseFile and return it as a byte array. If PassphraseFile is nil, attempt to open "/dev/tty". If PassphraseFile is a terminal, then write prompt to PassphrasePrompt before reading the passphrase and disable echo.

func GetPass2

func GetPass2(prompt string) []byte

Call GetPass twice until the user enters the same passphrase twice. Intended for when the user is selecting a new passphrase, to reduce the chances of the user mistyping the passphrase.

func GetTxrepField

func GetTxrepField(t xdr.XdrType, field string) (ret xdr.XdrType)

Extract and return a field with a particular txrep name from an XDR data structure. Returns nil if the field name doesn't exist, either because it is invalid or because a containing pointer is nil or because a union has a different active case.

Note that for pointer fields this functionreturns the pointer, not the underlying value. Hence the XdrPointer() method returns a pointer-to-pointer type that is guaranteed not to be nil even if the pointer is nil.

Example
var a1, a2 stx.MuxedAccount
fmt.Sscan("GATPALHEEUERWYW275QDBNBMCM4KEHYJU34OPIZ6LKJAXK6B4IJ73V4L", &a1)
fmt.Sscan("GDFR4HZMNZCNHFEIBWDQCC4JZVFQUGXUQ473EJ4SUPFOJ3XBG5DUCS2G", &a2)
txe := stc.NewTransactionEnvelope()
txe.Append(nil, stc.Payment{
	Destination: a1,
	Asset:       stc.NativeAsset(),
	Amount:      10000000,
})

// The sourceAccount field of a transaction is an AccountID
*GetTxrepField(txe, "tx.sourceAccount").XdrPointer().(*stx.MuxedAccount) =
	a1

// The sourceAccount field of an operation is a *AccountID, so the
// field we get back is of type **AccountID
op0src := "tx.operations[0].sourceAccount"
*GetTxrepField(txe, op0src).XdrPointer().(**stx.MuxedAccount) = &a2

XdrToTxrep(os.Stdout, "", txe)
Output:

type: ENVELOPE_TYPE_TX
tx.sourceAccount: GATPALHEEUERWYW275QDBNBMCM4KEHYJU34OPIZ6LKJAXK6B4IJ73V4L
tx.fee: 0
tx.seqNum: 0
tx.timeBounds._present: false
tx.memo.type: MEMO_NONE
tx.operations.len: 1
tx.operations[0].sourceAccount._present: true
tx.operations[0].sourceAccount: GDFR4HZMNZCNHFEIBWDQCC4JZVFQUGXUQ473EJ4SUPFOJ3XBG5DUCS2G
tx.operations[0].body.type: PAYMENT
tx.operations[0].body.paymentOp.destination: GATPALHEEUERWYW275QDBNBMCM4KEHYJU34OPIZ6LKJAXK6B4IJ73V4L
tx.operations[0].body.paymentOp.asset: native
tx.operations[0].body.paymentOp.amount: 10000000 (1e7)
tx.ext.v: 0
signatures.len: 0

func HideFieldName

func HideFieldName(field string, t xdr.XdrType) bool

Returns true for types whose field names should be hidden when the field name is of the form v[0-9]+. This if for backwards compatibility, as fields of this type are intended to be used as versions of the same structure in a version union, and eliding the field names (v0, v1, ...) allows one to change the version without invalidating the rest of the fields.

func JsonNumberToI64

func JsonNumberToI64(n json.Number) (int64, error)

Convert a json.Number to an int64 by scanning the textual representation of the number. (The simpler approach of going through a double risks losing precision.)

func JsonToXdr

func JsonToXdr(dst xdr.XdrAggregate, src []byte) (err error)

Parse JSON into an XDR structure. This function assumes that dst is in a pristine state--for example, it won't reset pointers to nil if the corresponding JSON is null. Moreover, it is somewhat strict in expecting the JSON to conform to the XDR.

func PrettyPrint

func PrettyPrint(arg interface{}) string

func PrettyPrintAux

func PrettyPrintAux(aux func(interface{}) (string, bool),
	arg interface{}) string

func PrintVecOpaque

func PrintVecOpaque(bs []byte) string

Convert an array of bytes into a string of hex digits. Show an empty vector as "0 bytes", since we need to show it as something. (Note the bytes is a comment, but just "0" might be unintuitive.)

func ReadFile

func ReadFile(path string) ([]byte, os.FileInfo, error)

Read the contents of a file and also return the FileInfo at the time the file is read. The returned FileInfo can be checked with FileChanged to see if the file has changed since it was last read, and the result will be guaranteed not to miss modifications (at least on Unix where setting the mtime to something in the past increases the ctime).

func ReadTextLine

func ReadTextLine(r io.Reader) ([]byte, error)

Read a line of text without using bufio.

func RepDiff

func RepDiff(prefix, arep, brep string) string

Takes two inputs in txrep format, and returns a string describing all the lines that have changed in the form:

field: old_value -> new_value

Either old_value or new_value may be empty for a field that appears only in a or only in b.

func SafeCreateFile

func SafeCreateFile(path string, data string, perm os.FileMode) error

Like SafeWriteFile, but fails if the file already exists after the lock is acquired. Does not exclusively create the target file, but rather uses a lockfile to ensure that if the file is created it will have data as its contents. (Exclusively creating the target file could lead to the file existing but being empty after a crash.)

func SafeWriteFile

func SafeWriteFile(path string, data string, perm os.FileMode) error

Writes data to file path in a safe way. If path is "foo", then data is first written to a file called "foo.lock" and that file is flushed to disk. Then, if a file called "foo" already exists, "foo" is linked to "foo~" to keep a backup. Finally, "foo.lock" is renamed to "foo". Fails if "foo.lock" already exists.

func ScaleFmt

func ScaleFmt(val int64, exp int) string

Print a number divided by 10^exp, appending the exponent.

Example
fmt.Println(ScaleFmt(987654321, 7))
Output:

98.7654321e7

func Stream

func Stream(ctx context.Context, url string,
	cb func(eventType string, data []byte) error) error

Stream results from a URL that returns a body of type text/event-stream, as described in https://www.w3.org/TR/eventsource/

The callback function, cb, gets called with a series of event types and data payloads. The event type will generally be one of "message", "error", "open", or "close" (where you will typically ignore events of type open and close).

Stream does not spawn a new goroutine. It loops until the Context ctx is canceled or there is a non-nil error. Hence, the cb can make Stream return by returning a non-nil error. You will generally want to spawn Stream in a new goroutine, and may wish to wrap it in a loop to keep trying in the face of errors.

In keeping with the Stellar Horizon REST API, if url does not contain a cursor parameter, Stream adds cursor=now to the query. It furthermore updates the cursor to the latest event ID whenever it needs to reconnect.

func TxPayloadHash

func TxPayloadHash(network string, tx stx.Signable) *stx.Hash

Returns the transaction hash for a transaction. The first argument, network, is the network name, since the transaction hash depends on the particular instantiation of the Stellar network.

func Verify

func Verify(pk *stx.PublicKey, message []byte, sig []byte) bool

Verify a signature on an arbitrary raw message. Stellar messages should be hashed with the NetworkID before signing or verifying, so you probably don't want to use this function. See VerifyTx and the ToSignerKey() method of PublicKey, instead.

func VerifyTx

func VerifyTx(pk *stx.SignerKey, network string, tx stx.Signable,
	sig []byte) bool

Verify the signature on a transaction.

func XdrExtract

func XdrExtract(t xdr.XdrType, out interface{}) bool

If out is of type **T, then *out is set to point to the first instance of T found when traversing t.

func XdrFromBase64

func XdrFromBase64(e xdr.XdrType, input string) (err error)

Parse base64-encoded binary XDR into an XDR aggregate structure.

func XdrFromBin

func XdrFromBin(t xdr.XdrType, input string) (err error)

Unmarshal an XDR type from the raw binary bytes defined in RFC4506.

func XdrSHA256

func XdrSHA256(ts ...xdr.XdrType) (ret stx.Hash)

Computes the SHA-256 hash of an arbitrary XDR data structure.

func XdrToBase64

func XdrToBase64(es ...xdr.XdrType) string

Convert an XDR aggregate to base64-encoded binary format. Calls panic() with an XdrError if any field contains illegal values (e.g., if a slice exceeds its bounds or a union discriminant has an invalid value).

func XdrToBin

func XdrToBin(t xdr.XdrType) string

Marshal an XDR type to the raw binary bytes defined in RFC4506. The return value is binary, not UTF-8. For most marshaling purposes you might prefer a []byte (so see XdrOut), but this function is handy if you want to convert the contents of an XDR structure into a map key or compare two XDR structures for equality.

func XdrToJson

func XdrToJson(src xdr.XdrAggregate) (json []byte, err error)

Format an XDR structure as JSON.

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

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

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

// Sign the transaction
stc.DefaultStellarNet("main").SignTx(&mykey, txe)

// Print the transaction in JSON
j, _ := XdrToJson(txe)
fmt.Print(string(j))
Output:

{
    "type": "ENVELOPE_TYPE_TX",
    "tx": {
        "sourceAccount": "GDFR4HZMNZCNHFEIBWDQCC4JZVFQUGXUQ473EJ4SUPFOJ3XBG5DUCS2G",
        "fee": 100,
        "seqNum": "3319833626148865",
        "timeBounds": null,
        "memo": {
            "type": "MEMO_TEXT",
            "text": "Hello"
        },
        "operations": [
            {
                "sourceAccount": null,
                "body": {
                    "type": "PAYMENT",
                    "paymentOp": {
                        "destination": "GATPALHEEUERWYW275QDBNBMCM4KEHYJU34OPIZ6LKJAXK6B4IJ73V4L",
                        "asset": "native",
                        "amount": "20000000"
                    }
                }
            }
        ],
        "ext": {
            "v": 0
        }
    },
    "signatures": [
        {
            "hint": "4TdHQQ==",
            "signature": "O/lsKauVcwd1YStamg7GMNd5hGqzGy4H3o0k3pJ5YfhmdgQJGjlC51bg3BTdlEZeK2EyiASB5AMFXsM5BUKVAg=="
        }
    ]
}

Types

type Ed25519Priv

type Ed25519Priv ed25519.PrivateKey

func NewEd25519Priv

func NewEd25519Priv() Ed25519Priv

func (Ed25519Priv) Public

func (sk Ed25519Priv) Public() (ret stx.PublicKey)

func (Ed25519Priv) Sign

func (sk Ed25519Priv) Sign(msg []byte) ([]byte, error)

func (Ed25519Priv) String

func (sk Ed25519Priv) String() string

type ErrFileHasChanged

type ErrFileHasChanged string

func (ErrFileHasChanged) Error

func (e ErrFileHasChanged) Error() string

type ErrIsDirectory

type ErrIsDirectory string

func (ErrIsDirectory) Error

func (e ErrIsDirectory) Error() string

type HTTPerror

type HTTPerror struct {
	Resp *http.Response
	Body []byte
}

A status line for a non-200 HTTP response

func NewHTTPerror

func NewHTTPerror(resp *http.Response) *HTTPerror

func (*HTTPerror) Error

func (e *HTTPerror) Error() string

func (*HTTPerror) Temporary

func (e *HTTPerror) Temporary() bool

Returns true for 503, false otherwise. Should examine the result more carefully to distinguish between transient or permanent 500 errors.

type JsonInt64

type JsonInt64 int64

An int64 that marshals and unmarshals as a string in JSON to avoid loss of precision (since JSON numbers are floating point).

func (JsonInt64) MarshalText

func (i JsonInt64) MarshalText() ([]byte, error)

func (*JsonInt64) UnmarshalText

func (i *JsonInt64) UnmarshalText(text []byte) error

type JsonInt64e7

type JsonInt64e7 int64

An int64 that marshals and unmarshals to a string in JSON containing a fixed-point number 10^{-7} times the value.

func (JsonInt64e7) MarshalText

func (i JsonInt64e7) MarshalText() ([]byte, error)

func (JsonInt64e7) String

func (i JsonInt64e7) String() string

func (*JsonInt64e7) UnmarshalText

func (i *JsonInt64e7) UnmarshalText(text []byte) error

type LockedFile

type LockedFile interface {
	io.Writer
	io.StringWriter

	// Call when you wish to replace the locked file with what you
	// have written to this Writer and then release the lock.
	Commit() error

	// Returns the contents of the locked file.  (This is not the
	// contents of the lockfile itself, which is initially empty and
	// to which you must write the new contents that you want to swap
	// in atomically.)  Also checks the file modification time, so as
	// to cause an abort if anyone else changes the file after you've
	// locked it and before you've called Commit().
	ReadFile() ([]byte, error)

	// Return the file info at the time the lock was taken (or nil if
	// the file did not exist).
	Status() os.FileInfo

	// You must call Abort() to clean up the lockfile, unless you have
	// called Commit().  However, it is safe to call Abort() multiple
	// times, or to call Abort() after Commit(), so the best use is to
	// call defer lf.Abort() as soon as you have a LockedFile.
	Abort()
}

An interface to update a file atomically. Acts as a Writer, and when you call Commit() atomically renames the lockfile you just wrote to the target filename.

func LockFile

func LockFile(path string, perm os.FileMode) (LockedFile, error)

Locks a file for updating. Exclusively creates a file with name path + ".lock", returns a writer that lets you write into this lockfile, and then when you call Commit() replaces path with what you have just written. You must call Abort() or Commit() on the returned interface. Since it is safe to call both, best practice is to defer a call to Abort() immediately.

Example
lf, err := LockFile("testfile", 0666)
if err != nil {
	return err
}
defer lf.Abort()

fmt.Fprintf(lf, "New file contents\n")

return lf.Commit()
Output:

func LockFileIfUnchanged

func LockFileIfUnchanged(path string, fi os.FileInfo) (LockedFile, error)

Like LockFile, but fails if file's stat information (other than atime) does not exactly match fi. If fi is nil, then acts like LockFile with perm of 0666.

type MetaDelta

type MetaDelta struct {
	Key      stx.LedgerKey
	Old, New *stx.LedgerEntry
}

Structure representing the value of a specific ledger entry before and after execution of a transaction.

func GetMetaDeltas

func GetMetaDeltas(ms ...xdr.XdrType) (ret []MetaDelta)

Extract the before/after ledger entry values from XDR structures containing LedgerEntryChanges.

func (MetaDelta) AccountID

func (md MetaDelta) AccountID() *stx.AccountID

The account that owns the ledger entry.

type PrivateKeyInterface

type PrivateKeyInterface interface {
	String() string
	Sign([]byte) ([]byte, error)
	Public() stx.PublicKey
}

type TxrepError

type TxrepError []struct {
	Line int
	Msg  string
}

Represents errors encountered when parsing textual Txrep into XDR structures.

func XdrFromTxrep

func XdrFromTxrep(in io.Reader, name string, t xdr.XdrType) TxrepError

Parse input in Txrep format into an XdrType type. If the XdrType has a method named SetHelp(string), then it is called for field names when the value ends with '?'.

func (TxrepError) Error

func (e TxrepError) Error() string

func (TxrepError) FileError

func (e TxrepError) FileError(filename string) string

Convert TxrepError to string, but placing filename and a colon before each line, so as to render messages in the conventional "file:line: message" format.

func (TxrepError) Is

func (TxrepError) Is(e error) bool

type XdrBadValue

type XdrBadValue []struct {
	Field string
	Msg   string
}

Reports illegal values in an XDR structure.

func XdrToTxrep

func XdrToTxrep(out io.Writer, name string, t xdr.XdrType) XdrBadValue

Writes a human-readable version of a transaction or other XdrType structure to out in txrep format. The following methods on t can be used to add comments into the output

Comment for AccountID:

AccountIDNote(string) string

Comment for SignerKey:

SignerNote(*SignerKey) string

Comment for Signature:

SigNote(*TransactionEnvelope, *DecoratedSignature) string

Help comment for field fieldname:

GetHelp(fieldname string) bool

func (XdrBadValue) Error

func (e XdrBadValue) Error() string

Jump to

Keyboard shortcuts

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