-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinit_friendbot.go
More file actions
192 lines (173 loc) · 6.75 KB
/
init_friendbot.go
File metadata and controls
192 lines (173 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/stellar/friendbot/internal"
"github.com/stellar/friendbot/internal/horizonnetworkclient"
"github.com/stellar/friendbot/internal/rpcnetworkclient"
"github.com/stellar/go-stellar-sdk/clients/horizonclient"
"github.com/stellar/go-stellar-sdk/keypair"
"github.com/stellar/go-stellar-sdk/strkey"
"github.com/stellar/go-stellar-sdk/support/errors"
"github.com/stellar/go-stellar-sdk/txnbuild"
)
func initFriendbot(cfg Config, secrets Secrets) (*internal.Bot, error) {
if secrets.FriendbotSecret == "" || cfg.NetworkPassphrase == "" || cfg.StartingBalance == "" || cfg.NumMinions < 0 {
return nil, errors.New("invalid input param(s)")
}
// Guarantee that friendbotSecret is a seed, if not blank.
strkey.MustDecode(strkey.VersionByteSeed, secrets.FriendbotSecret)
networkClient, err := newNetworkClient(cfg)
if err != nil {
return nil, err
}
botKP, err := keypair.Parse(secrets.FriendbotSecret)
if err != nil {
return nil, errors.Wrap(err, "parsing bot keypair")
}
// Casting from the interface type will work, since we
// already confirmed that friendbotSecret is a seed.
botKeypair := botKP.(*keypair.Full)
botAccount := internal.Account{AccountID: botKeypair.Address()}
// set default values
minionBalance := "101.00"
numMinions := cfg.NumMinions
if numMinions == 0 {
numMinions = 1000
}
minionBatchSize := cfg.MinionBatchSize
if minionBatchSize == 0 {
minionBatchSize = 50
}
submitTxRetriesAllowed := cfg.SubmitTxRetriesAllowed
if submitTxRetriesAllowed == 0 {
submitTxRetriesAllowed = 5
}
log.Printf("Found all valid params, now creating %d minions", numMinions)
minions, err := createMinionAccounts(botAccount, botKeypair, cfg.NetworkPassphrase, cfg.StartingBalance, minionBalance, numMinions, minionBatchSize, submitTxRetriesAllowed, cfg.BaseFee, networkClient)
if err != nil && len(minions) == 0 {
return nil, errors.Wrap(err, "creating minion accounts")
}
log.Printf("Adding %d minions to friendbot", len(minions))
// Validate that contract address funding is only enabled when using RPC
if cfg.FundContractAddresses && !networkClient.SupportsContractAddresses() {
return nil, errors.New("fund_contract_addresses is enabled but the network client does not support contract addresses; configure rpc_url instead of horizon_url to fund contract addresses")
}
return &internal.Bot{
Minions: minions,
NetworkClient: networkClient,
FundContractAddresses: cfg.FundContractAddresses,
}, nil
}
func newNetworkClient(cfg Config) (internal.NetworkClient, error) {
if cfg.HorizonURL != "" && cfg.RPCURL != "" {
return nil, errors.New("only one of horizon_url or rpc_url should be provided, not both")
}
if cfg.RPCURL != "" {
return rpcnetworkclient.NewNetworkClient(cfg.RPCURL, http.DefaultClient, cfg.NetworkPassphrase), nil
}
if cfg.HorizonURL != "" {
return horizonnetworkclient.NewNetworkClient(&horizonclient.Client{
HorizonURL: cfg.HorizonURL,
HTTP: http.DefaultClient,
AppName: "friendbot",
}), nil
}
return nil, errors.New("either horizon_url or rpc_url must be provided")
}
func createMinionAccounts(botAccount internal.Account, botKeypair *keypair.Full, networkPassphrase, newAccountBalance, minionBalance string,
numMinions, minionBatchSize, submitTxRetriesAllowed int, baseFee int64, networkClient internal.NetworkClient) ([]internal.Minion, error) {
var minions []internal.Minion
numRemainingMinions := numMinions
// Allow retries to account for testnet congestion
currentSubmitTxRetry := 0
for numRemainingMinions > 0 {
var (
newMinions []internal.Minion
ops []txnbuild.Operation
)
// Refresh the sequence number before submitting a new transaction.
rerr := botAccount.RefreshSequenceNumber(context.Background(), networkClient)
if rerr != nil {
return minions, errors.Wrap(rerr, "refreshing bot seqnum")
}
// The tx will create min(numRemainingMinions, minionBatchSize) Minion accounts.
numCreateMinions := minionBatchSize
if numRemainingMinions < minionBatchSize {
numCreateMinions = numRemainingMinions
}
log.Printf("Creating %d new minion accounts", numCreateMinions)
for i := 0; i < numCreateMinions; i++ {
minionKeypair, err := keypair.Random()
if err != nil {
return minions, errors.Wrap(err, "making keypair")
}
newMinions = append(newMinions, internal.Minion{
Account: internal.Account{AccountID: minionKeypair.Address()},
Keypair: minionKeypair,
BotAccount: botAccount,
BotKeypair: botKeypair,
NetworkClient: networkClient,
Network: networkPassphrase,
StartingBalance: newAccountBalance,
SubmitTransaction: internal.SubmitTransaction,
CheckSequenceRefresh: internal.CheckSequenceRefresh,
CheckAccountExists: internal.CheckAccountExists,
BaseFee: baseFee,
})
ops = append(ops, &txnbuild.CreateAccount{
Destination: minionKeypair.Address(),
Amount: minionBalance,
})
}
// Build and submit batched account creation tx.
tx, err := txnbuild.NewTransaction(
txnbuild.TransactionParams{
SourceAccount: botAccount,
IncrementSequenceNum: true,
Operations: ops,
BaseFee: txnbuild.MinBaseFee,
Preconditions: txnbuild.Preconditions{TimeBounds: txnbuild.NewTimeout(300)},
},
)
if err != nil {
return minions, errors.Wrap(err, "unable to build tx")
}
tx, err = tx.Sign(networkPassphrase, botKeypair)
if err != nil {
return minions, errors.Wrap(err, "unable to sign tx")
}
txe, err := tx.Base64()
if err != nil {
return minions, errors.Wrap(err, "unable to serialize tx")
}
err = networkClient.SubmitTransaction(context.Background(), txe)
if err != nil {
switch e := err.(type) {
case internal.NetworkError:
// If we hit an error here due to network congestion, or a bad seq on
// the source account, try again until we hit max # of retries allowed
if e.IsTimeout() || e.IsBadSequence() {
err = errors.Wrap(err, "submitting create accounts tx")
if currentSubmitTxRetry >= submitTxRetriesAllowed {
return minions, errors.Wrap(err, fmt.Sprintf("after retrying %d times", currentSubmitTxRetry))
}
log.Println(err)
log.Println("trying again to submit create accounts tx")
currentSubmitTxRetry += 1
continue
}
return minions, errors.Wrap(err, "submitting create accounts tx")
}
return minions, errors.Wrap(err, "submitting create accounts tx")
}
currentSubmitTxRetry = 0
// Process successful create accounts tx.
numRemainingMinions -= numCreateMinions
minions = append(minions, newMinions...)
log.Printf("Submitted create accounts tx for %d minions successfully", numCreateMinions)
}
return minions, nil
}