summaryrefslogtreecommitdiff
path: root/ledger/eval/txntracer_test.go
blob: 4711709c6856a5d657c6354448cc851f68753dbe (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
// 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 eval

import (
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/data/basics"
	basics_testing "github.com/algorand/go-algorand/data/basics/testing"
	"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/transactions/logic/mocktracer"
	"github.com/algorand/go-algorand/data/txntest"
	"github.com/algorand/go-algorand/ledger/ledgercore"
	ledgertesting "github.com/algorand/go-algorand/ledger/testing"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/test/partitiontest"
)

func TestTransactionGroupWithDeltaTracer(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	// In all cases, a group of three transactions is tested. They are:
	//   1. A basic app call transaction
	//   2. A payment transaction
	//   3. An app call transaction that spawns inners. This is from the mocktracer scenarios.

	// We don't care about testing error scenarios here--just exercising different successful txn group evals
	scenario := mocktracer.GetTestScenarios()["none"]
	type tracerTestCase struct {
		name                 string
		innerAppCallScenario mocktracer.TestScenarioGenerator
	}
	var testCases = []tracerTestCase{
		{
			name:                 "noError",
			innerAppCallScenario: scenario,
		},
	}

	for _, testCase := range testCases {
		testCase := testCase
		t.Run(testCase.name, func(t *testing.T) {
			t.Parallel()
			// SETUP THE BLOCK
			genesisInitState, addrs, keys := ledgertesting.Genesis(4)

			// newTestLedger uses ConsensusFuture, so we check it to find out if
			// we should use 1001 as the initial resources ID.
			protoVersion := protocol.ConsensusFuture
			proto := config.Consensus[protoVersion]
			offset := basics.AppIndex(0)
			if proto.AppForbidLowResources {
				offset += 1000
			}

			innerAppID := basics.AppIndex(3) + offset
			innerAppAddress := innerAppID.Address()
			appID := basics.AppIndex(1) + offset
			appAddress := appID.Address()
			innerBoxAppID := basics.AppIndex(7) + offset
			innerBoxAppAddress := innerBoxAppID.Address()
			balances := genesisInitState.Accounts
			balances[innerAppAddress] = basics_testing.MakeAccountData(basics.Offline, basics.MicroAlgos{Raw: 1_000_000})
			balances[appAddress] = basics_testing.MakeAccountData(basics.Offline, basics.MicroAlgos{Raw: 1_000_000})

			genesisBalances := bookkeeping.GenesisBalances{
				Balances:    genesisInitState.Accounts,
				FeeSink:     testSinkAddr,
				RewardsPool: testPoolAddr,
				Timestamp:   0,
			}
			l := newTestLedger(t, genesisBalances)
			blkHeader, err := l.BlockHdr(basics.Round(0))
			require.NoError(t, err)
			newBlock := bookkeeping.MakeBlock(blkHeader)
			tracer := MakeTxnGroupDeltaTracer(4)
			eval, err := l.StartEvaluator(newBlock.BlockHeader, 0, 0, tracer)
			require.NoError(t, err)
			eval.validate = true
			eval.generate = true
			genHash := l.GenesisHash()

			basicAppCallApproval := `#pragma version 8
byte "hellobox"
int 10
box_create
pop
int 1`
			basicAppCallClear := `#pragma version 8
int 1`
			basicAppCallClearOps, err := logic.AssembleString(basicAppCallClear)
			require.NoError(t, err)
			basicAppCallApprovalOps, err := logic.AssembleString(basicAppCallApproval)
			require.NoError(t, err)
			// a basic app call
			basicAppCallTxn := txntest.Txn{
				Type:              protocol.ApplicationCallTx,
				Sender:            addrs[0],
				ApprovalProgram:   basicAppCallApproval,
				ClearStateProgram: basicAppCallClear,
				FirstValid:        newBlock.Round(),
				LastValid:         newBlock.Round() + 1000,
				Fee:               minFee,
				GenesisHash:       genHash,
				Note:              []byte("one"),
				Boxes: []transactions.BoxRef{{
					Index: 0,
					Name:  []byte("hellobox"),
				}},
			}

			// a non-app call txn
			var txnLease [32]byte
			copy(txnLease[:], "txnLeaseTest")
			payTxn := txntest.Txn{
				Type:             protocol.PaymentTx,
				Sender:           addrs[1],
				Receiver:         addrs[2],
				CloseRemainderTo: addrs[3],
				Amount:           1_000_000,
				FirstValid:       newBlock.Round(),
				LastValid:        newBlock.Round() + 1000,
				Fee:              minFee,
				GenesisHash:      genHash,
				Note:             []byte("two"),
				Lease:            txnLease,
			}
			// an app call with inner txn
			v6Clear := `#pragma version 6
int 1`
			v6ClearOps, err := logic.AssembleString(v6Clear)
			require.NoError(t, err)
			innerAppCallTxn := txntest.Txn{
				Type:              protocol.ApplicationCallTx,
				Sender:            addrs[0],
				ClearStateProgram: v6Clear,
				FirstValid:        newBlock.Round(),
				LastValid:         newBlock.Round() + 1000,
				Fee:               minFee,
				GenesisHash:       genHash,
				Note:              []byte("three"),
			}
			scenario := testCase.innerAppCallScenario(mocktracer.TestScenarioInfo{
				CallingTxn:   innerAppCallTxn.Txn(),
				MinFee:       minFee,
				CreatedAppID: innerAppID,
			})
			innerAppCallTxn.ApprovalProgram = scenario.Program
			innerAppCallApprovalOps, err := logic.AssembleString(scenario.Program)
			require.NoError(t, err)

			// inner txn with more box mods
			innerAppCallBoxApproval := `#pragma version 8
byte "goodbyebox"
int 10
box_create
pop
byte "goodbyebox"
int 0
byte "2"
box_replace
byte "goodbyebox"
box_del
pop
int 1`
			innerAppCallBoxApprovalOps, err := logic.AssembleString(innerAppCallBoxApproval)
			require.NoError(t, err)
			innerAppCallBoxTxn := txntest.Txn{
				Type:              protocol.ApplicationCallTx,
				Sender:            addrs[0],
				ApprovalProgram:   innerAppCallBoxApproval,
				ClearStateProgram: basicAppCallClear,
				FirstValid:        newBlock.Round(),
				LastValid:         newBlock.Round() + 1000,
				Fee:               minFee,
				GenesisHash:       genHash,
				Boxes: []transactions.BoxRef{{
					Index: 0,
					Name:  []byte("goodbyebox"),
				}},
			}

			txntest.Group(&basicAppCallTxn, &payTxn, &innerAppCallTxn, &innerAppCallBoxTxn)

			txgroup := transactions.WrapSignedTxnsWithAD([]transactions.SignedTxn{
				basicAppCallTxn.Txn().Sign(keys[0]),
				payTxn.Txn().Sign(keys[1]),
				innerAppCallTxn.Txn().Sign(keys[0]),
				innerAppCallBoxTxn.Txn().Sign(keys[0]),
			})

			require.Len(t, eval.block.Payset, 0)

			err = eval.TransactionGroup(txgroup)
			require.NoError(t, err)
			require.Len(t, eval.block.Payset, 4)

			secondPayTxn := txntest.Txn{
				Type:        protocol.PaymentTx,
				Sender:      addrs[2],
				Receiver:    addrs[1],
				Amount:      100_000,
				FirstValid:  newBlock.Round(),
				LastValid:   newBlock.Round() + 1000,
				Fee:         minFee,
				GenesisHash: genHash,
			}
			secondTxGroup := transactions.WrapSignedTxnsWithAD([]transactions.SignedTxn{
				secondPayTxn.Txn().Sign(keys[2]),
			})
			err = eval.TransactionGroup(secondTxGroup)
			require.NoError(t, err)

			expectedAccts := ledgercore.AccountDeltas{
				Accts: []ledgercore.BalanceRecord{
					{
						Addr: addrs[0],
						AccountData: ledgercore.AccountData{
							AccountBaseData: ledgercore.AccountBaseData{
								MicroAlgos:     basics.MicroAlgos{Raw: 1666666666663666},
								TotalAppParams: 3,
							},
						},
					},
					{
						Addr: testSinkAddr,
						AccountData: ledgercore.AccountData{
							AccountBaseData: ledgercore.AccountBaseData{
								Status:     basics.Status(2),
								MicroAlgos: basics.MicroAlgos{Raw: 1666666666673666},
							},
						},
					},
					{
						Addr: appAddress,
						AccountData: ledgercore.AccountData{
							AccountBaseData: ledgercore.AccountBaseData{
								MicroAlgos:    basics.MicroAlgos{Raw: 1000000},
								TotalBoxes:    1,
								TotalBoxBytes: 18,
							},
						},
					},
					{
						Addr: addrs[1],
					},
					{
						Addr: addrs[2],
						AccountData: ledgercore.AccountData{
							AccountBaseData: ledgercore.AccountBaseData{
								MicroAlgos: basics.MicroAlgos{Raw: 1666666667666666},
							},
						},
					},
					{
						Addr: addrs[3],
						AccountData: ledgercore.AccountData{
							AccountBaseData: ledgercore.AccountBaseData{
								MicroAlgos: basics.MicroAlgos{Raw: 3333333332332332},
							},
						},
					},
					{
						Addr: innerAppAddress,
						AccountData: ledgercore.AccountData{
							AccountBaseData: ledgercore.AccountBaseData{
								MicroAlgos:     basics.MicroAlgos{Raw: 997000},
								TotalAppParams: 1,
							},
						},
					},
					{
						Addr:        innerBoxAppAddress,
						AccountData: ledgercore.AccountData{},
					},
				},
				AppResources: []ledgercore.AppResourceRecord{
					{
						Aidx: 1 + offset,
						Addr: addrs[0],
						Params: ledgercore.AppParamsDelta{
							Params: &basics.AppParams{
								ApprovalProgram:   basicAppCallApprovalOps.Program,
								ClearStateProgram: basicAppCallClearOps.Program,
							},
						},
					},
					{
						Aidx: 3 + offset,
						Addr: addrs[0],
						Params: ledgercore.AppParamsDelta{
							Params: &basics.AppParams{
								ApprovalProgram:   innerAppCallApprovalOps.Program,
								ClearStateProgram: v6ClearOps.Program,
							},
						},
					},
					{
						Aidx: 4 + offset,
						Addr: innerAppAddress,
						Params: ledgercore.AppParamsDelta{
							Params: &basics.AppParams{
								ApprovalProgram:   []byte{0x06, 0x80, 0x01, 0x78, 0xb0, 0x81, 0x01}, // #pragma version 6; pushbytes "x"; log; pushint 1
								ClearStateProgram: v6ClearOps.Program,
							},
						},
					},
					{
						Aidx: innerBoxAppID,
						Addr: addrs[0],
						Params: ledgercore.AppParamsDelta{
							Params: &basics.AppParams{
								ApprovalProgram:   innerAppCallBoxApprovalOps.Program,
								ClearStateProgram: basicAppCallClearOps.Program,
							},
						},
					},
				},
			}
			expectedKvMods := map[string]ledgercore.KvValueDelta{
				"bx:\x00\x00\x00\x00\x00\x00\x03\xe9hellobox": {
					OldData: []uint8{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
					Data:    []uint8{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
				},
				"bx:\x00\x00\x00\x00\x00\x00\x03\xefgoodbyebox": {
					OldData: nil,
					Data:    nil,
				},
			}
			expectedLeases := map[ledgercore.Txlease]basics.Round{
				{Sender: payTxn.Sender, Lease: payTxn.Lease}: payTxn.LastValid,
			}

			actualDelta, err := tracer.GetDeltaForID(crypto.Digest(txgroup[0].ID()))
			require.NoError(t, err)
			_, err = tracer.GetDeltaForID(crypto.Digest(txgroup[1].ID()))
			require.NoError(t, err)
			_, err = tracer.GetDeltaForID(crypto.Digest(txgroup[2].ID()))
			require.NoError(t, err)
			allDeltas, err := tracer.GetDeltasForRound(basics.Round(1))
			require.NoError(t, err)
			require.Len(t, allDeltas, 2)

			require.Equal(t, expectedAccts.Accts, actualDelta.Accts.Accts)
			require.Equal(t, expectedAccts.AppResources, actualDelta.Accts.AppResources)
			require.Equal(t, expectedAccts.AssetResources, actualDelta.Accts.AssetResources)
			require.Equal(t, expectedKvMods, actualDelta.KvMods)
			require.Equal(t, expectedLeases, actualDelta.Txleases)
		})
	}
}