summaryrefslogtreecommitdiff
path: root/cmd/tealdbg/local.go
blob: 6fe2d006a2aa3e44140a7ce4e63eef8ee0b4301f (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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// 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 (
	"fmt"
	"io"
	"log"
	"time"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/data/transactions"
	"github.com/algorand/go-algorand/data/transactions/logic"
	"github.com/algorand/go-algorand/ledger/apply"
	"github.com/algorand/go-algorand/protocol"
)

func protoFromString(protoString string) (name string, proto config.ConsensusParams, err error) {
	if len(protoString) == 0 || protoString == "current" {
		name = string(protocol.ConsensusCurrentVersion)
		proto = config.Consensus[protocol.ConsensusCurrentVersion]
	} else {
		var ok bool
		proto, ok = config.Consensus[protocol.ConsensusVersion(protoString)]
		if !ok {
			err = fmt.Errorf("unknown protocol %s", protoString)
			return
		}
		name = protoString
	}

	return
}

// txnGroupFromParams validates DebugParams.TxnBlob
// DebugParams.TxnBlob parsed as JSON object, JSON array or MessagePack array of transactions.SignedTxn.
// The function returns ready to use txnGroup or an error
func txnGroupFromParams(dp *DebugParams) (txnGroup []transactions.SignedTxn, err error) {
	if len(dp.TxnBlob) == 0 {
		txnGroup = append(txnGroup, transactions.SignedTxn{})
		return
	}

	var data []byte = dp.TxnBlob

	// 1. Attempt json - a single transaction
	var txn transactions.SignedTxn
	err1 := protocol.DecodeJSON(data, &txn)
	if err1 == nil {
		txnGroup = append(txnGroup, txn)
		return
	}

	// 2. Attempt json - array of transactions
	err2 := protocol.DecodeJSON(data, &txnGroup)
	if err2 == nil {
		return
	}

	// 3. Attempt msgp - array of transactions
	dec := protocol.NewDecoderBytes(data)
	for {
		var txn transactions.SignedTxn
		err = dec.Decode(&txn)
		if err == io.EOF {
			err = nil
			break
		}
		if err != nil {
			break
		}
		txnGroup = append(txnGroup, txn)
	}

	// if conversion failed report all intermediate decoding errors
	if err != nil {
		if err1 != nil {
			log.Printf("Decoding as JSON txn failed: %s", err1.Error())
		}
		if err2 != nil {
			log.Printf("Decoding as JSON txn group failed: %s", err2.Error())
		}
	}

	return
}

// balanceRecordsFromParams attempts to parse DebugParams.BalanceBlob as
// JSON object, JSON array or MessagePack array of basics.BalanceRecord
func balanceRecordsFromParams(dp *DebugParams) (records []basics.BalanceRecord, err error) {
	if len(dp.BalanceBlob) == 0 {
		return
	}

	var data []byte = dp.BalanceBlob

	// 1. Attempt json - a single record
	var record basics.BalanceRecord
	err1 := protocol.DecodeJSON(data, &record)
	if err1 == nil {
		records = append(records, record)
		return
	}

	// 2. Attempt json - a array of records
	err2 := protocol.DecodeJSON(data, &records)
	if err2 == nil {
		return
	}

	// 3. Attempt msgp - a array of records
	dec := protocol.NewDecoderBytes(data)
	for {
		var record basics.BalanceRecord
		err = dec.Decode(&record)
		if err == io.EOF {
			err = nil
			break
		}
		if err != nil {
			break
		}
		records = append(records, record)
	}

	// if conversion failed report all intermediate decoding errors
	if err != nil {
		if err1 != nil {
			log.Printf("Decoding as JSON record failed: %s", err1.Error())
		}
		if err2 != nil {
			log.Printf("Decoding as JSON array of records failed: %s", err2.Error())
		}
	}

	return
}

type evalResult struct {
	pass bool
	err  error
}

// AppState encapsulates information about execution of stateful teal program
type AppState struct {
	appIdx  basics.AppIndex
	schemas basics.StateSchemas
	global  map[basics.AppIndex]basics.TealKeyValue
	locals  map[basics.Address]map[basics.AppIndex]basics.TealKeyValue
}

func (a *AppState) clone() (b AppState) {
	b.appIdx = a.appIdx
	b.global = make(map[basics.AppIndex]basics.TealKeyValue, len(a.global))
	for aid, tkv := range a.global {
		b.global[aid] = tkv.Clone()
	}
	b.locals = make(map[basics.Address]map[basics.AppIndex]basics.TealKeyValue, len(a.locals))
	for addr, local := range a.locals {
		b.locals[addr] = make(map[basics.AppIndex]basics.TealKeyValue, len(local))
		for aid, tkv := range local {
			b.locals[addr][aid] = tkv.Clone()
		}
	}
	return
}

func (a *AppState) empty() bool {
	return a.appIdx == 0 && len(a.global) == 0 && len(a.locals) == 0
}

type modeType int

func (m modeType) String() string {
	switch m {
	case modeLogicsig:
		return "logicsig"
	case modeStateful:
		return "stateful"
	default:
		return "unknown"
	}
}

const (
	modeUnknown modeType = iota
	modeLogicsig
	modeStateful
)

// evaluation is a description of a single debugger run
type evaluation struct {
	program         []byte
	source          string
	offsetToLine    map[int]int
	name            string
	groupIndex      uint64
	pastSideEffects []logic.EvalSideEffects
	mode            modeType
	aidx            basics.AppIndex
	ba              apply.Balances
	result          evalResult
	states          AppState
}

func (e *evaluation) eval(ep logic.EvalParams) (pass bool, err error) {
	if e.mode == modeStateful {
		pass, _, err = e.ba.StatefulEval(ep, e.aidx, e.program)
		return
	}
	return logic.Eval(e.program, ep)
}

// LocalRunner runs local eval
type LocalRunner struct {
	debugger  *Debugger
	proto     config.ConsensusParams
	protoName string
	txnGroup  []transactions.SignedTxn
	runs      []evaluation
}

func makeAppState() (states AppState) {
	states.global = make(map[basics.AppIndex]basics.TealKeyValue)
	states.locals = make(map[basics.Address]map[basics.AppIndex]basics.TealKeyValue)
	return
}

// MakeLocalRunner creates LocalRunner
func MakeLocalRunner(debugger *Debugger) *LocalRunner {
	r := new(LocalRunner)
	r.debugger = debugger
	return r
}

func determineEvalMode(program []byte, modeIn string) (mode modeType, err error) {
	switch modeIn {
	case "signature":
		mode = modeLogicsig
	case "application":
		mode = modeStateful
	case "auto":
		var hasStateful bool
		hasStateful, err = logic.HasStatefulOps(program)
		if err != nil {
			return
		}
		if hasStateful {
			mode = modeStateful
		} else {
			mode = modeLogicsig
		}
	default:
		err = fmt.Errorf("unknown run mode")
	}
	return
}

// Setup validates input params and resolves inputs into canonical balance record structures.
// Programs for execution are discovered in the following way:
// - Sources from command line file names.
// - Programs mentioned in transaction group txnGroup.
// - if DryrunRequest present and no sources or transaction group set in command line then:
//   1. DryrunRequest.Sources are expanded to DryrunRequest.Apps or DryrunRequest.Txns.
//   2. DryrunRequest.Apps are expanded into DryrunRequest.Txns.
//   3. txnGroup is set to DryrunRequest.Txns
// Application search by id:
//  - Balance records from CLI or DryrunRequest.Accounts
//  - If no balance records set in CLI then DryrunRequest.Accounts and DryrunRequest.Apps are used.
//    In this case Accounts data is used as a base for balance records creation,
//    and Apps supply updates to AppParams field.
func (r *LocalRunner) Setup(dp *DebugParams) (err error) {
	ddr, err := ddrFromParams(dp)
	if err != nil {
		return
	}

	protoString := ddr.ProtocolVersion
	if len(dp.Proto) != 0 {
		protoString = dp.Proto
	}
	r.protoName, r.proto, err = protoFromString(protoString)
	if err != nil {
		return
	}

	log.Printf("Using proto: %s", r.protoName)

	r.txnGroup = ddr.Txns
	if len(dp.TxnBlob) != 0 || len(r.txnGroup) == 0 {
		r.txnGroup, err = txnGroupFromParams(dp)
		if err != nil {
			return
		}
	}

	// if no sources provided, check dryrun request object
	if len(dp.ProgramBlobs) == 0 && len(ddr.Sources) > 0 {
		err = ddr.ExpandSources()
		if err != nil {
			return
		}
	}

	var records []basics.BalanceRecord
	if len(dp.BalanceBlob) > 0 {
		records, err = balanceRecordsFromParams(dp)
	} else {
		records, err = balanceRecordsFromDdr(&ddr)
	}
	if err != nil {
		return
	}

	balances := make(map[basics.Address]basics.AccountData)
	for _, record := range records {
		balances[record.Addr] = record.AccountData
	}

	if dp.Round == 0 && ddr.Round != 0 {
		dp.Round = ddr.Round
	}

	if dp.LatestTimestamp == 0 && ddr.LatestTimestamp != 0 {
		dp.LatestTimestamp = int64(ddr.LatestTimestamp)
	}

	if dp.PastSideEffects == nil {
		dp.PastSideEffects = logic.MakePastSideEffects(len(r.txnGroup))
	} else if len(dp.PastSideEffects) != len(r.txnGroup) {
		err = fmt.Errorf(
			"invalid past side effects slice with length %d should match group length of %d txns",
			len(dp.PastSideEffects),
			len(r.txnGroup),
		)
		return
	}

	// if program(s) specified then run from it
	if len(dp.ProgramBlobs) > 0 {
		if len(r.txnGroup) == 1 && dp.GroupIndex != 0 {
			err = fmt.Errorf("invalid group index %d for a single transaction", dp.GroupIndex)
			return
		}
		if len(r.txnGroup) > 0 && dp.GroupIndex >= len(r.txnGroup) {
			err = fmt.Errorf("invalid group index %d for a txn in a transaction group of %d", dp.GroupIndex, len(r.txnGroup))
			return
		}

		r.runs = make([]evaluation, len(dp.ProgramBlobs))
		for i, data := range dp.ProgramBlobs {
			r.runs[i].program = data
			if IsTextFile(data) {
				source := string(data)
				ops, err := logic.AssembleString(source)
				if ops.Version > r.proto.LogicSigVersion {
					return fmt.Errorf("program version (%d) is beyond the maximum supported protocol version (%d)", ops.Version, r.proto.LogicSigVersion)
				}
				if err != nil {
					errorLines := ""
					for _, lineError := range ops.Errors {
						errorLines = fmt.Sprintf("%s\n%s", errorLines, lineError.Error())
					}
					if errorLines != "" {
						return fmt.Errorf("%w:%s", err, errorLines)
					}
					return err
				}
				r.runs[i].program = ops.Program
				if !dp.DisableSourceMap {
					r.runs[i].offsetToLine = ops.OffsetToLine
					r.runs[i].source = source
				}
			}
			r.runs[i].groupIndex = uint64(dp.GroupIndex)
			r.runs[i].pastSideEffects = dp.PastSideEffects
			r.runs[i].name = dp.ProgramNames[i]

			var mode modeType
			mode, err = determineEvalMode(r.runs[i].program, dp.RunMode)
			if err != nil {
				return
			}
			log.Printf("Run mode: %s", mode.String())
			r.runs[i].mode = mode
			if mode == modeStateful {
				var b apply.Balances
				var states AppState
				txn := r.txnGroup[dp.GroupIndex]
				appIdx := txn.Txn.ApplicationID
				if appIdx == 0 {
					appIdx = basics.AppIndex(dp.AppID)
				}

				b, states, err = makeBalancesAdapter(
					balances, r.txnGroup, dp.GroupIndex,
					r.protoName, dp.Round, dp.LatestTimestamp, appIdx,
					dp.Painless, dp.IndexerURL, dp.IndexerToken,
				)
				if err != nil {
					return
				}

				r.runs[i].aidx = appIdx
				r.runs[i].ba = b
				r.runs[i].states = states
			}
		}
		return nil
	}

	r.runs = nil
	// otherwise, if no program(s) set, check transactions for TEAL programs
	for gi, stxn := range r.txnGroup {
		// make a new ledger per possible execution since it requires a current group index
		if len(stxn.Lsig.Logic) > 0 {
			run := evaluation{
				program:    stxn.Lsig.Logic,
				groupIndex: uint64(gi),
				mode:       modeLogicsig,
			}
			r.runs = append(r.runs, run)
		} else if stxn.Txn.Type == protocol.ApplicationCallTx {
			var b apply.Balances
			var states AppState
			appIdx := stxn.Txn.ApplicationID
			if appIdx == 0 { // app create, use ApprovalProgram from the transaction
				if len(stxn.Txn.ApprovalProgram) > 0 {
					appIdx = basics.AppIndex(dp.AppID)
					b, states, err = makeBalancesAdapter(
						balances, r.txnGroup, gi,
						r.protoName, dp.Round, dp.LatestTimestamp,
						appIdx, dp.Painless, dp.IndexerURL, dp.IndexerToken,
					)
					if err != nil {
						return
					}
					run := evaluation{
						program:         stxn.Txn.ApprovalProgram,
						groupIndex:      uint64(gi),
						pastSideEffects: dp.PastSideEffects,
						mode:            modeStateful,
						aidx:            appIdx,
						ba:              b,
						states:          states,
					}
					r.runs = append(r.runs, run)
				}
			} else {
				// attempt to find this appIdx in balance records provided
				// and error if it is not there
				found := false
				for _, rec := range records {
					for a, ap := range rec.AppParams {
						if a == appIdx {
							var program []byte
							if stxn.Txn.OnCompletion == transactions.ClearStateOC {
								program = ap.ClearStateProgram
							} else {
								program = ap.ApprovalProgram
							}
							if len(program) == 0 {
								err = fmt.Errorf("empty program found for app idx %d", appIdx)
								return
							}
							b, states, err = makeBalancesAdapter(
								balances, r.txnGroup, gi,
								r.protoName, dp.Round, dp.LatestTimestamp,
								appIdx, dp.Painless, dp.IndexerURL, dp.IndexerToken,
							)
							if err != nil {
								return
							}
							run := evaluation{
								program:         program,
								groupIndex:      uint64(gi),
								pastSideEffects: dp.PastSideEffects,
								mode:            modeStateful,
								aidx:            appIdx,
								ba:              b,
								states:          states,
							}
							r.runs = append(r.runs, run)
							found = true
							break
						}
					}
				}
				if !found {
					err = fmt.Errorf("no program found for app idx %d", appIdx)
					return
				}
			}
		}
	}

	if len(r.runs) == 0 {
		err = fmt.Errorf("no programs found in transactions")
	}

	return
}

// RunAll runs all the programs
func (r *LocalRunner) RunAll() error {
	if len(r.runs) < 1 {
		return fmt.Errorf("no program to debug")
	}

	failed := 0
	start := time.Now()
	for _, run := range r.runs {
		r.debugger.SaveProgram(run.name, run.program, run.source, run.offsetToLine, run.states)

		ep := logic.EvalParams{
			Proto:           &r.proto,
			Debugger:        r.debugger,
			Txn:             &r.txnGroup[groupIndex],
			TxnGroup:        r.txnGroup,
			GroupIndex:      run.groupIndex,
			PastSideEffects: run.pastSideEffects,
			Specials:        &transactions.SpecialAddresses{},
		}

		run.result.pass, run.result.err = run.eval(ep)
		if run.result.err != nil {
			failed++
		}
	}
	elapsed := time.Since(start)
	if failed == len(r.runs) && elapsed < time.Second {
		return fmt.Errorf("all %d program(s) failed in less than a second, invocation error?", failed)
	}
	return nil
}

// Run starts the first program in list
func (r *LocalRunner) Run() (bool, error) {
	if len(r.runs) < 1 {
		return false, fmt.Errorf("no program to debug")
	}

	run := r.runs[0]

	ep := logic.EvalParams{
		Proto:           &r.proto,
		Txn:             &r.txnGroup[groupIndex],
		TxnGroup:        r.txnGroup,
		GroupIndex:      run.groupIndex,
		PastSideEffects: run.pastSideEffects,
		Specials:        &transactions.SpecialAddresses{},
	}

	// Workaround for Go's nil/empty interfaces nil check after nil assignment, i.e.
	// r.debugger = nil
	// ep.Debugger = r.debugger
	// if ep.Debugger != nil // FALSE
	if r.debugger != nil {
		r.debugger.SaveProgram(run.name, run.program, run.source, run.offsetToLine, run.states)
		ep.Debugger = r.debugger
	}

	return run.eval(ep)
}