summaryrefslogtreecommitdiff
path: root/test/framework/fixtures/goalFixture.go
blob: 69e43e784ab16c2bb8f5867a2f33ce27be314640 (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
// Copyright (C) 2019-2023 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 fixtures

import (
	"fmt"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/algorand/go-algorand/libgoal"
	"github.com/algorand/go-algorand/util"
)

// GoalFixture is a fixture for tests against the goal CLI
type GoalFixture struct {
	RestClientFixture
}

// ErrAccountAlreadyTaken indicates account new is called with a duplicate / existing friendly account name
var ErrAccountAlreadyTaken = fmt.Errorf("account name already taken")

// ErrAccountNewCall indicates the account new REST call failed
var ErrAccountNewCall = fmt.Errorf("account new failed")

const (
	goalCmd = "goal"

	accountCmd       = "account"
	listCmd          = "list"
	newCmd           = "new"
	renameCmd        = "rename"
	importRootKeyCmd = "importrootkey"

	clerkCmd     = "clerk"
	sendCmd      = "send"
	amountParam  = "-a"
	feeParam     = "--fee"
	fromParam    = "-f"
	noteParam    = "-n"
	noteb64Param = "--noteb64"
	toParam      = "-t"

	nodeCmd  = "node"
	startCmd = "start"
	stopCmd  = "stop"

	networkCmd = "network"
	pregenCmd  = "pregen"
	createCmd  = "create"
)

func (f *GoalFixture) executeRawCommand(args ...string) (retStdout string, retStderr string, err error) {
	// Executes a command without a specified data directory
	cmd := filepath.Join(f.binDir, goalCmd)
	retStdout, retStderr, err = util.ExecAndCaptureOutput(cmd, args...)
	retStdout = strings.TrimRight(retStdout, "\n")
	retStderr = strings.TrimRight(retStderr, "\n")
	return
}

func (f *GoalFixture) executeCommand(args ...string) (retStdout string, retStderr string, err error) {
	// We always execute goal against the PrimaryDataDir() instance
	args = append(args, "-d", f.PrimaryDataDir())
	return f.executeRawCommand(args...)
}

// combine the error and the output so that we could return it as a single error object.
func combineExecuteError(retStdout string, retStderr string, err error) error {
	if err == nil {
		return err
	}
	return fmt.Errorf("%v\nStdout:\n%s\nStderr:\n%s", err, retStdout, retStderr)
}

// AccountNew exposes the `goal account new` command
func (f *GoalFixture) AccountNew(name string) (address string, err error) {
	stdout, stderr, err := f.executeCommand(accountCmd, newCmd, name)

	if err != nil {
		if strings.Contains(stderr, "is already taken") {
			return "", ErrAccountAlreadyTaken
		}
		return "", combineExecuteError(stdout, stderr, err)
	}
	valid := strings.HasPrefix(stdout, "Created new account with address")
	if !valid {
		return "", ErrAccountNewCall
	}
	lastSpaceIndex := strings.LastIndexByte(stdout, ' ')
	if lastSpaceIndex < 0 {
		return "", fmt.Errorf("invalid account result: %s", stdout)
	}
	address = string(stdout[lastSpaceIndex+1:])
	return
}

// AccountRename exposes the `goal account rename` command
func (f *GoalFixture) AccountRename(name, newName string) (err error) {
	stdout, stderr, err := f.executeCommand(accountCmd, renameCmd, name, newName)
	if err != nil {
		return combineExecuteError(stdout, stderr, err)
	}

	if strings.Contains(stdout, "Renamed") {
		return nil
	}

	return fmt.Errorf("error processing rename: %s", stderr)
}

// CheckAccountListContainsAccount processes the `goal account list` results and returns true
// if the provided matcher matches one of the results
func (f *GoalFixture) CheckAccountListContainsAccount(matcher func([]string) bool) (bool, error) {
	stdout, stderr, err := f.executeCommand(accountCmd, listCmd)
	if err != nil {
		return false, combineExecuteError(stdout, stderr, err)
	}

	accounts := strings.Split(stdout, "\n")
	if len(accounts) == 0 {
		return false, nil
	}

	for _, row := range accounts {
		elements := strings.Split(row, "\t")
		if len(elements) >= 4 { // Valid Account entries should include 4 components (status, name, address, balance)
			if matcher(elements) {
				return true, nil
			}
		}
	}
	return false, nil
}

// NodeStart exposes the `goal node start` command
func (f *GoalFixture) NodeStart() error {
	stdout, stderr, err := f.executeCommand(nodeCmd, startCmd)
	if err != nil {
		return combineExecuteError(stdout, stderr, err)
	}
	if !strings.Contains(stdout, "Algorand node successfully started") {
		err = fmt.Errorf("failed to start node: %s", stderr)
	}
	return err
}

// NodeStop exposes the `goal node stop` command
func (f *GoalFixture) NodeStop() error {
	stdout, stderr, err := f.executeCommand(nodeCmd, stopCmd)
	if err != nil {
		return combineExecuteError(stdout, stderr, err)
	}
	if !strings.Contains(stdout, "The node was successfully stopped") {
		err = fmt.Errorf("failed to stop node: %s", stderr)
	}
	return err
}

// ClerkSend exposes the `goal clerk send` command with a plaintext note
func (f *GoalFixture) ClerkSend(from, to string, amount, fee int64, note string) (string, error) {
	// Successful send returns response in form of:
	// Sent <amt> algos from account <from> to address <to>, transaction ID: tx-<txID>. Fee set to <fee>
	stdout, stderr, err := f.executeCommand(clerkCmd, sendCmd,
		fromParam, from,
		toParam, to,
		feeParam, strconv.FormatInt(fee, 10),
		amountParam, strconv.FormatInt(amount, 10),
		noteParam, note)
	if err != nil {
		return "", combineExecuteError(stdout, stderr, err)
	}
	return parseClerkSendResponse(stdout)
}

// ClerkSendNoteb64 exposes the `goal clerk send` command but passes the note as base64
func (f *GoalFixture) ClerkSendNoteb64(from, to string, amount, fee int64, noteb64 string) (string, error) {
	// Successful send returns response in form of:
	// Sent <amt> algos from account <from> to address <to>, transaction ID: tx-<txID>. Fee set to <fee>
	stdout, stderr, err := f.executeCommand(clerkCmd, sendCmd,
		fromParam, from,
		toParam, to,
		feeParam, strconv.FormatInt(fee, 10),
		amountParam, strconv.FormatInt(amount, 10),
		noteb64Param, noteb64)
	if err != nil {
		return "", combineExecuteError(stdout, stderr, err)
	}

	return parseClerkSendResponse(stdout)
}

func parseClerkSendResponse(ret string) (txID string, err error) {
	if strings.HasPrefix(ret, "Sent ") {
		txIndex := strings.Index(ret, "ID: ")
		if txIndex > 0 {
			// Extract "tx-<txid>" string
			txID = ret[txIndex+4:]
			txID = txID[:52] // 52 is the len of txid
			return
		}
	}
	err = fmt.Errorf("unable to parse txid from response: %s", ret)
	return
}

// AccountImportRootKey exposes the `goal account importrootkey` command
func (f *GoalFixture) AccountImportRootKey(wallet string, createDefaultUnencrypted bool) (err error) {
	if wallet == "" {
		wallet = string(libgoal.UnencryptedWalletName)
	}
	args := []string{
		accountCmd,
		importRootKeyCmd,
		"-w",
		wallet,
	}
	if createDefaultUnencrypted {
		args = append(args, "-u")
	}
	_, _, err = f.executeCommand(args...)
	return
}

// NetworkPregen exposes the `goal network pregen` command
func (f *GoalFixture) NetworkPregen(template, pregendir string) (stdErr string, err error) {
	args := []string{
		networkCmd,
		pregenCmd,
		"-p",
		pregendir,
	}
	if template != "" {
		args = append(args, "-t", template)
	}
	_, stdErr, err = f.executeRawCommand(args...)
	return
}

// NetworkCreate exposes the `goal network create` command
func (f *GoalFixture) NetworkCreate(networkdir, networkName, template, pregendir string) (err error) {
	args := []string{
		networkCmd,
		createCmd,
		"-r",
		networkdir,
	}
	if networkName != "" {
		args = append(args, "-n", networkName)
	}
	if template != "" {
		args = append(args, "-t", template)
	}
	if pregendir != "" {
		args = append(args, "-p", pregendir)
	}
	_, _, err = f.executeRawCommand(args...)
	return
}

// NetworkStart exposes the `goal network start` command
func (f *GoalFixture) NetworkStart(networkdir string) (err error) {
	args := []string{
		networkCmd,
		startCmd,
		"-r",
		networkdir,
	}
	_, _, err = f.executeRawCommand(args...)
	return
}

// NetworkStop exposes the `goal network stop` command
func (f *GoalFixture) NetworkStop(networkdir string) (err error) {
	args := []string{
		networkCmd,
		stopCmd,
		"-r",
		networkdir,
	}
	_, _, err = f.executeRawCommand(args...)
	return
}