summaryrefslogtreecommitdiff
path: root/cmd/pingpong/runCmd.go
blob: ed834f4add436416dca73e1e843d75abd91e5d70 (plain)
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"github.com/spf13/cobra"

	"github.com/algorand/go-algorand/data/transactions/logic"
	"github.com/algorand/go-algorand/libgoal"
	"github.com/algorand/go-algorand/shared/pingpong"
)

var dataDir string
var srcAddress string
var numAccounts uint32
var minAccountFunds uint64
var maxAmount uint64
var maxFee int64
var minFee uint64
var randomFee, noRandomFee bool
var randomAmount, noRandomAmount bool
var randomDst bool
var delayBetween string
var runTime string
var restTime string
var refreshTime string
var saveConfig bool
var useDefault bool
var quietish bool
var logicProg string
var randomNote bool
var randomLease bool
var txnPerSec uint64
var teal string
var groupSize uint32
var numAsset uint32
var numApp uint32
var numAppOptIn uint32
var appProgOps uint32
var appProgHashes uint32
var appProgHashSize string
var appProgGlobKeys uint32
var appProgLocalKeys uint32
var duration uint32
var rekey bool
var nftAsaPerSecond uint32

func init() {
	rootCmd.AddCommand(runCmd)
	runCmd.PersistentFlags().StringVarP(&dataDir, "datadir", "d", "", "Data directory for the node")

	runCmd.Flags().StringVarP(&srcAddress, "src", "s", "", "Account address to use as funding source for new accounts)")
	runCmd.Flags().Uint32VarP(&numAccounts, "numaccounts", "n", 0, "The number of accounts to include in the transfers")
	runCmd.Flags().Uint64VarP(&maxAmount, "ma", "a", 0, "The (max) amount to be transferred")
	runCmd.Flags().Uint64VarP(&minAccountFunds, "minaccount", "", 0, "The minimum amount to fund a test account with")
	runCmd.Flags().Uint64VarP(&txnPerSec, "tps", "t", 200, "Number of Txn per second that pingpong sends")
	runCmd.Flags().Int64VarP(&maxFee, "mf", "f", -1, "The MAX fee to be used for transactions, a value of '0' tells the server to use a suggested fee.")
	runCmd.Flags().Uint64VarP(&minFee, "minf", "m", 1000, "The MIN fee to be used for randomFee transactions")
	runCmd.Flags().BoolVar(&randomAmount, "ra", false, "Set to enable random amounts (up to maxamount)")
	runCmd.Flags().BoolVar(&noRandomAmount, "nra", false, "Set to disable random amounts")
	runCmd.Flags().BoolVar(&randomFee, "rf", false, "Set to enable random fees (between minf and mf)")
	runCmd.Flags().BoolVar(&noRandomFee, "nrf", false, "Set to disable random fees")
	runCmd.Flags().BoolVar(&randomDst, "rd", false, "Send money to randomly-generated addresses")
	runCmd.Flags().StringVar(&delayBetween, "delay", "", "Delay (ms) between every transaction (0 means none)")
	runCmd.Flags().StringVar(&runTime, "run", "", "Duration of time (seconds) to run transfers before resting (0 means non-stop)")
	runCmd.Flags().StringVar(&restTime, "rest", "", "Duration of time (seconds) to rest between transfer periods (0 means no rest)")
	runCmd.Flags().StringVar(&refreshTime, "refresh", "", "Duration of time (seconds) between refilling accounts with money (0 means no refresh)")
	runCmd.Flags().StringVar(&logicProg, "program", "", "File containing the compiled program to include as a logic sig")
	runCmd.Flags().BoolVar(&saveConfig, "save", false, "Save the effective configuration to disk")
	runCmd.Flags().BoolVar(&useDefault, "reset", false, "Reset to the default configuration (not read from disk)")
	runCmd.Flags().BoolVar(&quietish, "quiet", false, "quietish stdout logging")
	runCmd.Flags().BoolVar(&randomNote, "randomnote", false, "generates a random byte array between 0-1024 bytes long")
	runCmd.Flags().StringVar(&teal, "teal", "", "teal test scenario, can be light, normal, or heavy, this overrides --program")
	runCmd.Flags().Uint32Var(&groupSize, "groupsize", 1, "The number of transactions in each group")
	runCmd.Flags().Uint32Var(&numAsset, "numasset", 0, "The number of assets each account holds")
	runCmd.Flags().Uint32Var(&numApp, "numapp", 0, "The total number of apps to create")
	runCmd.Flags().Uint32Var(&numAppOptIn, "numappoptin", 0, "The number of apps each account opts in to")
	runCmd.Flags().Uint32Var(&appProgOps, "appprogops", 0, "The approximate number of TEAL operations to perform in each ApplicationCall transaction")
	runCmd.Flags().Uint32Var(&appProgHashes, "appproghashes", 0, "The number of hashes to include in the Application")
	runCmd.Flags().StringVar(&appProgHashSize, "appproghashsize", "sha256", "The size of hashes to include in the Application")
	runCmd.Flags().Uint32Var(&appProgGlobKeys, "appproggk", 0, "Number of global state writes in the Application")
	runCmd.Flags().Uint32Var(&appProgLocalKeys, "appproglk", 0, "Number of local state writes in the Application. Number or local keys per account will be appproglk / proto.MaxAppTxnAccounts")
	runCmd.Flags().BoolVar(&randomLease, "randomlease", false, "set the lease to contain a random value")
	runCmd.Flags().BoolVar(&rekey, "rekey", false, "Create RekeyTo transactions. Requires groupsize=2 and any of random flags exc random dst")
	runCmd.Flags().Uint32Var(&duration, "duration", 0, "The number of seconds to run the pingpong test, forever if 0")
	runCmd.Flags().Uint32Var(&nftAsaPerSecond, "nftasapersecond", 0, "The number of NFT-style ASAs to create per second")

}

var runCmd = &cobra.Command{
	Use:   "run",
	Short: "Start running the ping-pong activity",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		// Make a cache dir for wallet handle tokens
		cacheDir, err := ioutil.TempDir("", "pingpong")
		if err != nil {
			reportErrorf("Cannot make temp dir: %v\n", err)
		}

		// Get libgoal Client
		ac, err := libgoal.MakeClient(dataDir, cacheDir, libgoal.FullClient)
		if err != nil {
			panic(err)
		}

		// Prepare configuration
		var cfg pingpong.PpConfig
		cfgPath := filepath.Join(ac.DataDir(), pingpong.ConfigFilename)
		if useDefault {
			cfg = pingpong.DefaultConfig
		} else {
			cfg, err = pingpong.LoadConfigFromFile(cfgPath)
			if err != nil && !os.IsNotExist(err) {
				reportErrorf("Error loading configuration from '%s': %v\n", cfgPath, err)
			}
		}

		if srcAddress != "" {
			cfg.SrcAccount = srcAddress
		}
		if numAccounts > 0 {
			cfg.NumPartAccounts = numAccounts
		}
		if maxAmount > 0 {
			cfg.MaxAmt = maxAmount
		}
		if maxFee >= 0 {
			cfg.MaxFee = uint64(maxFee)
		}
		if minFee > 0 {
			cfg.MinFee = minFee
		}
		if minAccountFunds > 0 {
			cfg.MinAccountFunds = minAccountFunds
		}

		if txnPerSec == 0 {
			reportErrorf("cannot set tps to 0")
		}
		cfg.TxnPerSec = txnPerSec

		if randomFee {
			if cfg.MinFee > cfg.MaxFee {
				reportErrorf("Cannot use randomFee with --minf > --mf.\n")
			}
			cfg.RandomizeFee = true
		}
		if noRandomFee {
			if randomFee {
				reportErrorf("Error --rf and --nrf can't both be specified\n")
			}
			cfg.RandomizeFee = false
		}
		if randomAmount {
			cfg.RandomizeAmt = true
		}
		cfg.RandomLease = randomLease
		if noRandomAmount {
			if randomAmount {
				reportErrorf("Error --ra and --nra can't both be specified\n")
			}
			cfg.RandomizeAmt = false
		}
		cfg.RandomizeDst = randomDst
		cfg.Quiet = quietish
		if delayBetween != "" {
			val, err := strconv.ParseUint(delayBetween, 10, 32)
			if err != nil {
				reportErrorf("Invalid value specified for --delay: %v\n", err)
			}
			cfg.DelayBetweenTxn = time.Duration(uint32(val)) * time.Millisecond
		}
		if runTime != "" {
			val, err := strconv.ParseUint(runTime, 10, 32)
			if err != nil {
				reportErrorf("Invalid value specified for --run: %v\n", err)
			}
			cfg.RunTime = time.Duration(uint32(val)) * time.Second
		}
		if restTime != "" {
			val, err := strconv.ParseUint(restTime, 10, 32)
			if err != nil {
				reportErrorf("Invalid value specified for --rest: %v\n", err)
			}
			cfg.RestTime = time.Duration(uint32(val)) * time.Second
		}
		if refreshTime != "" {
			val, err := strconv.ParseUint(refreshTime, 10, 32)
			if err != nil {
				reportErrorf("Invalid value specified for --refresh: %v\n", err)
			}
			cfg.RefreshTime = time.Duration(uint32(val)) * time.Second
		}
		if duration > 0 {
			cfg.MaxRuntime = time.Duration(uint32(duration)) * time.Second
		}
		if randomNote {
			cfg.RandomNote = true
		}

		if teal != "" {
			logicProg = ""
			var programStr string
			switch teal {
			case "light":
				programStr = tealLight
			case "normal":
				programStr = tealNormal
				bytes, err := base64.StdEncoding.DecodeString("iZWMx72KvU6Bw6sPAWQFL96YH+VMrBA0XKWD9XbZOZI=")
				if err != nil {
					reportErrorf("Internal error, cannot decode.")
				}
				cfg.LogicArgs = [][]byte{bytes}
			case "heavy":
				programStr = tealHeavy
			default:
				reportErrorf("Invalid argument for --teal: %v\n", teal)
			}
			ops, err := logic.AssembleString(programStr)
			if err != nil {
				ops.ReportProblems(teal)
				reportErrorf("Internal error, cannot assemble %v \n", programStr)
			}
			cfg.Program = ops.Program
		}

		if logicProg != "" {
			cfg.Program, err = ioutil.ReadFile(logicProg)
			if err != nil {
				reportErrorf("Error opening logic program: %v\n", err)
			}
		}

		if groupSize > 0 && groupSize <= 16 {
			cfg.GroupSize = groupSize
		} else {
			reportErrorf("Invalid group size: %v\n", groupSize)
		}

		if numAsset <= 1000 {
			cfg.NumAsset = numAsset
		} else {
			reportErrorf("Invalid number of assets: %d, (valid number: 0 - 1000)\n", numAsset)
		}

		cfg.AppProgOps = appProgOps
		cfg.AppProgHashes = appProgHashes
		cfg.AppProgHashSize = appProgHashSize

		if numApp <= 1000 {
			cfg.NumApp = numApp
		} else {
			reportErrorf("Invalid number of apps: %d, (valid number: 0 - 1000)\n", numApp)
		}

		if numAppOptIn > cfg.NumApp {
			reportErrorf("Cannot opt in %d times of %d total apps\n", numAppOptIn, numApp)
		}

		cfg.NumAppOptIn = numAppOptIn

		if appProgGlobKeys > 0 {
			cfg.AppGlobKeys = appProgGlobKeys
		}
		if appProgLocalKeys > 0 {
			cfg.AppLocalKeys = appProgLocalKeys
		}

		if numAsset != 0 && numApp != 0 {
			reportErrorf("only one of numapp and numasset may be specified\n")
		}

		if rekey {
			cfg.Rekey = rekey
			if !cfg.RandomLease && !cfg.RandomNote && !cfg.RandomizeFee && !cfg.RandomizeAmt {
				reportErrorf("RandomNote, RandomLease, RandomizeFee or RandomizeAmt must be used with rekeying\n")
			}
			if cfg.GroupSize != 2 {
				reportErrorf("Rekeying requires txn groups of size 2\n")
			}
		}

		cfg.NftAsaPerSecond = nftAsaPerSecond

		reportInfof("Preparing to initialize PingPong with config:\n")
		cfg.Dump(os.Stdout)

		pps := pingpong.NewPingpong(cfg)

		// Initialize accounts if necessary
		err = pps.PrepareAccounts(ac)
		if err != nil {
			reportErrorf("Error preparing accounts for transfers: %v\n", err)
		}

		if saveConfig {
			cfg.Save(cfgPath)
		}

		reportInfof("Preparing to run PingPong with config:\n")
		cfg.Dump(os.Stdout)

		// Kick off the real processing
		pps.RunPingPong(context.Background(), ac)
	},
}

func reportErrorf(format string, args ...interface{}) {
	fmt.Printf(format, args...)
	os.Exit(1)
}

func reportInfof(format string, args ...interface{}) {
	fmt.Printf(format, args...)
}