-
Notifications
You must be signed in to change notification settings - Fork 90
/
dryrun.go
303 lines (250 loc) · 7.97 KB
/
dryrun.go
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
package future
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"text/tabwriter"
"github.com/algorand/go-algorand-sdk/client/v2/algod"
"github.com/algorand/go-algorand-sdk/client/v2/common/models"
"github.com/algorand/go-algorand-sdk/crypto"
"github.com/algorand/go-algorand-sdk/types"
)
const (
defaultAppId uint64 = 1380011588
rejectMsg = "REJECT"
defaultMaxWidth = 30
)
// CreateDryrun creates a DryrunRequest object from a client and slice of SignedTxn objects and a default configuration
// Passed in as a pointer to a DryrunRequest object to use for extra parameters
func CreateDryrun(client *algod.Client, txns []types.SignedTxn, dr *models.DryrunRequest, ctx context.Context) (drr models.DryrunRequest, err error) {
var (
apps []types.AppIndex
assets []types.AssetIndex
accts []types.Address
)
drr.Txns = txns
if dr != nil {
drr.LatestTimestamp = dr.LatestTimestamp
drr.Round = dr.Round
drr.ProtocolVersion = dr.ProtocolVersion
drr.Sources = dr.Sources
}
for _, t := range txns {
if t.Txn.Type != types.ApplicationCallTx {
continue
}
accts = append(accts, t.Txn.Sender)
accts = append(accts, t.Txn.Accounts...)
apps = append(apps, t.Txn.ForeignApps...)
for _, aidx := range t.Txn.ForeignApps {
accts = append(accts, crypto.GetApplicationAddress(uint64(aidx)))
}
assets = append(assets, t.Txn.ForeignAssets...)
if t.Txn.ApplicationID == 0 {
drr.Apps = append(drr.Apps, models.Application{
Id: defaultAppId,
Params: models.ApplicationParams{
Creator: t.Txn.Sender.String(),
ApprovalProgram: t.Txn.ApprovalProgram,
ClearStateProgram: t.Txn.ClearStateProgram,
LocalStateSchema: models.ApplicationStateSchema{
NumByteSlice: t.Txn.LocalStateSchema.NumByteSlice,
NumUint: t.Txn.LocalStateSchema.NumUint,
},
GlobalStateSchema: models.ApplicationStateSchema{
NumByteSlice: t.Txn.GlobalStateSchema.NumByteSlice,
NumUint: t.Txn.GlobalStateSchema.NumUint,
},
},
})
} else {
apps = append(apps, t.Txn.ApplicationID)
accts = append(accts, crypto.GetApplicationAddress(uint64(t.Txn.ApplicationID)))
}
}
seenAssets := map[types.AssetIndex]bool{}
for _, assetId := range assets {
if _, ok := seenAssets[assetId]; ok {
continue
}
assetInfo, err := client.GetAssetByID(uint64(assetId)).Do(ctx)
if err != nil {
return drr, fmt.Errorf("failed to get asset %d: %+v", assetId, err)
}
addr, err := types.DecodeAddress(assetInfo.Params.Creator)
if err != nil {
return drr, fmt.Errorf("failed to decode creator adddress %s: %+v", assetInfo.Params.Creator, err)
}
accts = append(accts, addr)
seenAssets[assetId] = true
}
seenApps := map[types.AppIndex]bool{}
for _, appId := range apps {
if _, ok := seenApps[appId]; ok {
continue
}
appInfo, err := client.GetApplicationByID(uint64(appId)).Do(ctx)
if err != nil {
return drr, fmt.Errorf("failed to get application %d: %+v", appId, err)
}
drr.Apps = append(drr.Apps, appInfo)
creator, err := types.DecodeAddress(appInfo.Params.Creator)
if err != nil {
return drr, fmt.Errorf("failed to decode creator address %s: %+v", appInfo.Params.Creator, err)
}
accts = append(accts, creator)
seenApps[appId] = true
}
seenAccts := map[types.Address]bool{}
for _, acct := range accts {
if _, ok := seenAccts[acct]; ok {
continue
}
acctInfo, err := client.AccountInformation(acct.String()).Do(ctx)
if err != nil {
return drr, fmt.Errorf("failed to get application %s: %+v", acct, err)
}
drr.Accounts = append(drr.Accounts, acctInfo)
seenAccts[acct] = true
}
return
}
// StackPrinterConfig holds some configuration parameters for how to print a DryrunResponse stack trace
type StackPrinterConfig struct {
MaxValueWidth int // Set the max width of the column, 0 is no max
TopOfStackFirst bool // Set the order of the stack values printed, true is top of stack (last pushed) first
}
// DefaultStackPrinterConfig returns a new StackPrinterConfig with reasonable defaults
func DefaultStackPrinterConfig() StackPrinterConfig {
return StackPrinterConfig{MaxValueWidth: defaultMaxWidth, TopOfStackFirst: true}
}
type DryrunResponse struct {
Error string `json:"error"`
ProtocolVersion string `json:"protocol-version"`
Txns []DryrunTxnResult `json:"txns"`
}
func NewDryrunResponse(d models.DryrunResponse) (DryrunResponse, error) {
// Marshal and unmarshal to fix integer types.
b, err := json.Marshal(d)
if err != nil {
return DryrunResponse{}, err
}
return NewDryrunResponseFromJson(b)
}
func NewDryrunResponseFromJson(js []byte) (DryrunResponse, error) {
dr := DryrunResponse{}
err := json.Unmarshal(js, &dr)
return dr, err
}
type DryrunTxnResult struct {
models.DryrunTxnResult
}
// AppCallRejected returns true if the Application Call was rejected
// for this transaction
func (d *DryrunTxnResult) AppCallRejected() bool {
for _, m := range d.AppCallMessages {
if m == rejectMsg {
return true
}
}
return false
}
// LogicSigRejected returns true if the LogicSig was rejected
// for this transaction
func (d *DryrunTxnResult) LogicSigRejected() bool {
for _, m := range d.LogicSigMessages {
if m == rejectMsg {
return true
}
}
return false
}
type indexedScratchValue struct {
Idx int
Val models.TealValue
}
func scratchToString(prevScratch, currScratch []models.TealValue) string {
if len(currScratch) == 0 {
return ""
}
var newScratchVal *indexedScratchValue
prevScratchMap := map[indexedScratchValue]bool{}
for idx, psv := range prevScratch {
isv := indexedScratchValue{Idx: idx, Val: psv}
prevScratchMap[isv] = true
}
for idx, csv := range currScratch {
isv := indexedScratchValue{Idx: idx, Val: csv}
if _, ok := prevScratchMap[isv]; !ok {
newScratchVal = &isv
}
}
if newScratchVal == nil {
return ""
}
if len(newScratchVal.Val.Bytes) > 0 {
decoded, _ := base64.StdEncoding.DecodeString(newScratchVal.Val.Bytes)
return fmt.Sprintf("%d = %#x", newScratchVal.Idx, decoded)
}
return fmt.Sprintf("%d = %d", newScratchVal.Idx, newScratchVal.Val.Uint)
}
func stackToString(reverse bool, stack []models.TealValue) string {
elems := len(stack)
svs := make([]string, elems)
for idx, s := range stack {
svidx := idx
if reverse {
svidx = (elems - 1) - idx
}
if s.Type == 1 {
// Just returns empty string if there is an error, use it
decoded, _ := base64.StdEncoding.DecodeString(s.Bytes)
svs[svidx] = fmt.Sprintf("%#x", decoded)
} else {
svs[svidx] = fmt.Sprintf("%d", s.Uint)
}
}
return fmt.Sprintf("[%s]", strings.Join(svs, ", "))
}
func (d *DryrunTxnResult) trace(state []models.DryrunState, disassemmbly []string, spc StackPrinterConfig) string {
buff := bytes.NewBuffer(nil)
w := tabwriter.NewWriter(buff, 0, 0, 1, ' ', tabwriter.Debug)
fmt.Fprintln(w, "pc#\tln#\tsource\tscratch\tstack")
for idx, s := range state {
prevScratch := []models.TealValue{}
if idx > 0 {
prevScratch = state[idx-1].Scratch
}
src := disassemmbly[s.Line]
if s.Error != "" {
src = fmt.Sprintf("!! %s !!", s.Error)
}
srcLine := fmt.Sprintf("%d\t%d\t%s\t%s\t%s",
s.Pc, s.Line,
truncate(src, spc.MaxValueWidth),
truncate(scratchToString(prevScratch, s.Scratch), spc.MaxValueWidth),
truncate(stackToString(spc.TopOfStackFirst, s.Stack), spc.MaxValueWidth))
fmt.Fprintln(w, srcLine)
}
w.Flush()
return buff.String()
}
// GetAppCallTrace returns a string representing a stack trace for this transactions
// application logic evaluation
func (d *DryrunTxnResult) GetAppCallTrace(spc StackPrinterConfig) string {
return d.trace(d.AppCallTrace, d.Disassembly, spc)
}
// GetLogicSigTrace returns a string representing a stack trace for this transactions
// logic signature evaluation
func (d *DryrunTxnResult) GetLogicSigTrace(spc StackPrinterConfig) string {
return d.trace(d.LogicSigTrace, d.LogicSigDisassembly, spc)
}
func truncate(str string, width int) string {
if len(str) > width && width > 0 {
return str[:width] + "..."
}
return str
}