From 817967984a49b688cff8497b0dda701c627dc6dd Mon Sep 17 00:00:00 2001 From: Adolfo Builes Date: Tue, 15 Sep 2020 10:03:15 -0500 Subject: [PATCH] Fix static check tests. (#3005) * Ignore U1001 check in test files. * Add test for ClaimableBalancesQueryURITemplate. * Remove demo and example from internal txnbuild package. * Fix static checks. --- .../actions/claimable_balance_test.go | 8 + .../claimable_balances_processor_test.go | 1 + .../transaction_operation_wrapper_test.go | 1 + services/horizon/internal/test/integration.go | 17 - .../begin_sponsoring_future_reserves.go | 1 + .../txnbuild/claim_claimable_balance.go | 1 + .../internal/txnbuild/cmd/demo/cmd/init.go | 39 -- .../internal/txnbuild/cmd/demo/cmd/reset.go | 40 -- .../internal/txnbuild/cmd/demo/cmd/root.go | 83 --- .../internal/txnbuild/cmd/demo/cmd/txerror.go | 40 -- .../internal/txnbuild/cmd/demo/main.go | 10 - .../txnbuild/cmd/demo/operations/demo.go | 522 ------------------ .../txnbuild/create_claimable_balance.go | 1 + .../end_sponsoring_future_reserves.go | 1 + .../examplehorizonclient.go | 67 --- .../horizon/internal/txnbuild/transaction.go | 45 -- 16 files changed, 14 insertions(+), 863 deletions(-) delete mode 100644 services/horizon/internal/txnbuild/cmd/demo/cmd/init.go delete mode 100644 services/horizon/internal/txnbuild/cmd/demo/cmd/reset.go delete mode 100644 services/horizon/internal/txnbuild/cmd/demo/cmd/root.go delete mode 100644 services/horizon/internal/txnbuild/cmd/demo/cmd/txerror.go delete mode 100644 services/horizon/internal/txnbuild/cmd/demo/main.go delete mode 100644 services/horizon/internal/txnbuild/cmd/demo/operations/demo.go delete mode 100644 services/horizon/internal/txnbuild/examplehorizonclient/examplehorizonclient.go diff --git a/services/horizon/internal/actions/claimable_balance_test.go b/services/horizon/internal/actions/claimable_balance_test.go index ed47ccc91b..d76e34a13a 100644 --- a/services/horizon/internal/actions/claimable_balance_test.go +++ b/services/horizon/internal/actions/claimable_balance_test.go @@ -10,6 +10,7 @@ import ( "github.com/stellar/go/support/errors" "github.com/stellar/go/support/render/problem" "github.com/stellar/go/xdr" + "github.com/stretchr/testify/assert" ) func TestGetClaimableBalanceByID(t *testing.T) { @@ -530,3 +531,10 @@ func TestGetClaimableBalances(t *testing.T) { // ) // } } + +func TestClaimableBalancesQueryURLTemplate(t *testing.T) { + tt := assert.New(t) + expected := "/claimable_balances?{asset,claimant,sponsor}" + q := ClaimableBalancesQuery{} + tt.Equal(expected, q.URITemplate()) +} diff --git a/services/horizon/internal/expingest/processors/claimable_balances_processor_test.go b/services/horizon/internal/expingest/processors/claimable_balances_processor_test.go index 4f78d59f33..ea1d211d21 100644 --- a/services/horizon/internal/expingest/processors/claimable_balances_processor_test.go +++ b/services/horizon/internal/expingest/processors/claimable_balances_processor_test.go @@ -1,3 +1,4 @@ +//lint:file-ignore U1001 Ignore all unused code, staticcheck doesn't understand testify/suite package processors import ( diff --git a/services/horizon/internal/expingest/processors/transaction_operation_wrapper_test.go b/services/horizon/internal/expingest/processors/transaction_operation_wrapper_test.go index c0cd3a2a55..ef6e544f45 100644 --- a/services/horizon/internal/expingest/processors/transaction_operation_wrapper_test.go +++ b/services/horizon/internal/expingest/processors/transaction_operation_wrapper_test.go @@ -1,3 +1,4 @@ +//lint:file-ignore U1001 Ignore all unused code, staticcheck doesn't understand testify/suite package processors import ( diff --git a/services/horizon/internal/test/integration.go b/services/horizon/internal/test/integration.go index 465d3dce60..10310aab9a 100644 --- a/services/horizon/internal/test/integration.go +++ b/services/horizon/internal/test/integration.go @@ -325,23 +325,6 @@ func (i *IntegrationTest) CreateAccounts(count int) ([]*keypair.Full, []txnbuild return pairs, accounts } -// Establishes a trustline for a given asset for a particular account. -// -// Note: The function panics if this account doesn't exist in the ledger yet, so -// be sure to fund it before doing this. -func (i *IntegrationTest) EstablishTrustline( - truster *keypair.Full, asset txnbuild.Asset, -) (proto.Transaction, error) { - request := sdk.AccountRequest{AccountID: truster.Address()} - account, err := i.Client().AccountDetail(request) - panicIf(err) - - return i.SubmitOperations(&account, truster, &txnbuild.ChangeTrust{ - Line: asset, - Limit: "2000", - }) -} - // Submits a signed transaction from an account with standard options. // // Namely, we set the standard fee, time bounds, etc. to "non-production" diff --git a/services/horizon/internal/txnbuild/begin_sponsoring_future_reserves.go b/services/horizon/internal/txnbuild/begin_sponsoring_future_reserves.go index 6e6d84b5da..6de29df4d2 100644 --- a/services/horizon/internal/txnbuild/begin_sponsoring_future_reserves.go +++ b/services/horizon/internal/txnbuild/begin_sponsoring_future_reserves.go @@ -1,3 +1,4 @@ +//lint:file-ignore U1001 Ignore all unused code, staticcheck doesn't understand testify/suite package txnbuild import ( diff --git a/services/horizon/internal/txnbuild/claim_claimable_balance.go b/services/horizon/internal/txnbuild/claim_claimable_balance.go index 5ea8540f6d..9dec4693b3 100644 --- a/services/horizon/internal/txnbuild/claim_claimable_balance.go +++ b/services/horizon/internal/txnbuild/claim_claimable_balance.go @@ -1,3 +1,4 @@ +//lint:file-ignore U1001 Ignore all unused code, staticcheck doesn't understand testify/suite package txnbuild import ( diff --git a/services/horizon/internal/txnbuild/cmd/demo/cmd/init.go b/services/horizon/internal/txnbuild/cmd/demo/cmd/init.go deleted file mode 100644 index 382fcf1d5c..0000000000 --- a/services/horizon/internal/txnbuild/cmd/demo/cmd/init.go +++ /dev/null @@ -1,39 +0,0 @@ -package cmd - -import ( - "fmt" - - log "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "github.com/stellar/go/clients/horizonclient" - demo "github.com/stellar/go/txnbuild/cmd/demo/operations" -) - -// initCmd represents the init command -var initCmd = &cobra.Command{ - Use: "init", - Short: "Create and fund some demo accounts on the TestNet", - Long: `This command creates four test accounts for use with further operations.`, - Run: func(cmd *cobra.Command, args []string) { - log.Info("Initialising TestNet accounts...") - keys := demo.InitKeys(4) - client := horizonclient.DefaultTestNetClient - - demo.Initialise(client, keys) - fmt.Println("Initialisation complete.") - }, -} - -func init() { - rootCmd.AddCommand(initCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // initCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // initCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} diff --git a/services/horizon/internal/txnbuild/cmd/demo/cmd/reset.go b/services/horizon/internal/txnbuild/cmd/demo/cmd/reset.go deleted file mode 100644 index 8e68a23c0c..0000000000 --- a/services/horizon/internal/txnbuild/cmd/demo/cmd/reset.go +++ /dev/null @@ -1,40 +0,0 @@ -package cmd - -import ( - "fmt" - - log "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "github.com/stellar/go/clients/horizonclient" - demo "github.com/stellar/go/txnbuild/cmd/demo/operations" -) - -// resetCmd represents the reset command -var resetCmd = &cobra.Command{ - Use: "reset", - Short: "Reset the state of all demo accounts on the TestNet", - Long: `Run this command before trying other commands in order to have a clean slate -for testing.`, - Run: func(cmd *cobra.Command, args []string) { - log.Info("Resetting TestNet state...") - keys := demo.InitKeys(4) - client := horizonclient.DefaultTestNetClient - - demo.Reset(client, keys) - fmt.Println("Reset complete.") - }, -} - -func init() { - rootCmd.AddCommand(resetCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // resetCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // resetCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} diff --git a/services/horizon/internal/txnbuild/cmd/demo/cmd/root.go b/services/horizon/internal/txnbuild/cmd/demo/cmd/root.go deleted file mode 100644 index 81846f78fa..0000000000 --- a/services/horizon/internal/txnbuild/cmd/demo/cmd/root.go +++ /dev/null @@ -1,83 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - - log "github.com/sirupsen/logrus" - - homedir "github.com/mitchellh/go-homedir" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var cfgFile string -var verbose bool - -// rootCmd represents the base command when called without any subcommands -var rootCmd = &cobra.Command{ - Use: "demo", - Short: "Exercise the Stellar Go SDK (horizonclient + txnbuild)", - Long: `This CLI is a working demonstration of the Stellar Go SDK. The SDK is used to interact -with the Stellar network. It can retrieve information about the state of the network, and can -submit _transactions_, made up of _operations_, to change the state of the network. - -Try out the different commands here to see the SDK in action, then browse the source code in -/operations/demo.go to see how the SDK is used.`, - // Uncomment the following line if your bare application - // has an action associated with it: - // Run: func(cmd *cobra.Command, args []string) { }, -} - -// Execute adds all child commands to the root command and sets flags appropriately. -// This is called by main.main(). It only needs to happen once to the rootCmd. -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Println(err) - os.Exit(1) - } -} - -func init() { - cobra.OnInitialize(initConfig) - - // Here you will define your flags and configuration settings. - // Cobra supports persistent flags, which, if defined here, - // will be global for your application. - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)") - rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose logging") - - // Cobra also supports local flags, which will only run - // when this action is called directly. - // rootCmd.Flags().BoolP("verbose", "v", false, "Enable verbose logging") -} - -// initConfig reads in config file and ENV variables if set. -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := homedir.Dir() - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - // Search config in home directory with name ".demo" (without extension). - viper.AddConfigPath(home) - viper.SetConfigName(".demo") - } - - viper.AutomaticEnv() // read in environment variables that match - - // If a config file is found, read it in. - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } - - if verbose { - log.SetLevel(log.DebugLevel) - } -} diff --git a/services/horizon/internal/txnbuild/cmd/demo/cmd/txerror.go b/services/horizon/internal/txnbuild/cmd/demo/cmd/txerror.go deleted file mode 100644 index 7db945967d..0000000000 --- a/services/horizon/internal/txnbuild/cmd/demo/cmd/txerror.go +++ /dev/null @@ -1,40 +0,0 @@ -package cmd - -import ( - "fmt" - - log "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - - "github.com/stellar/go/clients/horizonclient" - demo "github.com/stellar/go/txnbuild/cmd/demo/operations" -) - -// txerrorCmd represents the txerror command -var txerrorCmd = &cobra.Command{ - Use: "txerror", - Short: "Submit a purposefully invalid transaction", - Long: `This command submits an invalid transaction, in order to demonstrate a Horizon error return.`, - Run: func(cmd *cobra.Command, args []string) { - log.Info("Demonstrating a bad transaction response...") - keys := demo.InitKeys(4) - client := horizonclient.DefaultTestNetClient - - demo.TXError(client, keys) - fmt.Println("Transaction complete.") - }, -} - -func init() { - rootCmd.AddCommand(txerrorCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // txerrorCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // txerrorCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} diff --git a/services/horizon/internal/txnbuild/cmd/demo/main.go b/services/horizon/internal/txnbuild/cmd/demo/main.go deleted file mode 100644 index 01a87df777..0000000000 --- a/services/horizon/internal/txnbuild/cmd/demo/main.go +++ /dev/null @@ -1,10 +0,0 @@ -// Demo is an interactive demonstration of the Go SDK using the Stellar TestNet. -package main - -import ( - "github.com/stellar/go/txnbuild/cmd/demo/cmd" -) - -func main() { - cmd.Execute() -} diff --git a/services/horizon/internal/txnbuild/cmd/demo/operations/demo.go b/services/horizon/internal/txnbuild/cmd/demo/operations/demo.go deleted file mode 100644 index 39f65ceb70..0000000000 --- a/services/horizon/internal/txnbuild/cmd/demo/operations/demo.go +++ /dev/null @@ -1,522 +0,0 @@ -// Package demo is an interactive demonstration of the Go SDK using the Stellar TestNet. -package demo - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - - log "github.com/sirupsen/logrus" - - "github.com/stellar/go/clients/horizonclient" - "github.com/stellar/go/network" - hProtocol "github.com/stellar/go/protocols/horizon" - "github.com/stellar/go/strkey" - "github.com/stellar/go/support/errors" - "github.com/stellar/go/txnbuild" - "github.com/stellar/go/xdr" - - "github.com/stellar/go/keypair" -) - -// The account address of the TestNet "friendbot" -const friendbotAddress = "GAIH3ULLFQ4DGSECF2AR555KZ4KNDGEKN4AFI4SU2M7B43MGK3QJZNSR" - -// The local file where your generated demo account keys will be stored -// For convenience, the address is also stored so you can look up accounts on the network -const accountsFile = "demo.keys" - -// Account represents a Stellar account for this demo. -type Account struct { - Seed string `json:"name"` - Address string `json:"address"` - HAccount *hProtocol.Account `json:"account"` - Keypair *keypair.Full `json:"keypair"` - Exists bool `json:"exists"` -} - -// InitKeys creates n random new keypairs, storing them in a local file. If the file exists, -// InitKeys reads the file instead to construct the keypairs (and ignores n). -func InitKeys(n int) []Account { - accounts := make([]Account, n) - - fh, err := os.Open(accountsFile) - if os.IsNotExist(err) { - // Create the accounts and record them in a file - log.Info("Accounts file not found - creating new keypairs...") - for i := 0; i < n; i++ { - accounts[i] = createKeypair() - } - - jsonAccounts, err2 := json.MarshalIndent(accounts, "", " ") - dieIfError("problem marshalling json accounts", err2) - err = ioutil.WriteFile(accountsFile, jsonAccounts, 0644) - dieIfError("problem writing json accounts file", err) - log.Info("Wrote keypairs to local file ", accountsFile) - - return accounts - } - - // Read the file and create keypairs - log.Infof("Found accounts file %s...", accountsFile) - defer fh.Close() - bytes, err := ioutil.ReadAll(fh) - dieIfError("problem converting json file to bytes", err) - json.Unmarshal(bytes, &accounts) - - // Create the keypair objects - for i, k := range accounts { - kp, err := keypair.Parse(k.Seed) - dieIfError("keypair didn't parse!", err) - accounts[i].Keypair = kp.(*keypair.Full) - } - - return accounts -} - -// Reset is a command that removes all test accounts created by this demo. All funds are -// transferred back to Friendbot using the account merge operation. -func Reset(client *horizonclient.Client, keys []Account) { - keys = loadAccounts(client, keys) - for _, k := range keys { - if !k.Exists { - log.Infof("Account %s not found - skipping further operations on it...", k.Address) - continue - } - - // It exists - so we will proceed to deconstruct any existing account entries, and then merge it - // See https://www.stellar.org/developers/guides/concepts/ledger.html#ledger-entries - log.Info("Found testnet account with ID:", k.HAccount.ID) - - // Find any offers that need deleting... - offerRequest := horizonclient.OfferRequest{ - ForAccount: k.Address, - Order: horizonclient.OrderDesc, - } - offers, err := client.Offers(offerRequest) - dieIfError("error while getting offers", err) - log.Infof("Account %s has %v offers...", k.Address, len(offers.Embedded.Records)) - - // ...and delete them - for _, o := range offers.Embedded.Records { - log.Info(" ", o) - txe, err := deleteOffer(k.HAccount, o.ID, k) - dieIfError("problem building deleteOffer op", err) - log.Infof("Deleting offer %d...", o.ID) - resp := submit(client, txe) - log.Debug(resp) - } - - // Find any authorised trustlines on this account... - log.Infof("Account %s has %d balances...", k.Address, len(k.HAccount.Balances)) - - // ...and delete them - for _, b := range k.HAccount.Balances { - // Native balances don't have trustlines - if b.Type == "native" { - continue - } - asset := txnbuild.CreditAsset{ - Code: b.Code, - Issuer: b.Issuer, - } - - // Send the asset back to the issuer... - log.Infof("Sending %v of surplus asset %s:%s back to issuer...", b.Balance, asset.Code, asset.Issuer) - txe, err := payment(k.HAccount, asset.Issuer, b.Balance, asset, k) - dieIfError("problem building payment op", err) - resp := submit(client, txe) - log.Debug(resp) - - // Delete the now-empty trustline... - log.Infof("Deleting trustline for asset %s:%s...", b.Code, b.Issuer) - txe, err = deleteTrustline(k.HAccount, asset, k) - dieIfError("problem building deleteTrustline op", err) - resp = submit(client, txe) - log.Debug(resp) - } - - // Find any data entries on this account... - log.Infof("Account %s has %d data entries...", k.Address, len(k.HAccount.Data)) - for dataKey := range k.HAccount.Data { - decodedV, _ := k.HAccount.GetData(dataKey) - log.Infof("Deleting data entry '%s' -> '%s'...", dataKey, decodedV) - txe, err := deleteData(k.HAccount, dataKey, k) - dieIfError("problem building manageData op", err) - resp := submit(client, txe) - log.Debug(resp) - } - } - - // Finally, the accounts may be merged - for _, k := range keys { - if !k.Exists { - continue - } - log.Infof("Merging account %s back to friendbot (%s)...", k.Address, friendbotAddress) - txe, err := mergeAccount(k.HAccount, friendbotAddress, k) - dieIfError("problem building mergeAccount op", err) - resp := submit(client, txe) - log.Debug(resp) - } -} - -// Initialise is a command that funds an initial set of accounts for use with other demo operations. -// The first account is funded from Friendbot; subseqeuent accounts are created and funded from this -// first account. -func Initialise(client *horizonclient.Client, keys []Account) { - // Fund the first account from friendbot - log.Infof("Funding account %s from friendbot...", keys[0].Address) - _, err := client.Fund(keys[0].Address) - dieIfError(fmt.Sprintf("couldn't fund account %s from friendbot", keys[0].Address), err) - keys[0].HAccount = loadAccount(client, keys[0].Address) - keys[0].Exists = true - - // Fund the others using the create account operation - for i := 1; i < len(keys); i++ { - log.Infof("Funding account %s from account %s...", keys[i].Address, keys[0].Address) - txe, err := createAccount(keys[0].HAccount, keys[i].Address, keys[0]) - dieIfError("problem building createAccount op", err) - resp := submit(client, txe) - log.Debug(resp) - } -} - -// TXError is a command that deliberately creates a bad transaction to trigger an error response -// from Horizon. This code demonstrates how to retrieve and inspect the error. -func TXError(client *horizonclient.Client, keys []Account) { - keys = loadAccounts(client, keys) - // Create a bump seq operation - // Set the seq number to -1 (invalid) - // Create the transaction - txe, err := bumpSequence(keys[0].HAccount, -1, keys[0]) - dieIfError("problem building createAccount op", err) - - // Submit - resp := submit(client, txe) - - // Inspect and print error - log.Info(resp) -} - -/***** Examples of operation building follow *****/ - -func bumpSequence(source *hProtocol.Account, seqNum int64, signer Account) (string, error) { - bumpSequenceOp := txnbuild.BumpSequence{ - BumpTo: seqNum, - } - - tx, err := txnbuild.NewTransaction( - txnbuild.TransactionParams{ - SourceAccount: source, - IncrementSequenceNum: true, - Operations: []txnbuild.Operation{&bumpSequenceOp}, - BaseFee: txnbuild.MinBaseFee, - Timebounds: txnbuild.NewTimeout(300), - }, - ) - if err != nil { - return "", errors.Wrap(err, "couldn't build transaction") - } - tx, err = tx.Sign(network.TestNetworkPassphrase, signer.Keypair) - if err != nil { - return "", errors.Wrap(err, "couldn't sign transaction") - } - - txeBase64, err := tx.Base64() - if err != nil { - return txeBase64, errors.Wrap(err, "couldn't serialise transaction") - } - return txeBase64, nil -} - -func createAccount(source *hProtocol.Account, dest string, signer Account) (string, error) { - createAccountOp := txnbuild.CreateAccount{ - Destination: dest, - Amount: "100", - } - - tx, err := txnbuild.NewTransaction( - txnbuild.TransactionParams{ - SourceAccount: source, - IncrementSequenceNum: true, - Operations: []txnbuild.Operation{&createAccountOp}, - BaseFee: txnbuild.MinBaseFee, - Timebounds: txnbuild.NewTimeout(300), - }, - ) - if err != nil { - return "", errors.Wrap(err, "couldn't build transaction") - } - tx, err = tx.Sign(network.TestNetworkPassphrase, signer.Keypair) - if err != nil { - return "", errors.Wrap(err, "couldn't sign transaction") - } - - txeBase64, err := tx.Base64() - if err != nil { - return txeBase64, errors.Wrap(err, "couldn't serialise transaction") - } - return txeBase64, nil -} - -func deleteData(source *hProtocol.Account, dataKey string, signer Account) (string, error) { - manageDataOp := txnbuild.ManageData{ - Name: dataKey, - } - - tx, err := txnbuild.NewTransaction( - txnbuild.TransactionParams{ - SourceAccount: source, - IncrementSequenceNum: true, - Operations: []txnbuild.Operation{&manageDataOp}, - BaseFee: txnbuild.MinBaseFee, - Timebounds: txnbuild.NewTimeout(300), - }, - ) - if err != nil { - return "", errors.Wrap(err, "couldn't build transaction") - } - tx, err = tx.Sign(network.TestNetworkPassphrase, signer.Keypair) - if err != nil { - return "", errors.Wrap(err, "couldn't sign transaction") - } - - txeBase64, err := tx.Base64() - if err != nil { - return txeBase64, errors.Wrap(err, "couldn't serialise transaction") - } - return txeBase64, nil -} - -func payment(source *hProtocol.Account, dest, amount string, asset txnbuild.Asset, signer Account) (string, error) { - paymentOp := txnbuild.Payment{ - Destination: dest, - Amount: amount, - Asset: asset, - } - - tx, err := txnbuild.NewTransaction( - txnbuild.TransactionParams{ - SourceAccount: source, - IncrementSequenceNum: true, - Operations: []txnbuild.Operation{&paymentOp}, - BaseFee: txnbuild.MinBaseFee, - Timebounds: txnbuild.NewTimeout(300), - }, - ) - if err != nil { - return "", errors.Wrap(err, "couldn't build transaction") - } - tx, err = tx.Sign(network.TestNetworkPassphrase, signer.Keypair) - if err != nil { - return "", errors.Wrap(err, "couldn't sign transaction") - } - - txeBase64, err := tx.Base64() - if err != nil { - return txeBase64, errors.Wrap(err, "couldn't serialise transaction") - } - return txeBase64, nil -} - -func deleteTrustline(source *hProtocol.Account, asset txnbuild.Asset, signer Account) (string, error) { - deleteTrustline := txnbuild.RemoveTrustlineOp(asset) - - tx, err := txnbuild.NewTransaction( - txnbuild.TransactionParams{ - SourceAccount: source, - IncrementSequenceNum: true, - Operations: []txnbuild.Operation{&deleteTrustline}, - BaseFee: txnbuild.MinBaseFee, - Timebounds: txnbuild.NewTimeout(300), - }, - ) - if err != nil { - return "", errors.Wrap(err, "couldn't build transaction") - } - tx, err = tx.Sign(network.TestNetworkPassphrase, signer.Keypair) - if err != nil { - return "", errors.Wrap(err, "couldn't sign transaction") - } - - txeBase64, err := tx.Base64() - if err != nil { - return txeBase64, errors.Wrap(err, "couldn't serialise transaction") - } - return txeBase64, nil -} - -func deleteOffer(source *hProtocol.Account, offerID int64, signer Account) (string, error) { - deleteOffer, err := txnbuild.DeleteOfferOp(offerID) - if err != nil { - return "", errors.Wrap(err, "building offer") - } - - tx, err := txnbuild.NewTransaction( - txnbuild.TransactionParams{ - SourceAccount: source, - IncrementSequenceNum: true, - Operations: []txnbuild.Operation{&deleteOffer}, - BaseFee: txnbuild.MinBaseFee, - Timebounds: txnbuild.NewTimeout(300), - }, - ) - if err != nil { - return "", errors.Wrap(err, "couldn't build transaction") - } - tx, err = tx.Sign(network.TestNetworkPassphrase, signer.Keypair) - if err != nil { - return "", errors.Wrap(err, "couldn't sign transaction") - } - - txeBase64, err := tx.Base64() - if err != nil { - return txeBase64, errors.Wrap(err, "couldn't serialise transaction") - } - return txeBase64, nil -} - -func mergeAccount(source *hProtocol.Account, destAddress string, signer Account) (string, error) { - accountMerge := txnbuild.AccountMerge{ - Destination: destAddress, - } - - tx, err := txnbuild.NewTransaction( - txnbuild.TransactionParams{ - SourceAccount: source, - IncrementSequenceNum: true, - Operations: []txnbuild.Operation{&accountMerge}, - BaseFee: txnbuild.MinBaseFee, - Timebounds: txnbuild.NewTimeout(300), - }, - ) - if err != nil { - return "", errors.Wrap(err, "couldn't build transaction") - } - tx, err = tx.Sign(network.TestNetworkPassphrase, signer.Keypair) - if err != nil { - return "", errors.Wrap(err, "couldn't sign transaction") - } - - txeBase64, err := tx.Base64() - if err != nil { - return txeBase64, errors.Wrap(err, "couldn't serialise transaction") - } - return txeBase64, nil -} - -// createKeypair constructs a new random keypair, and returns it in a DemoAccount. -func createKeypair() Account { - pair, err := keypair.Random() - if err != nil { - log.Fatal(err) - } - log.Info("Seed:", pair.Seed()) - log.Info("Address:", pair.Address()) - - return Account{ - Seed: pair.Seed(), - Address: pair.Address(), - Keypair: pair, - } -} - -// loadAccounts looks up each account in the provided list and stores the returned information. -func loadAccounts(client *horizonclient.Client, accounts []Account) []Account { - for i, a := range accounts { - accounts[i].HAccount = loadAccount(client, a.Address) - accounts[i].Exists = true - } - - return accounts -} - -// loadAccount is an example of how to get an account's details from Horizon. -func loadAccount(client *horizonclient.Client, address string) *hProtocol.Account { - accountRequest := horizonclient.AccountRequest{AccountID: address} - horizonSourceAccount, err := client.AccountDetail(accountRequest) - if err != nil { - dieIfError(fmt.Sprintf("couldn't get account detail for %s", address), err) - } - - return &horizonSourceAccount -} - -func submit(client *horizonclient.Client, txeBase64 string) (resp hProtocol.Transaction) { - resp, err := client.SubmitTransactionXDR(txeBase64) - if err != nil { - hError := err.(*horizonclient.Error) - err = printHorizonError(hError) - dieIfError("couldn't print Horizon eror", err) - os.Exit(1) - } - - return -} - -func dieIfError(desc string, err error) { - if err != nil { - log.Fatalf("Fatal error (%s): %s", desc, err) - } -} - -// printHorizonError is an example of how to inspect the error returned from Horizon. -func printHorizonError(hError *horizonclient.Error) error { - problem := hError.Problem - log.Println("Error type:", problem.Type) - log.Println("Error title:", problem.Title) - log.Println("Error status:", problem.Status) - log.Println("Error detail:", problem.Detail) - - resultCodes, err := hError.ResultCodes() - if err != nil { - return errors.Wrap(err, "Couldn't read ResultCodes") - } - log.Println("TransactionCode:", resultCodes.TransactionCode) - log.Println("OperationCodes:") - for _, code := range resultCodes.OperationCodes { - log.Println(" ", code) - } - - resultString, err := hError.ResultString() - if err != nil { - return errors.Wrap(err, "Couldn't read ResultString") - } - log.Println("TransactionResult XDR (base 64):", resultString) - - envelope, err := hError.Envelope() - if err != nil { - return errors.Wrap(err, "Couldn't read Envelope") - } - - aid := envelope.SourceAccount().MustEd25519() - decodedAID, err := strkey.Encode(strkey.VersionByteAccountID, aid[:]) - if err != nil { - log.Println("Couldn't decode account ID:", err) - } else { - log.Printf("SourceAccount (%s): %s", envelope.SourceAccount().Type, decodedAID) - } - log.Println("Fee:", envelope.Fee()) - log.Println("SequenceNumber:", envelope.SeqNum()) - log.Println("TimeBounds:", envelope.TimeBounds()) - log.Println("Memo:", envelope.Memo()) - log.Println("Memo.Type:", envelope.Memo().Type) - if envelope.Memo().Type != xdr.MemoTypeMemoNone { - log.Println("Memo.Text:", envelope.Memo().Text) - log.Println("Memo.Id:", envelope.Memo().Id) - log.Println("Memo.Hash:", envelope.Memo().Hash) - log.Println("Memo.RetHash:", envelope.Memo().RetHash) - } - log.Println("Operations:", envelope.Operations()) - - for _, op := range envelope.Operations() { - log.Println("Operations.SourceAccount:", op.SourceAccount) - log.Println("Operations.Body.Type:", op.Body.Type) - } - // TODO is Ext a useful field which we should print? - // log.Println("Ext:", txe.Ext) - - return nil -} diff --git a/services/horizon/internal/txnbuild/create_claimable_balance.go b/services/horizon/internal/txnbuild/create_claimable_balance.go index 61995d1f40..79b868b9ee 100644 --- a/services/horizon/internal/txnbuild/create_claimable_balance.go +++ b/services/horizon/internal/txnbuild/create_claimable_balance.go @@ -1,3 +1,4 @@ +//lint:file-ignore U1001 Ignore all unused code, staticcheck doesn't understand testify/suite package txnbuild import ( diff --git a/services/horizon/internal/txnbuild/end_sponsoring_future_reserves.go b/services/horizon/internal/txnbuild/end_sponsoring_future_reserves.go index a32f7336f6..213c335159 100644 --- a/services/horizon/internal/txnbuild/end_sponsoring_future_reserves.go +++ b/services/horizon/internal/txnbuild/end_sponsoring_future_reserves.go @@ -1,3 +1,4 @@ +//lint:file-ignore U1001 Ignore all unused code, staticcheck doesn't understand testify/suite package txnbuild import ( diff --git a/services/horizon/internal/txnbuild/examplehorizonclient/examplehorizonclient.go b/services/horizon/internal/txnbuild/examplehorizonclient/examplehorizonclient.go deleted file mode 100644 index 12abe3e2e7..0000000000 --- a/services/horizon/internal/txnbuild/examplehorizonclient/examplehorizonclient.go +++ /dev/null @@ -1,67 +0,0 @@ -// Package examplehorizonclient provides a dummy client for use with the GoDoc examples. -package examplehorizonclient - -import ( - hProtocol "github.com/stellar/go/protocols/horizon" -) - -// AccountRequest is a simple mock -type AccountRequest struct { - AccountID string -} - -// Client is a simple mock -type Client struct { -} - -// DefaultTestNetClient is a simple mock -var DefaultTestNetClient = Client{} - -// AccountDetail returns a minimal, static Account object -func (client *Client) AccountDetail(req AccountRequest) (hProtocol.Account, error) { - return hProtocol.Account{ - AccountID: req.AccountID, - Sequence: "3556091187167235", - }, nil -} - -// FeeStats returns mock network fee information -func (client *Client) FeeStats() (hProtocol.FeeStats, error) { - return hProtocol.FeeStats{ - LastLedger: 22606298, - LastLedgerBaseFee: 100, - LedgerCapacityUsage: 0.97, - MaxFee: hProtocol.FeeDistribution{ - Max: 100, - Min: 100, - Mode: 200, - P10: 250, - P20: 300, - P30: 350, - P40: 500, - P50: 600, - P60: 700, - P70: 800, - P80: 900, - P90: 2000, - P95: 3000, - P99: 5000, - }, - FeeCharged: hProtocol.FeeDistribution{ - Max: 100, - Min: 100, - Mode: 100, - P10: 100, - P20: 100, - P30: 100, - P40: 100, - P50: 100, - P60: 100, - P70: 100, - P80: 100, - P90: 100, - P95: 100, - P99: 100, - }, - }, nil -} diff --git a/services/horizon/internal/txnbuild/transaction.go b/services/horizon/internal/txnbuild/transaction.go index cbb5469ca0..836d58ab22 100644 --- a/services/horizon/internal/txnbuild/transaction.go +++ b/services/horizon/internal/txnbuild/transaction.go @@ -367,12 +367,6 @@ func (t *FeeBumpTransaction) Hash(networkStr string) ([32]byte, error) { return network.HashTransactionInEnvelope(t.envelope, networkStr) } -// HashHex returns the network specific hash of this transaction -// encoded as a hexadecimal string. -func (t *FeeBumpTransaction) HashHex(network string) (string, error) { - return hashHex(t.envelope, network) -} - // Sign returns a new FeeBumpTransaction instance which extends the current instance // with additional signatures derived from the given list of keypair instances. func (t *FeeBumpTransaction) Sign(network string, kps ...*keypair.Full) (*FeeBumpTransaction, error) { @@ -387,45 +381,6 @@ func (t *FeeBumpTransaction) Sign(network string, kps ...*keypair.Full) (*FeeBum return newTx, nil } -// SignWithKeyString returns a new FeeBumpTransaction instance which extends the current instance -// with additional signatures derived from the given list of private key strings. -func (t *FeeBumpTransaction) SignWithKeyString(network string, keys ...string) (*FeeBumpTransaction, error) { - kps, err := stringsToKP(keys...) - if err != nil { - return nil, err - } - return t.Sign(network, kps...) -} - -// SignHashX returns a new FeeBumpTransaction instance which extends the current instance -// with HashX signature type. -// See description here: https://www.stellar.org/developers/guides/concepts/multi-sig.html#hashx. -func (t *FeeBumpTransaction) SignHashX(preimage []byte) (*FeeBumpTransaction, error) { - extendedSignatures, err := concatHashX(t.signatures, preimage) - if err != nil { - return nil, err - } - - newTx := new(FeeBumpTransaction) - *newTx = *t - newTx.signatures = extendedSignatures - return newTx, nil -} - -// AddSignatureBase64 returns a new FeeBumpTransaction instance which extends the current instance -// with an additional signature derived from the given base64-encoded signature. -func (t *FeeBumpTransaction) AddSignatureBase64(network, publicKey, signature string) (*FeeBumpTransaction, error) { - extendedSignatures, err := concatSignatureBase64(t.envelope, t.signatures, network, publicKey, signature) - if err != nil { - return nil, err - } - - newTx := new(FeeBumpTransaction) - *newTx = *t - newTx.signatures = extendedSignatures - return newTx, nil -} - // TxEnvelope returns the a xdr.TransactionEnvelope instance which is // equivalent to this transaction. func (t *FeeBumpTransaction) TxEnvelope() (xdr.TransactionEnvelope, error) {