-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdebug.go
More file actions
415 lines (373 loc) · 11.5 KB
/
Copy pathdebug.go
File metadata and controls
415 lines (373 loc) · 11.5 KB
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
package main
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"crypto/tls"
tm "github.com/buger/goterm"
"github.com/gcash/bchd/bchrpc/pb"
"github.com/gcash/bchd/chaincfg"
"github.com/gcash/bchd/chaincfg/chainhash"
"github.com/gcash/bchd/txscript"
"github.com/gcash/bchd/wire"
term "github.com/nsf/termbox-go"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// Debug holds the options to the debug command.
type Debug struct {
Transaction string `short:"t" long:"tx" description:"the full transaction hex or BCH mainnet txid. If only a txid is provided the transaction will be looked up via the RPC server."`
InputIndex int `short:"i" long:"idx" description:"the input index to debug"`
InputAmount int64 `short:"a" long:"amt" description:"the amount of the input (in satoshis) we're debugging. This can be omitted if the transaction is in the BCH blockchain as it will be looked up via the RPC server."`
ScriptPubkey string `short:"s" long:"pkscript" description:"the input's scriptPubkey. This can be omitted if the transaction is in the BCH blockchain as it will be looked up via the RPC server."`
RPCServer string `long:"rpcserver" description:"A hostname:port for a gRPC API to use to fetch the transaction and scriptPubkey if not providing through the options."`
RPCAllowInsecure bool `long:"rpcallowinsecure" description:"Allow insecure TLS (skip certificate validation)."`
}
func dial(x *Debug) (*grpc.ClientConn, error) {
if x.RPCAllowInsecure {
tlsCfg := &tls.Config{
InsecureSkipVerify: true,
}
creds := credentials.NewTLS(tlsCfg)
return grpc.NewClient(x.RPCServer, grpc.WithTransportCredentials(creds))
}
return grpc.NewClient(x.RPCServer, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")))
}
// Execute will run the Debug command. This drops into the terminal debugger and allows
// us to step forward and backwards.
func (x *Debug) Execute(_ []string) error {
var (
txBytes []byte
scriptPubkey []byte
client pb.BchrpcClient
err error
done bool
fail bool
)
err = term.Init()
if err != nil {
panic(err)
}
defer term.Close()
if txid, err := chainhash.NewHashFromStr(x.Transaction); err == nil {
conn, err := dial(x)
if err != nil {
return err
}
client = pb.NewBchrpcClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
resp, err := client.GetRawTransaction(ctx, &pb.GetRawTransactionRequest{
Hash: txid[:],
})
if err != nil {
return err
}
txBytes = resp.Transaction
} else {
txBytes, err = hex.DecodeString(x.Transaction)
if err != nil {
return err
}
}
tx := &wire.MsgTx{}
if err := tx.BchDecode(bytes.NewReader(txBytes), wire.ProtocolVersion, wire.BaseEncoding); err != nil {
return err
}
if len(tx.TxIn) == 0 {
return errors.New("transaction has no inputs")
}
if x.ScriptPubkey == "" {
if client == nil {
conn, err := dial(x)
if err != nil {
return err
}
client = pb.NewBchrpcClient(conn)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
resp, err := client.GetTransaction(ctx, &pb.GetTransactionRequest{
Hash: tx.TxIn[x.InputIndex].PreviousOutPoint.Hash[:],
})
if err != nil {
return err
}
scriptPubkey = resp.Transaction.Outputs[tx.TxIn[x.InputIndex].PreviousOutPoint.Index].PubkeyScript
} else {
scriptPubkey, err = hex.DecodeString(x.ScriptPubkey)
if err != nil {
return err
}
}
if x.InputAmount == 0 {
if client == nil {
conn, err := dial(x)
if err != nil {
return err
}
client = pb.NewBchrpcClient(conn)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
resp, err := client.GetTransaction(ctx, &pb.GetTransactionRequest{
Hash: tx.TxIn[x.InputIndex].PreviousOutPoint.Hash[:],
})
if err != nil {
return err
}
x.InputAmount = resp.Transaction.Outputs[tx.TxIn[x.InputIndex].PreviousOutPoint.Index].Value
}
utxoCache := txscript.NewUtxoCache()
for i, txIn := range tx.TxIn {
if client == nil {
conn, err := dial(x)
if err != nil {
return err
}
client = pb.NewBchrpcClient(conn)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
resp, err := client.GetTransaction(ctx, &pb.GetTransactionRequest{
Hash: txIn.PreviousOutPoint.Hash[:],
})
if err != nil {
return err
}
output := resp.Transaction.Outputs[txIn.PreviousOutPoint.Index]
txOut := wire.TxOut{}
txOut.Value = output.Value
txOut.PkScript = output.PubkeyScript
txOut.TokenData = wire.TokenData{}
if output.CashToken != nil {
copy(txOut.TokenData.CategoryID[:], output.CashToken.CategoryId)
txOut.TokenData.BitField = output.CashToken.Bitfield[0]
txOut.TokenData.Amount = output.CashToken.Amount
txOut.TokenData.Commitment = output.CashToken.Commitment
}
utxoCache.AddEntry(i, txOut)
}
flags := txscript.StandardVerifyFlags | txscript.ScriptAllowCashTokens | txscript.ScriptAllowMay2025 | txscript.ScriptAllowMay2026
vm, err := txscript.NewEngine(scriptPubkey, tx, x.InputIndex, flags, nil, nil, utxoCache, x.InputAmount)
if err != nil {
return err
}
scriptClass, _, _, err := txscript.ExtractPkScriptAddrs(scriptPubkey, &chaincfg.MainNetParams)
if err != nil {
return err
}
isP2SH := (scriptClass == txscript.ScriptHashTy) || (scriptClass == txscript.ScriptHash32Ty)
scriptSig := tx.TxIn[x.InputIndex].SignatureScript
disassembledScriptSig, err := txscript.DisasmString(scriptSig)
if err != nil {
return err
}
disassembledScriptPubkey, err := txscript.DisasmString(scriptPubkey)
if err != nil {
return err
}
var (
splitDisassembledRedeemScript []string
unExecutedOpcodes [][]int
)
splitDisassembledScriptSig := strings.Split(disassembledScriptSig, " ")
splitDisassembledScriptPubkey := strings.Split(disassembledScriptPubkey, " ")
if isP2SH {
redeemScript, err := txscript.ExtractRedeemScript(scriptSig)
if err != nil {
return err
}
disassembledRedeemScript, err := txscript.DisasmString(redeemScript)
if err != nil {
return err
}
splitDisassembledRedeemScript = strings.Split(disassembledRedeemScript, " ")
}
savedStates := make([]*txscript.Engine, len(splitDisassembledScriptSig)+len(splitDisassembledScriptPubkey)+len(splitDisassembledRedeemScript))
stateIndex := 0
savedStates[stateIndex] = vm.Clone()
var fastForward = false
scriptLoop:
_, _ = tm.Println(tm.Background(tm.Color(tm.Bold(fmt.Sprintf("%s%s", "Debugger", strings.Repeat(" ", tm.Width()-8))), tm.BLACK), tm.GREEN))
tm.Flush()
var (
dissasm string
scriptIdx, offsetIdx int
)
if !done && !fail {
dissasm, err = vm.DisasmPC()
if err != nil {
return err
}
s := strings.Split(dissasm, ":")
scriptIdxBytes, err := hex.DecodeString(s[0])
if err != nil {
return err
}
scriptIdx = int(binary.BigEndian.Uint32(append([]byte{0x00, 0x00, 0x00}, scriptIdxBytes...)))
offsetIdxBytes, err := hex.DecodeString(s[1])
if err != nil {
return err
}
offsetIdx = int(binary.BigEndian.Uint32(append([]byte{0x00, 0x00}, offsetIdxBytes...)))
if !vm.IsBranchExecuting() && !strings.Contains(s[2], "OP_ENDIF") {
contains := false
for _, op := range unExecutedOpcodes {
if op[0] == scriptIdx && op[1] == offsetIdx {
contains = true
break
}
}
if !contains {
unExecutedOpcodes = append(unExecutedOpcodes, []int{scriptIdx, offsetIdx})
}
}
}
_, _ = tm.Println(tm.Background(tm.Color(tm.Bold("ScriptSig"), tm.WHITE), tm.BLUE))
for i, op := range splitDisassembledScriptSig {
if scriptIdx == 0 && offsetIdx == i && !done {
_, _ = tm.Printf(tm.Background(tm.Color(tm.Bold("%s"), tm.BLACK), tm.WHITE), op)
_, _ = tm.Printf(" ")
} else {
_, _ = tm.Printf("%s ", op)
}
}
_, _ = tm.Printf("\n\n")
_, _ = tm.Println(tm.Background(tm.Color(tm.Bold("ScriptPubkey"), tm.WHITE), tm.BLUE))
for i, op := range splitDisassembledScriptPubkey {
if scriptIdx == 1 && offsetIdx == i {
_, _ = tm.Printf(tm.Background(tm.Color(tm.Bold("%s"), tm.BLACK), tm.WHITE), op)
_, _ = tm.Printf(" ")
} else {
unexecuted := false
for _, unex := range unExecutedOpcodes {
if unex[0] == 1 && unex[1] == i {
_, _ = tm.Printf(tm.Background(tm.Color(tm.Bold("%s"), tm.RED), tm.BLACK), op)
_, _ = tm.Printf(" ")
unexecuted = true
}
}
if !unexecuted {
_, _ = tm.Printf("%s ", op)
}
}
}
_, _ = tm.Printf("\n\n")
if isP2SH {
_, _ = tm.Println(tm.Background(tm.Color(tm.Bold("RedeemScript"), tm.WHITE), tm.BLUE))
for i, op := range splitDisassembledRedeemScript {
if scriptIdx == 2 && offsetIdx == i {
_, _ = tm.Printf(tm.Background(tm.Color(tm.Bold("%s"), tm.BLACK), tm.WHITE), op)
_, _ = tm.Printf(" ")
} else {
unexecuted := false
for _, unex := range unExecutedOpcodes {
if unex[0] == 2 && unex[1] == i && scriptIdx >= unex[0] && offsetIdx >= unex[1] {
_, _ = tm.Printf(tm.Background(tm.Color(tm.Bold("%s"), tm.RED), tm.BLACK), op)
_, _ = tm.Printf(" ")
unexecuted = true
}
}
if !unexecuted {
_, _ = tm.Printf("%s ", op)
}
}
}
_, _ = tm.Printf("\n\n")
}
fmt.Println()
_, _ = tm.Println(tm.Background(tm.Color(tm.Bold("Next Instruction"), tm.WHITE), tm.CYAN))
_, _ = tm.Printf("%s\n\n", dissasm)
_, _ = tm.Println(tm.Background(tm.Color(tm.Bold("Stack"), tm.WHITE), tm.MAGENTA))
var box *tm.Box
if done && !fail {
err = vm.CheckErrorCondition(true)
if err != nil {
done = false
fail = true
}
}
if done && !fail {
box = tm.NewBox(100|tm.PCT, 3, 0)
_, _ = fmt.Fprintf(box, "%s\n", "Success!!!")
} else if fail {
box = tm.NewBox(100|tm.PCT, 3, 0)
_, _ = fmt.Fprintf(box, "%s %s\n", "Fail :(", err)
} else {
box = tm.NewBox(100|tm.PCT, len(vm.GetStack())+2, 0)
stack := vm.GetStack()
for i := len(stack) - 1; i >= 0; i-- {
_, _ = fmt.Fprintf(box, "%s\n", hex.EncodeToString(stack[i]))
}
}
_, _ = tm.Println(box.String())
altstack := vm.GetAltStack()
if len(altstack) > 0 && !done && !fail {
_, _ = tm.Println(tm.Background(tm.Color(tm.Bold("Alt Stack"), tm.WHITE), tm.MAGENTA))
var box *tm.Box
if done && !fail {
err = vm.CheckErrorCondition(true)
if err != nil {
done = false
fail = true
}
}
box = tm.NewBox(100|tm.PCT, len(vm.GetAltStack())+2, 0)
for i := len(altstack) - 1; i >= 0; i-- {
_, _ = fmt.Fprintf(box, "%s\n", hex.EncodeToString(altstack[i]))
}
_, _ = tm.Println(box.String())
}
_, _ = tm.Printf("%s%s%s%s%s%s\n", "F3", tm.Background(tm.Color(tm.Bold("Step Back"), tm.WHITE), tm.CYAN), "F4", tm.Background(tm.Color(tm.Bold("Step Forward"), tm.WHITE), tm.CYAN), "ESC", tm.Background(tm.Color(tm.Bold("Quit"), tm.WHITE), tm.CYAN))
tm.Flush()
if fastForward {
_ = term.Sync()
done, err = vm.Step()
if err != nil {
fail = true
}
if !done {
stateIndex++
savedStates[stateIndex] = vm.Clone()
}
fastForward = !done && !fail && !vm.IsBranchExecuting()
goto scriptLoop
}
for {
switch ev := term.PollEvent(); ev.Type {
case term.EventKey:
switch ev.Key {
case term.KeyEsc:
return nil
case term.KeyF4:
if done {
return nil
}
_ = term.Sync()
done, err = vm.Step()
if err != nil {
fail = true
}
if !done {
stateIndex++
savedStates[stateIndex] = vm.Clone()
}
fastForward = (!done && !vm.IsBranchExecuting())
goto scriptLoop
case term.KeyF3:
_ = term.Sync()
if stateIndex > 0 {
stateIndex--
vm = savedStates[stateIndex].Clone()
}
goto scriptLoop
}
}
}
}