summaryrefslogtreecommitdiff
path: root/data/transactions/logic/mocktracer/scenarios.go
blob: 09a6a3a2d016d94d3b959f8bfea1b0205b353a7c (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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
// Copyright (C) 2019-2024 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 mocktracer

import (
	"encoding/hex"
	"fmt"
	"math"

	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/data/bookkeeping"
	"github.com/algorand/go-algorand/data/transactions"
	"github.com/algorand/go-algorand/data/transactions/logic"
	"github.com/algorand/go-algorand/data/txntest"
	"github.com/algorand/go-algorand/ledger/ledgercore"
	"github.com/algorand/go-algorand/protocol"
)

const programTemplate string = `#pragma version 6
pushbytes "a"
log

%s

itxn_begin
pushint 6 // appl
itxn_field TypeEnum
pushint 0 // NoOp
itxn_field OnCompletion
pushbytes %s
itxn_field ApprovalProgram
pushbytes 0x068101 // #pragma version 6; int 1;
itxn_field ClearStateProgram
itxn_submit

pushbytes "b"
log

%s

itxn_begin
pushint 1 // pay
itxn_field TypeEnum
pushint %d
itxn_field Amount
global CurrentApplicationAddress
itxn_field Receiver
itxn_next
pushint 1 // pay
itxn_field TypeEnum
pushint %d
itxn_field Amount
global CurrentApplicationAddress
itxn_field Receiver
itxn_submit

pushbytes "c"
log

%s`

func fillProgramTemplate(beforeInnersOps, innerApprovalProgram, betweenInnersOps string, innerPay1Amount, innerPay2Amount uint64, afterInnersOps string) string {
	return fmt.Sprintf(programTemplate, beforeInnersOps, innerApprovalProgram, betweenInnersOps, innerPay1Amount, innerPay2Amount, afterInnersOps)
}

// TestScenarioInfo holds arguments used to call a TestScenarioGenerator
type TestScenarioInfo struct {
	CallingTxn     transactions.Transaction
	SenderData     ledgercore.AccountData
	AppAccountData ledgercore.AccountData
	FeeSinkData    ledgercore.AccountData
	FeeSinkAddr    basics.Address
	MinFee         basics.MicroAlgos
	CreatedAppID   basics.AppIndex
	BlockHeader    bookkeeping.BlockHeader
	PrevTimestamp  int64
}

func expectedApplyDataAndStateDelta(info TestScenarioInfo, appCallProgram string, innerProgramBytes []byte) (transactions.ApplyData, ledgercore.StateDelta, ledgercore.StateDelta, ledgercore.StateDelta, ledgercore.StateDelta) {
	expectedInnerAppCall := txntest.Txn{
		Type:   protocol.ApplicationCallTx,
		Sender: info.CreatedAppID.Address(),
		ApprovalProgram: `#pragma version 6
pushbytes "x"
log
pushint 1`,
		ClearStateProgram: `#pragma version 6
pushint 1`,

		FirstValid: info.CallingTxn.FirstValid,
		LastValid:  info.CallingTxn.LastValid,
		Fee:        info.MinFee,
	}
	expectedInnerAppCallAD := transactions.ApplyData{
		ApplicationID: info.CreatedAppID + 1,
		EvalDelta: transactions.EvalDelta{
			GlobalDelta: basics.StateDelta{},
			LocalDeltas: map[uint64]basics.StateDelta{},
			Logs:        []string{"x"},
		},
	}
	expectedInnerPay1 := txntest.Txn{
		Type:     protocol.PaymentTx,
		Sender:   info.CreatedAppID.Address(),
		Receiver: info.CreatedAppID.Address(),
		Amount:   1,

		FirstValid: info.CallingTxn.FirstValid,
		LastValid:  info.CallingTxn.LastValid,
		Fee:        info.MinFee,
	}
	expectedInnerPay1AD := transactions.ApplyData{}
	expectedInnerPay2 := txntest.Txn{
		Type:     protocol.PaymentTx,
		Sender:   info.CreatedAppID.Address(),
		Receiver: info.CreatedAppID.Address(),
		Amount:   2,

		FirstValid: info.CallingTxn.FirstValid,
		LastValid:  info.CallingTxn.LastValid,
		Fee:        info.MinFee,
	}
	expectedInnerPay2AD := transactions.ApplyData{}

	expectedAD := transactions.ApplyData{
		ApplicationID: info.CreatedAppID,
		EvalDelta: transactions.EvalDelta{
			GlobalDelta: basics.StateDelta{},
			LocalDeltas: map[uint64]basics.StateDelta{},
			InnerTxns: []transactions.SignedTxnWithAD{
				{
					SignedTxn: expectedInnerAppCall.SignedTxn(),
					ApplyData: expectedInnerAppCallAD,
				},
				{
					SignedTxn: expectedInnerPay1.SignedTxn(),
					ApplyData: expectedInnerPay1AD,
				},
				{
					SignedTxn: expectedInnerPay2.SignedTxn(),
					ApplyData: expectedInnerPay2AD,
				},
			},
			Logs: []string{"a", "b", "c"},
		},
	}

	ops, err := logic.AssembleString(appCallProgram)
	if err != nil {
		panic(err)
	}

	expectedSenderData := info.SenderData
	expectedSenderData.MicroAlgos.Raw -= info.CallingTxn.Fee.Raw
	expectedSenderData.TotalAppParams++
	expectedFeeSinkData := info.FeeSinkData
	expectedFeeSinkData.MicroAlgos.Raw += info.CallingTxn.Fee.Raw

	expectedDeltaCallingTxn := ledgercore.StateDelta{
		Accts: ledgercore.AccountDeltas{
			Accts: []ledgercore.BalanceRecord{
				{
					Addr:        info.CallingTxn.Sender,
					AccountData: expectedSenderData,
				},
				{
					Addr:        info.FeeSinkAddr,
					AccountData: expectedFeeSinkData,
				},
			},
			AppResources: []ledgercore.AppResourceRecord{
				{
					Aidx: info.CreatedAppID,
					Addr: info.CallingTxn.Sender,
					Params: ledgercore.AppParamsDelta{
						Params: &basics.AppParams{
							ApprovalProgram:   ops.Program,
							ClearStateProgram: info.CallingTxn.ClearStateProgram,
							StateSchemas: basics.StateSchemas{
								LocalStateSchema:  info.CallingTxn.LocalStateSchema,
								GlobalStateSchema: info.CallingTxn.GlobalStateSchema,
							},
							ExtraProgramPages: info.CallingTxn.ExtraProgramPages,
						},
					},
				},
			},
		},
		Creatables: map[basics.CreatableIndex]ledgercore.ModifiedCreatable{
			basics.CreatableIndex(info.CreatedAppID): {
				Ctype:   basics.AppCreatable,
				Created: true,
				Creator: info.CallingTxn.Sender,
			},
		},
		Txids: map[transactions.Txid]ledgercore.IncludedTransactions{
			// Cannot call info.CallingTxn.ID() yet, since the txn and its group are not yet final. Instead,
			// use the Txid zero value as a placeholder. It's up to the caller to update this if they need it.
			{}: {
				LastValid: info.CallingTxn.LastValid,
				Intra:     0,
			},
		},
		Hdr:           &info.BlockHeader,
		PrevTimestamp: info.PrevTimestamp,
	}
	expectedDeltaCallingTxn.Hydrate()

	expectedAppAccountData := info.AppAccountData
	expectedAppAccountData.TotalAppParams++
	expectedAppAccountData.MicroAlgos.Raw -= info.MinFee.Raw
	expectedFeeSinkData.MicroAlgos.Raw += info.MinFee.Raw

	expectedDeltaInnerAppCall := ledgercore.StateDelta{
		Accts: ledgercore.AccountDeltas{
			Accts: []ledgercore.BalanceRecord{
				{
					Addr:        info.CreatedAppID.Address(),
					AccountData: expectedAppAccountData,
				},
				{
					Addr:        info.FeeSinkAddr,
					AccountData: expectedFeeSinkData,
				},
			},
			AppResources: []ledgercore.AppResourceRecord{
				{
					Aidx: info.CreatedAppID + 1,
					Addr: info.CreatedAppID.Address(),
					Params: ledgercore.AppParamsDelta{
						Params: &basics.AppParams{
							ApprovalProgram:   innerProgramBytes,
							ClearStateProgram: []byte{0x06, 0x81, 0x01}, // #pragma version 6; int 1;
						},
					},
				},
			},
		},
		Creatables: map[basics.CreatableIndex]ledgercore.ModifiedCreatable{
			basics.CreatableIndex(info.CreatedAppID + 1): {
				Ctype:   basics.AppCreatable,
				Created: true,
				Creator: info.CreatedAppID.Address(),
			},
		},
		Hdr:           &info.BlockHeader,
		PrevTimestamp: info.PrevTimestamp,
	}
	expectedDeltaInnerAppCall.Hydrate()

	expectedAppAccountData.MicroAlgos.Raw -= info.MinFee.Raw
	expectedFeeSinkData.MicroAlgos.Raw += info.MinFee.Raw

	expectedDeltaInnerPay1 := ledgercore.StateDelta{
		Accts: ledgercore.AccountDeltas{
			Accts: []ledgercore.BalanceRecord{
				{
					Addr:        info.CreatedAppID.Address(),
					AccountData: expectedAppAccountData,
				},
				{
					Addr:        info.FeeSinkAddr,
					AccountData: expectedFeeSinkData,
				},
			},
		},
		Hdr:           &info.BlockHeader,
		PrevTimestamp: info.PrevTimestamp,
	}
	expectedDeltaInnerPay1.Hydrate()

	expectedAppAccountData.MicroAlgos.Raw -= info.MinFee.Raw
	expectedFeeSinkData.MicroAlgos.Raw += info.MinFee.Raw

	expectedDeltaInnerPay2 := ledgercore.StateDelta{
		Accts: ledgercore.AccountDeltas{
			Accts: []ledgercore.BalanceRecord{
				{
					Addr:        info.CreatedAppID.Address(),
					AccountData: expectedAppAccountData,
				},
				{
					Addr:        info.FeeSinkAddr,
					AccountData: expectedFeeSinkData,
				},
			},
		},
		Hdr:           &info.BlockHeader,
		PrevTimestamp: info.PrevTimestamp,
	}
	expectedDeltaInnerPay2.Hydrate()

	return expectedAD, expectedDeltaCallingTxn, expectedDeltaInnerAppCall, expectedDeltaInnerPay1, expectedDeltaInnerPay2
}

// TestScenarioOutcome represents an outcome of a TestScenario
type TestScenarioOutcome int

const (
	// ApprovalOutcome indicates the scenario should approve the program
	ApprovalOutcome TestScenarioOutcome = iota
	// RejectionOutcome indicates the scenario should reject the program
	RejectionOutcome
	// ErrorOutcome indicates the scenario should error during the program
	ErrorOutcome
)

// TestScenario represents a testing scenario. See GetTestScenarios for more details.
type TestScenario struct {
	Outcome              TestScenarioOutcome
	Program              string
	ExpectedError        string
	FailedAt             []uint64
	ExpectedEvents       []Event
	ExpectedSimulationAD transactions.ApplyData
	ExpectedStateDelta   ledgercore.StateDelta
	AppBudgetAdded       uint64
	AppBudgetConsumed    uint64
	TxnAppBudgetConsumed []uint64
}

// TestScenarioGenerator is a function which instantiates a TestScenario
type TestScenarioGenerator func(info TestScenarioInfo) TestScenario

// GetTestScenarios returns scenarios for testing code that invokes a logic.EvalTracer. These
// scenarios are all app calls which invoke inner transactions under various failure conditions.
// The scenarios follow this format:
//
//  1. An app call transaction that spawns inners. They are:
//     a. A basic app call transaction
//     b. A payment transaction [grouped with c]
//     c. A payment transaction [grouped with b]
//
// The scenarios differ by where they fail when attempting to execute that app call. Failures are
// possible during each inner transaction, as well as before all inners, between the two inner
// groups, and after all inners. For app call failures, there are scenarios for both rejection and
// runtime errors, which should invoke tracer hooks slightly differently.
func GetTestScenarios() map[string]TestScenarioGenerator {
	successInnerProgramBytes := []byte{0x06, 0x80, 0x01, 0x78, 0xb0, 0x81, 0x01} // #pragma version 6; pushbytes "x"; log; pushint 1
	successInnerProgram := "0x" + hex.EncodeToString(successInnerProgramBytes)

	noFailureName := "none"
	noFailure := func(info TestScenarioInfo) TestScenario {
		program := fillProgramTemplate("", successInnerProgram, "", 1, 2, "pushint 1")
		expectedAD, expectedDeltaCallingTxn, expectedDeltaInnerAppCall, expectedDeltaInnerPay1, expectedDeltaInnerPay2 := expectedApplyDataAndStateDelta(info, program, successInnerProgramBytes)
		expectedDelta := MergeStateDeltas(expectedDeltaCallingTxn, expectedDeltaInnerAppCall, expectedDeltaInnerPay1, expectedDeltaInnerPay2)

		return TestScenario{
			Outcome:       ApprovalOutcome,
			Program:       program,
			FailedAt:      nil,
			ExpectedError: "", // no error
			ExpectedEvents: FlattenEvents([][]Event{
				{
					BeforeTxn(protocol.ApplicationCallTx),
					BeforeProgram(logic.ModeApp),
				},
				OpcodeEvents(11, false),
				{
					BeforeOpcode(),
					BeforeTxnGroup(1), // start first itxn group
					BeforeTxn(protocol.ApplicationCallTx),
					BeforeProgram(logic.ModeApp),
				},
				OpcodeEvents(3, false),
				{
					AfterProgram(logic.ModeApp, ProgramResultPass),
					AfterTxn(protocol.ApplicationCallTx, expectedAD.EvalDelta.InnerTxns[0].ApplyData, false),
					AfterTxnGroup(1, nil, false), // end first itxn group
					AfterOpcode(false),
				},
				OpcodeEvents(16, false),
				{
					BeforeOpcode(),
					BeforeTxnGroup(2), // start second itxn group
					BeforeTxn(protocol.PaymentTx),
					AfterTxn(protocol.PaymentTx, expectedAD.EvalDelta.InnerTxns[1].ApplyData, false),
					BeforeTxn(protocol.PaymentTx),
					AfterTxn(protocol.PaymentTx, expectedAD.EvalDelta.InnerTxns[2].ApplyData, false),
					AfterTxnGroup(2, nil, false), // end second itxn group
					AfterOpcode(false),
				},
				OpcodeEvents(3, false),
				{
					AfterProgram(logic.ModeApp, ProgramResultPass),
					AfterTxn(protocol.ApplicationCallTx, expectedAD, false),
				},
			}),
			ExpectedSimulationAD: expectedAD,
			ExpectedStateDelta:   expectedDelta,
			AppBudgetAdded:       2100,
			AppBudgetConsumed:    35,
			TxnAppBudgetConsumed: []uint64{0, 35},
		}
	}

	scenarios := map[string]TestScenarioGenerator{
		noFailureName: noFailure,
	}

	for _, shouldError := range []bool{true, false} {
		shouldError := shouldError
		failureOps := "pushint 0\nreturn"
		singleFailureOp := "pushint 0"
		failureInnerProgramBytes := []byte{0x06, 0x80, 0x01, 0x78, 0xb0, 0x81, 0x00} // #pragma version 6; pushbytes "x"; log; pushint 0
		failureMessage := "transaction rejected by ApprovalProgram"
		outcome := RejectionOutcome
		programFailingResult := ProgramResultReject
		if shouldError {
			// We could use just the err opcode here, but we want to use two opcodes to maintain
			// trace event consistency with rejections.
			failureOps = "pushint 0\nerr"
			singleFailureOp = "err"
			failureInnerProgramBytes = []byte{0x06, 0x80, 0x01, 0x78, 0xb0, 0x00} // #pragma version 6; pushbytes "x"; log; err
			failureMessage = "err opcode executed"
			outcome = ErrorOutcome
			programFailingResult = ProgramResultError
		}
		failureInnerProgram := "0x" + hex.EncodeToString(failureInnerProgramBytes)

		beforeInnersName := fmt.Sprintf("before inners,error=%t", shouldError)
		beforeInners := func(info TestScenarioInfo) TestScenario {
			program := fillProgramTemplate(failureOps, successInnerProgram, "", 1, 2, "pushint 1")
			expectedAD, expectedDeltaCallingTxn, _, _, _ := expectedApplyDataAndStateDelta(info, program, successInnerProgramBytes)
			expectedDelta := expectedDeltaCallingTxn

			// remove failed txids from delta
			expectedDeltaCallingTxn.Txids = nil

			// EvalDeltas are removed from failed app call transactions
			expectedADNoED := expectedAD
			expectedADNoED.EvalDelta = transactions.EvalDelta{}
			// Only first log happens
			expectedAD.EvalDelta.Logs = expectedAD.EvalDelta.Logs[:1]
			expectedAD.EvalDelta.InnerTxns = nil
			return TestScenario{
				Outcome:       outcome,
				Program:       program,
				ExpectedError: failureMessage,
				FailedAt:      []uint64{0},
				ExpectedEvents: FlattenEvents([][]Event{
					{
						BeforeTxn(protocol.ApplicationCallTx),
						BeforeProgram(logic.ModeApp),
					},
					OpcodeEvents(4, shouldError),
					{
						AfterProgram(logic.ModeApp, programFailingResult),
						AfterTxn(protocol.ApplicationCallTx, expectedADNoED, true),
					},
				}),
				ExpectedSimulationAD: expectedAD,
				ExpectedStateDelta:   expectedDelta,
				AppBudgetAdded:       700,
				AppBudgetConsumed:    4,
				TxnAppBudgetConsumed: []uint64{0, 4},
			}
		}
		scenarios[beforeInnersName] = beforeInners

		firstInnerName := fmt.Sprintf("first inner,error=%t", shouldError)
		firstInner := func(info TestScenarioInfo) TestScenario {
			program := fillProgramTemplate("", failureInnerProgram, "", 1, 2, "pushint 1")
			expectedAD, expectedDeltaCallingTxn, _, _, _ := expectedApplyDataAndStateDelta(info, program, failureInnerProgramBytes)
			expectedDelta := expectedDeltaCallingTxn

			// remove failed txids from delta
			expectedDeltaCallingTxn.Txids = nil

			// EvalDeltas are removed from failed app call transactions
			expectedInnerAppCallADNoEvalDelta := expectedAD.EvalDelta.InnerTxns[0].ApplyData
			expectedInnerAppCallADNoEvalDelta.EvalDelta = transactions.EvalDelta{}
			expectedADNoED := expectedAD
			expectedADNoED.EvalDelta = transactions.EvalDelta{}

			// Only first log happens
			expectedAD.EvalDelta.Logs = expectedAD.EvalDelta.Logs[:1]

			expectedAD.EvalDelta.InnerTxns = expectedAD.EvalDelta.InnerTxns[:1]
			expectedAD.EvalDelta.InnerTxns[0].Txn.ApprovalProgram = failureInnerProgramBytes
			return TestScenario{
				Outcome:       outcome,
				Program:       program,
				ExpectedError: failureMessage,
				FailedAt:      []uint64{0, 0},
				ExpectedEvents: FlattenEvents([][]Event{
					{
						BeforeTxn(protocol.ApplicationCallTx),
						BeforeProgram(logic.ModeApp),
					},
					OpcodeEvents(11, false),
					{
						BeforeOpcode(),
						BeforeTxnGroup(1), // start first itxn group
						BeforeTxn(protocol.ApplicationCallTx),
						BeforeProgram(logic.ModeApp),
					},
					OpcodeEvents(3, shouldError),
					{
						AfterProgram(logic.ModeApp, programFailingResult),
						AfterTxn(protocol.ApplicationCallTx, expectedInnerAppCallADNoEvalDelta, true),
						AfterTxnGroup(1, nil, true), // end first itxn group
						AfterOpcode(true),
						AfterProgram(logic.ModeApp, ProgramResultError),
						AfterTxn(protocol.ApplicationCallTx, expectedADNoED, true),
					},
				}),
				ExpectedSimulationAD: expectedAD,
				ExpectedStateDelta:   expectedDelta,
				AppBudgetAdded:       1400,
				AppBudgetConsumed:    15,
				TxnAppBudgetConsumed: []uint64{0, 15},
			}
		}
		scenarios[firstInnerName] = firstInner

		betweenInnersName := fmt.Sprintf("between inners,error=%t", shouldError)
		betweenInners := func(info TestScenarioInfo) TestScenario {
			program := fillProgramTemplate("", successInnerProgram, failureOps, 1, 2, "pushint 1")
			expectedAD, expectedDeltaCallingTxn, _, _, _ := expectedApplyDataAndStateDelta(info, program, successInnerProgramBytes)
			expectedDelta := expectedDeltaCallingTxn

			// remove failed txids from delta
			expectedDeltaCallingTxn.Txids = nil

			expectedInnerAppCallAD := expectedAD.EvalDelta.InnerTxns[0].ApplyData

			// EvalDeltas are removed from failed app call transactions
			expectedADNoED := expectedAD
			expectedADNoED.EvalDelta = transactions.EvalDelta{}

			// Only first two logs happen
			expectedAD.EvalDelta.Logs = expectedAD.EvalDelta.Logs[:2]

			expectedAD.EvalDelta.InnerTxns = expectedAD.EvalDelta.InnerTxns[:1]
			return TestScenario{
				Outcome:       outcome,
				Program:       program,
				ExpectedError: failureMessage,
				FailedAt:      []uint64{0},
				ExpectedEvents: FlattenEvents([][]Event{
					{
						BeforeTxn(protocol.ApplicationCallTx),
						BeforeProgram(logic.ModeApp),
					},
					OpcodeEvents(11, false),
					{
						BeforeOpcode(),
						BeforeTxnGroup(1), // start first itxn group
						BeforeTxn(protocol.ApplicationCallTx),
						BeforeProgram(logic.ModeApp),
					},
					OpcodeEvents(3, false),
					{
						AfterProgram(logic.ModeApp, ProgramResultPass),
						AfterTxn(protocol.ApplicationCallTx, expectedInnerAppCallAD, false),
						AfterTxnGroup(1, nil, false), // end first itxn group
						AfterOpcode(false),
					},
					OpcodeEvents(4, shouldError),
					{
						AfterProgram(logic.ModeApp, programFailingResult),
						AfterTxn(protocol.ApplicationCallTx, expectedADNoED, true),
					},
				}),
				ExpectedSimulationAD: expectedAD,
				ExpectedStateDelta:   expectedDelta,
				AppBudgetAdded:       1400,
				AppBudgetConsumed:    19,
				TxnAppBudgetConsumed: []uint64{0, 19},
			}
		}
		scenarios[betweenInnersName] = betweenInners

		if shouldError {
			secondInnerName := "second inner"
			secondInner := func(info TestScenarioInfo) TestScenario {
				program := fillProgramTemplate("", successInnerProgram, "", math.MaxUint64, 2, "pushint 1")
				expectedAD, expectedDeltaCallingTxn, _, _, _ := expectedApplyDataAndStateDelta(info, program, successInnerProgramBytes)
				expectedDelta := expectedDeltaCallingTxn

				// remove failed txids from delta
				expectedDeltaCallingTxn.Txids = nil

				expectedInnerAppCallAD := expectedAD.EvalDelta.InnerTxns[0].ApplyData
				expectedInnerPay1AD := expectedAD.EvalDelta.InnerTxns[1].ApplyData

				// EvalDeltas are removed from failed app call transactions
				expectedADNoED := expectedAD
				expectedADNoED.EvalDelta = transactions.EvalDelta{}

				// Only first two logs happen
				expectedAD.EvalDelta.Logs = expectedAD.EvalDelta.Logs[:2]

				expectedAD.EvalDelta.InnerTxns[1].Txn.Amount.Raw = math.MaxUint64
				return TestScenario{
					Outcome:       ErrorOutcome,
					Program:       program,
					ExpectedError: "overspend",
					FailedAt:      []uint64{0, 1},
					ExpectedEvents: FlattenEvents([][]Event{
						{
							BeforeTxn(protocol.ApplicationCallTx),
							BeforeProgram(logic.ModeApp),
						},
						OpcodeEvents(11, false),
						{
							BeforeOpcode(),
							BeforeTxnGroup(1), // start first itxn group
							BeforeTxn(protocol.ApplicationCallTx),
							BeforeProgram(logic.ModeApp),
						},
						OpcodeEvents(3, false),
						{
							AfterProgram(logic.ModeApp, ProgramResultPass),
							AfterTxn(protocol.ApplicationCallTx, expectedInnerAppCallAD, false),
							AfterTxnGroup(1, nil, false), // end first itxn group
							AfterOpcode(false),
						},
						OpcodeEvents(16, false),
						{
							BeforeOpcode(),
							BeforeTxnGroup(2), // start second itxn group
							BeforeTxn(protocol.PaymentTx),
							AfterTxn(protocol.PaymentTx, expectedInnerPay1AD, true),
							AfterTxnGroup(2, nil, true), // end second itxn group
							AfterOpcode(true),
							AfterProgram(logic.ModeApp, ProgramResultError),
							AfterTxn(protocol.ApplicationCallTx, expectedADNoED, true),
						},
					}),
					ExpectedSimulationAD: expectedAD,
					ExpectedStateDelta:   expectedDelta,
					AppBudgetAdded:       2100,
					AppBudgetConsumed:    32,
					TxnAppBudgetConsumed: []uint64{0, 32},
				}
			}
			scenarios[secondInnerName] = secondInner

			thirdInnerName := "third inner"
			thirdInner := func(info TestScenarioInfo) TestScenario {
				program := fillProgramTemplate("", successInnerProgram, "", 1, math.MaxUint64, "pushint 1")
				expectedAD, expectedDeltaCallingTxn, _, _, _ := expectedApplyDataAndStateDelta(info, program, successInnerProgramBytes)
				expectedDelta := expectedDeltaCallingTxn

				// remove failed txids from delta
				expectedDeltaCallingTxn.Txids = nil

				expectedInnerAppCallAD := expectedAD.EvalDelta.InnerTxns[0].ApplyData
				expectedInnerPay1AD := expectedAD.EvalDelta.InnerTxns[1].ApplyData
				expectedInnerPay2AD := expectedAD.EvalDelta.InnerTxns[2].ApplyData

				// EvalDeltas are removed from failed app call transactions
				expectedADNoED := expectedAD
				expectedADNoED.EvalDelta = transactions.EvalDelta{}

				// Only first two logs happen
				expectedAD.EvalDelta.Logs = expectedAD.EvalDelta.Logs[:2]

				expectedAD.EvalDelta.InnerTxns[2].Txn.Amount.Raw = math.MaxUint64
				return TestScenario{
					Outcome:       ErrorOutcome,
					Program:       program,
					ExpectedError: "overspend",
					FailedAt:      []uint64{0, 2},
					ExpectedEvents: FlattenEvents([][]Event{
						{
							BeforeTxn(protocol.ApplicationCallTx),
							BeforeProgram(logic.ModeApp),
						},
						OpcodeEvents(11, false),
						{
							BeforeOpcode(),
							BeforeTxnGroup(1), // start first itxn group
							BeforeTxn(protocol.ApplicationCallTx),
							BeforeProgram(logic.ModeApp),
						},
						OpcodeEvents(3, false),
						{
							AfterProgram(logic.ModeApp, ProgramResultPass),
							AfterTxn(protocol.ApplicationCallTx, expectedInnerAppCallAD, false),
							AfterTxnGroup(1, nil, false), // end first itxn group
							AfterOpcode(false),
						},
						OpcodeEvents(16, false),
						{
							BeforeOpcode(),
							BeforeTxnGroup(2), // start second itxn group
							BeforeTxn(protocol.PaymentTx),
							AfterTxn(protocol.PaymentTx, expectedInnerPay1AD, false),
							BeforeTxn(protocol.PaymentTx),
							AfterTxn(protocol.PaymentTx, expectedInnerPay2AD, true),
							AfterTxnGroup(2, nil, true), // end second itxn group
							AfterOpcode(true),
							AfterProgram(logic.ModeApp, ProgramResultError),
							AfterTxn(protocol.ApplicationCallTx, expectedADNoED, true),
						},
					}),
					ExpectedSimulationAD: expectedAD,
					ExpectedStateDelta:   expectedDelta,
					AppBudgetAdded:       2100,
					AppBudgetConsumed:    32,
					TxnAppBudgetConsumed: []uint64{0, 32},
				}
			}
			scenarios[thirdInnerName] = thirdInner
		}

		afterInnersName := fmt.Sprintf("after inners,error=%t", shouldError)
		afterInners := func(info TestScenarioInfo) TestScenario {
			program := fillProgramTemplate("", successInnerProgram, "", 1, 2, singleFailureOp)
			expectedAD, expectedDeltaCallingTxn, _, _, _ := expectedApplyDataAndStateDelta(info, program, successInnerProgramBytes)
			expectedDelta := expectedDeltaCallingTxn

			// remove failed txids from delta
			expectedDeltaCallingTxn.Txids = nil

			expectedInnerAppCallAD := expectedAD.EvalDelta.InnerTxns[0].ApplyData
			expectedInnerPay1AD := expectedAD.EvalDelta.InnerTxns[1].ApplyData
			expectedInnerPay2AD := expectedAD.EvalDelta.InnerTxns[2].ApplyData
			// EvalDeltas are removed from failed app call transactions
			expectedADNoED := expectedAD
			expectedADNoED.EvalDelta = transactions.EvalDelta{}
			return TestScenario{
				Outcome:       outcome,
				Program:       program,
				ExpectedError: failureMessage,
				FailedAt:      []uint64{0},
				ExpectedEvents: FlattenEvents([][]Event{
					{
						BeforeTxn(protocol.ApplicationCallTx),
						BeforeProgram(logic.ModeApp),
					},
					OpcodeEvents(11, false),
					{
						BeforeOpcode(),
						BeforeTxnGroup(1), // start first itxn group
						BeforeTxn(protocol.ApplicationCallTx),
						BeforeProgram(logic.ModeApp),
					},
					OpcodeEvents(3, false),
					{
						AfterProgram(logic.ModeApp, ProgramResultPass),
						AfterTxn(protocol.ApplicationCallTx, expectedInnerAppCallAD, false),
						AfterTxnGroup(1, nil, false), // end first itxn group
						AfterOpcode(false),
					},
					OpcodeEvents(16, false),
					{
						BeforeOpcode(),
						BeforeTxnGroup(2), // start second itxn group
						BeforeTxn(protocol.PaymentTx),
						AfterTxn(protocol.PaymentTx, expectedInnerPay1AD, false),
						BeforeTxn(protocol.PaymentTx),
						AfterTxn(protocol.PaymentTx, expectedInnerPay2AD, false),
						AfterTxnGroup(2, nil, false), // end second itxn group
						AfterOpcode(false),
					},
					OpcodeEvents(3, shouldError),
					{
						AfterProgram(logic.ModeApp, programFailingResult),
						AfterTxn(protocol.ApplicationCallTx, expectedADNoED, true),
					},
				}),
				ExpectedSimulationAD: expectedAD,
				ExpectedStateDelta:   expectedDelta,
				AppBudgetAdded:       2100,
				AppBudgetConsumed:    35,
				TxnAppBudgetConsumed: []uint64{0, 35},
			}
		}
		scenarios[afterInnersName] = afterInners
	}

	return scenarios
}

func stripInnerTxnGroupIDs(ad *transactions.ApplyData) {
	for i := range ad.EvalDelta.InnerTxns {
		ad.EvalDelta.InnerTxns[i].Txn.Group = crypto.Digest{}
		stripInnerTxnGroupIDs(&ad.EvalDelta.InnerTxns[i].ApplyData)
	}
}

// StripInnerTxnGroupIDsFromEvents removes any inner transaction GroupIDs that are present in the
// TxnApplyData fields of the events.
func StripInnerTxnGroupIDsFromEvents(events []Event) []Event {
	for i := range events {
		stripInnerTxnGroupIDs(&events[i].TxnApplyData)
	}
	return events
}

// MergeStateDeltas merges multiple state deltas into one. The arguments are not modified, but the
// first delta is used to populate non-mergeable fields in the result.
func MergeStateDeltas(deltas ...ledgercore.StateDelta) ledgercore.StateDelta {
	if len(deltas) == 0 {
		return ledgercore.StateDelta{}
	}

	result := ledgercore.StateDelta{
		// copy basic fields from the first delta
		Hdr:            deltas[0].Hdr,
		StateProofNext: deltas[0].StateProofNext,
		PrevTimestamp:  deltas[0].PrevTimestamp,
		Totals:         deltas[0].Totals,

		// initialize structure for later use
		Txids: make(map[transactions.Txid]ledgercore.IncludedTransactions),
	}
	for _, delta := range deltas {
		result.Accts.MergeAccounts(delta.Accts)
		for key, delta := range delta.KvMods {
			result.AddKvMod(key, delta)
		}
		for id, delta := range delta.Creatables {
			result.AddCreatable(id, delta)
		}
		txidBase := uint64(len(result.Txids))
		for txid, includedTx := range delta.Txids {
			includedTx.Intra += txidBase
			result.Txids[txid] = includedTx
		}
		for lease, round := range delta.Txleases {
			result.Txleases[lease] = round
		}
	}
	return result
}