summaryrefslogtreecommitdiff
path: root/cmd/tealdbg/localLedger.go
blob: fc7655173f0b8bc25aec468144cc006e463cfacb (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
// 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 main

import (
	"encoding/json"
	"fmt"
	"io"
	"math/rand"
	"net/http"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/crypto"
	v2 "github.com/algorand/go-algorand/daemon/algod/api/server/v2"
	"github.com/algorand/go-algorand/daemon/algod/api/server/v2/generated/model"
	"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/ledger"
	"github.com/algorand/go-algorand/ledger/apply"
	"github.com/algorand/go-algorand/ledger/ledgercore"
	"github.com/algorand/go-algorand/protocol"
)

// AccountIndexerResponse represents the Account Response object from querying indexer
type AccountIndexerResponse struct {
	// Account information at a given round.
	//
	// Definition:
	// data/basics/userBalance.go : AccountData
	Account model.Account `json:"account"`

	// Round at which the results were computed.
	CurrentRound uint64 `json:"current-round"`
}

// ApplicationIndexerResponse represents the Application Response object from querying indexer
type ApplicationIndexerResponse struct {

	// Application index and its parameters
	Application model.Application `json:"application,omitempty"`

	// Round at which the results were computed.
	CurrentRound uint64 `json:"current-round"`
}

type localLedger struct {
	balances        map[basics.Address]basics.AccountData
	txnGroup        []transactions.SignedTxn
	groupIndex      int
	round           uint64
	aidx            basics.AppIndex
	latestTimestamp int64
}

func makeBalancesAdapter(
	balances map[basics.Address]basics.AccountData, txnGroup []transactions.SignedTxn,
	groupIndex int, proto string, round uint64, latestTimestamp int64,
	appIdx basics.AppIndex, painless bool, indexerURL string, indexerToken string,
) (apply.Balances, AppState, error) {

	if groupIndex >= len(txnGroup) {
		return nil, AppState{}, fmt.Errorf("invalid groupIndex %d exceed txn group length %d", groupIndex, len(txnGroup))
	}
	txn := txnGroup[groupIndex]

	accounts := []basics.Address{txn.Txn.Sender}
	accounts = append(accounts, txn.Txn.Accounts...)

	apps := []basics.AppIndex{appIdx}
	apps = append(apps, txn.Txn.ForeignApps...)

	// populate balances from the indexer if not already
	if indexerURL != "" {
		for _, acc := range accounts {
			// only populate from indexer if balance record not specified
			if _, ok := balances[acc]; !ok {
				var err error
				balances[acc], err = getBalanceFromIndexer(indexerURL, indexerToken, acc, round)
				if err != nil {
					return nil, AppState{}, err
				}
			}
		}
		for _, app := range apps {
			creator, err := getAppCreatorFromIndexer(indexerURL, indexerToken, app)
			if err != nil {
				return nil, AppState{}, err
			}
			balances[creator], err = getBalanceFromIndexer(indexerURL, indexerToken, creator, round)
			if err != nil {
				return nil, AppState{}, err
			}
		}
	}

	ll := &localLedger{
		balances:   balances,
		txnGroup:   txnGroup,
		groupIndex: groupIndex,
		round:      round,
	}

	appsExist := make(map[basics.AppIndex]bool, len(apps))
	states := makeAppState()
	states.schemas = makeSchemas()
	states.appIdx = appIdx
	for _, aid := range apps {
		for addr, ad := range balances {
			if params, ok := ad.AppParams[aid]; ok {
				if aid == appIdx {
					states.schemas = params.StateSchemas
				}
				states.global[aid] = params.GlobalState
				appsExist[aid] = true
			}
			if local, ok := ad.AppLocalStates[aid]; ok {
				ls, ok := states.locals[addr]
				if !ok {
					ls = make(map[basics.AppIndex]basics.TealKeyValue)
				}
				ls[aid] = local.KeyValue
				states.locals[addr] = ls
			}
		}
	}

	// painless mode creates all missed global states and opt-in all mentioned accounts
	if painless {
		for _, aid := range apps {
			if ok := appsExist[aid]; !ok {
				// create balance record and AppParams for this app
				addr, err := getRandomAddress()
				if err != nil {
					return nil, AppState{}, err
				}
				ad := basics.AccountData{
					AppParams: map[basics.AppIndex]basics.AppParams{
						aid: {
							StateSchemas: makeSchemas(),
							GlobalState:  make(basics.TealKeyValue),
						},
					},
				}
				balances[addr] = ad
			}
			for _, addr := range accounts {
				ad, ok := balances[addr]
				if !ok {
					ad = basics.AccountData{
						AppLocalStates: map[basics.AppIndex]basics.AppLocalState{},
					}
					balances[addr] = ad
				}
				if ad.AppLocalStates == nil {
					ad.AppLocalStates = make(map[basics.AppIndex]basics.AppLocalState)
				}
				_, ok = ad.AppLocalStates[aid]
				if !ok {
					ad.AppLocalStates[aid] = basics.AppLocalState{
						Schema: makeLocalSchema(),
					}
				}
			}
		}
	}

	ba := ledger.MakeDebugBalances(ll, basics.Round(round), protocol.ConsensusVersion(proto), latestTimestamp)
	ll.aidx = appIdx
	return ba, states, nil
}

func getAppCreatorFromIndexer(indexerURL string, indexerToken string, app basics.AppIndex) (basics.Address, error) {
	queryString := fmt.Sprintf("%s/v2/applications/%d", indexerURL, app)
	client := &http.Client{}
	request, err := http.NewRequest("GET", queryString, nil)
	if err != nil {
		return basics.Address{}, fmt.Errorf("application request error: %w", err)
	}
	request.Header.Set("X-Indexer-API-Token", indexerToken)
	resp, err := client.Do(request)
	if err != nil {
		return basics.Address{}, fmt.Errorf("application request error: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		msg, _ := io.ReadAll(resp.Body)
		return basics.Address{}, fmt.Errorf("application response error: %s, status code: %d, request: %s", string(msg), resp.StatusCode, queryString)
	}
	var appResp ApplicationIndexerResponse
	err = json.NewDecoder(resp.Body).Decode(&appResp)
	if err != nil {
		return basics.Address{}, fmt.Errorf("application response decode error: %w", err)
	}

	creator, err := basics.UnmarshalChecksumAddress(appResp.Application.Params.Creator)

	if err != nil {
		return basics.Address{}, fmt.Errorf("UnmarshalChecksumAddress error: %w", err)
	}
	return creator, nil
}

func getBalanceFromIndexer(indexerURL string, indexerToken string, account basics.Address, round uint64) (basics.AccountData, error) {
	queryString := fmt.Sprintf("%s/v2/accounts/%s?round=%d", indexerURL, account, round)
	client := &http.Client{}
	request, err := http.NewRequest("GET", queryString, nil)
	if err != nil {
		return basics.AccountData{}, fmt.Errorf("account request error: %w", err)
	}
	request.Header.Set("X-Indexer-API-Token", indexerToken)
	resp, err := client.Do(request)
	if err != nil {
		return basics.AccountData{}, fmt.Errorf("account request error: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		msg, _ := io.ReadAll(resp.Body)
		return basics.AccountData{}, fmt.Errorf("account response error: %s, status code: %d, request: %s", string(msg), resp.StatusCode, queryString)
	}
	var accountResp AccountIndexerResponse
	err = json.NewDecoder(resp.Body).Decode(&accountResp)
	if err != nil {
		return basics.AccountData{}, fmt.Errorf("account response decode error: %w", err)
	}
	balance, err := v2.AccountToAccountData(&accountResp.Account)
	if err != nil {
		return basics.AccountData{}, fmt.Errorf("AccountToAccountData error: %w", err)
	}
	return balance, nil
}

func makeSchemas() basics.StateSchemas {
	return basics.StateSchemas{
		LocalStateSchema:  makeLocalSchema(),
		GlobalStateSchema: makeGlobalSchema(),
	}
}

func makeLocalSchema() basics.StateSchema {
	return basics.StateSchema{
		NumUint:      16,
		NumByteSlice: 16,
	}
}

func makeGlobalSchema() basics.StateSchema {
	return basics.StateSchema{
		NumUint:      64,
		NumByteSlice: 64,
	}
}

func getRandomAddress() (basics.Address, error) {
	const rl = 16
	b := make([]byte, rl)
	_, err := rand.Read(b)
	if err != nil {
		return basics.Address{}, err
	}

	address := crypto.Hash(b)
	return basics.Address(address), nil
}

func (l *localLedger) BlockHdr(basics.Round) (bookkeeping.BlockHeader, error) {
	return bookkeeping.BlockHeader{}, nil
}

func (l *localLedger) GenesisHash() crypto.Digest {
	return crypto.Digest{}
}

func (l *localLedger) GetStateProofVerificationContext(_ basics.Round) (*ledgercore.StateProofVerificationContext, error) {
	return nil, fmt.Errorf("localLedger: GetStateProofVerificationContext, needed for state proof verification, is not implemented in debugger")
}

func (l *localLedger) CheckDup(config.ConsensusParams, basics.Round, basics.Round, basics.Round, transactions.Txid, ledgercore.Txlease) error {
	return nil
}

func (l *localLedger) LookupAsset(rnd basics.Round, addr basics.Address, aidx basics.AssetIndex) (ledgercore.AssetResource, error) {
	ad, ok := l.balances[addr]
	if !ok {
		return ledgercore.AssetResource{}, nil
	}
	var result ledgercore.AssetResource
	if p, ok := ad.AssetParams[basics.AssetIndex(aidx)]; ok {
		result.AssetParams = &p
	}
	if p, ok := ad.Assets[basics.AssetIndex(aidx)]; ok {
		result.AssetHolding = &p
	}

	return result, nil
}

func (l *localLedger) LookupApplication(rnd basics.Round, addr basics.Address, aidx basics.AppIndex) (ledgercore.AppResource, error) {
	ad, ok := l.balances[addr]
	if !ok {
		return ledgercore.AppResource{}, nil
	}
	var result ledgercore.AppResource
	if p, ok := ad.AppParams[basics.AppIndex(aidx)]; ok {
		result.AppParams = &p
	}
	if s, ok := ad.AppLocalStates[basics.AppIndex(aidx)]; ok {
		result.AppLocalState = &s
	}

	return result, nil
}

func (l *localLedger) LookupKv(rnd basics.Round, name string) ([]byte, error) {
	return nil, fmt.Errorf("boxes not implemented in debugger")
}

func (l *localLedger) LookupWithoutRewards(rnd basics.Round, addr basics.Address) (ledgercore.AccountData, basics.Round, error) {
	ad := l.balances[addr]
	// Clear RewardsBase since tealdbg has no idea about rewards level so the underlying calculation with reward will fail.
	ad.RewardsBase = 0
	return ledgercore.ToAccountData(ad), rnd, nil
}

func (l *localLedger) GetCreatorForRound(rnd basics.Round, cidx basics.CreatableIndex, ctype basics.CreatableType) (basics.Address, bool, error) {
	switch ctype {
	case basics.AssetCreatable:
		assetIdx := basics.AssetIndex(cidx)
		for addr, br := range l.balances {
			if _, ok := br.AssetParams[assetIdx]; ok {
				return addr, true, nil
			}
		}
		return basics.Address{}, false, nil
	case basics.AppCreatable:
		appIdx := basics.AppIndex(cidx)
		for addr, br := range l.balances {
			if _, ok := br.AppParams[appIdx]; ok {
				return addr, true, nil
			}
		}
		return basics.Address{}, false, nil
	}
	return basics.Address{}, false, fmt.Errorf("unknown creatable type %d", ctype)
}