-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinterpreter.go
464 lines (387 loc) · 11.7 KB
/
interpreter.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
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
package cli
import (
"context"
"encoding/base64"
"fmt"
"strconv"
"sync/atomic"
"time"
"github.com/btcsuite/btcutil/base58"
"github.com/koinos/koinos-cli/internal/cliutil"
"github.com/koinos/koinos-proto-golang/koinos/protocol"
util "github.com/koinos/koinos-util-golang"
)
// Command execution code
// Actual command implementations are in commands.go
const (
// NonceCheckTime is the time between nonce checks
NonceCheckTime = time.Second * 30
SelfPayer = "me"
AutoNonce = "auto"
AutoChainID = "auto"
)
// Command is the interface that all commands must implement
type Command interface {
Execute(ctx context.Context, ee *ExecutionEnvironment) (*ExecutionResult, error)
}
// ExecutionResult is the result of a command execution
type ExecutionResult struct {
Message []string
}
// NewExecutionResult creates a new execution result object
func NewExecutionResult() *ExecutionResult {
m := make([]string, 0)
return &ExecutionResult{Message: m}
}
// AddMessage adds a message to the execution result
func (er *ExecutionResult) AddMessage(m ...string) {
er.Message = append(er.Message, m...)
}
// Print prints each message in the execution result
func (er *ExecutionResult) Print() {
for _, m := range er.Message {
fmt.Println(m)
}
}
type rcInfo struct {
value uint64
absolute bool
}
type nonceInfo struct {
currentNonce uint64
nonceTime time.Time
}
// ExecutionEnvironment is a struct that holds the environment for command execution.
type ExecutionEnvironment struct {
RPCClient *cliutil.KoinosRPCClient
Key *util.KoinosKey
Parser *CommandParser
Contracts Contracts
Session *TransactionSession
nonceMap map[string]*nonceInfo
nonceMode string
rcLimit rcInfo
payer string
chainID string
}
// NewExecutionEnvironment creates a new ExecutionEnvironment object
func NewExecutionEnvironment(rpcClient *cliutil.KoinosRPCClient, parser *CommandParser) *ExecutionEnvironment {
return &ExecutionEnvironment{
RPCClient: rpcClient,
Parser: parser,
Contracts: make(map[string]*ContractInfo),
Session: &TransactionSession{},
nonceMap: make(map[string]*nonceInfo),
rcLimit: rcInfo{value: 100000000, absolute: false},
payer: SelfPayer,
chainID: AutoChainID,
nonceMode: AutoNonce,
}
}
// OpenWallet opens a wallet
func (ee *ExecutionEnvironment) OpenWallet(key *util.KoinosKey) {
ee.Key = key
}
// CloseWallet closes the wallet
func (ee *ExecutionEnvironment) CloseWallet() {
ee.Key = nil
}
// IsSelfPaying returns a bool representing whether or not the user is self paying
func (ee *ExecutionEnvironment) IsSelfPaying() bool {
return ee.payer == SelfPayer
}
// GetPayer returns the current payer address
func (ee *ExecutionEnvironment) GetPayerAddress() []byte {
if ee.IsSelfPaying() {
return ee.Key.AddressBytes()
}
return base58.Decode(ee.payer)
}
// SetPayer sets the payer
func (ee *ExecutionEnvironment) SetPayer(payer string) {
ee.payer = payer
}
// ResetNonce resets the nonce
func (ee *ExecutionEnvironment) ResetNonce() {
if nInfo, exists := ee.nonceMap[string(ee.Key.AddressBytes())]; exists {
atomic.StoreUint64(&nInfo.currentNonce, 0)
nInfo.nonceTime = time.Time{}
}
}
// IsNonceAuto returns a bool representing whether or not the nonce is being automatically fetched
func (ee *ExecutionEnvironment) IsNonceAuto() bool {
return ee.nonceMode == AutoNonce
}
// GetNextNonce returns the current nonce
func (ee *ExecutionEnvironment) GetNextNonce(ctx context.Context, update bool) (uint64, error) {
if !ee.IsNonceAuto() {
return strconv.ParseUint(ee.nonceMode, 10, 64)
}
nInfo, exists := ee.nonceMap[string(ee.Key.AddressBytes())]
if !exists {
nInfo = &nonceInfo{}
ee.nonceMap[string(ee.Key.AddressBytes())] = nInfo
}
if nInfo.nonceTime.IsZero() || time.Since(nInfo.nonceTime) > NonceCheckTime {
nonce, err := ee.RPCClient.GetAccountNonce(ctx, ee.Key.AddressBytes())
if err != nil {
return 0, err
}
nInfo.nonceTime = time.Now()
atomic.StoreUint64(&nInfo.currentNonce, nonce)
}
nonce := nInfo.currentNonce + 1
if update {
nInfo.nonceTime = time.Now()
atomic.AddUint64(&nInfo.currentNonce, 1)
}
return nonce, nil
}
// IsChainIDAuto returns a bool representing whether or not the chain ID is being automatically fetched
func (ee *ExecutionEnvironment) IsChainIDAuto() bool {
return ee.chainID == AutoChainID
}
// GetChainID returns the current chain ID
func (ee *ExecutionEnvironment) GetChainID(ctx context.Context) ([]byte, error) {
if ee.IsChainIDAuto() {
return ee.RPCClient.GetChainID(ctx)
}
return base64.URLEncoding.DecodeString(ee.chainID)
}
// GetRcLimit returns the current RC limit
func (ee *ExecutionEnvironment) GetRcLimit(ctx context.Context) (uint64, error) {
if ee.rcLimit.absolute {
return ee.rcLimit.value, nil
}
// else it's relative
limit, err := ee.RPCClient.GetAccountRc(ctx, ee.Key.AddressBytes())
if err != nil {
return 0, err
}
decLimit, err := util.SatoshiToDecimal(limit, 8)
if err != nil {
return 0, err
}
decVal, err := util.SatoshiToDecimal(ee.rcLimit.value, 8)
if err != nil {
return 0, err
}
decResult := decLimit.Mul(*decVal)
res, err := util.DecimalToSatoshi(&decResult, 8)
if err != nil {
return 0, err
}
return res, nil
}
// SubmitTransaction is a utility function to submit a transaction from a command
func (ee *ExecutionEnvironment) SubmitTransaction(ctx context.Context, result *ExecutionResult, ops ...*protocol.Operation) error {
// Fetch the nonce
subParams, err := ee.GetSubmissionParams(ctx)
if err != nil {
return err
}
receipt, err := ee.RPCClient.SubmitTransactionOpsWithPayer(ctx, ops, ee.Key, subParams, ee.GetPayerAddress(), true)
if err != nil {
ee.ResetNonce()
return err
}
result.AddMessage(cliutil.TransactionReceiptToString(receipt, len(ops)))
return nil
}
// GetSubmissionParams returns the submission parameters for a command
func (ee *ExecutionEnvironment) GetSubmissionParams(ctx context.Context) (*cliutil.SubmissionParams, error) {
nonce, err := ee.GetNextNonce(ctx, true)
if err != nil {
return nil, err
}
rcLimit, err := ee.GetRcLimit(ctx)
if err != nil {
return nil, err
}
return &cliutil.SubmissionParams{
Nonce: nonce,
RCLimit: rcLimit,
}, nil
}
// IsWalletOpen returns a bool representing whether or not there is an open wallet
func (ee *ExecutionEnvironment) IsWalletOpen() bool {
return ee.Key != nil
}
// IsOnline returns a bool representing whether or not the wallet is online
func (ee *ExecutionEnvironment) IsOnline() bool {
return ee.RPCClient != nil
}
func (ee *ExecutionEnvironment) CreateSignedTransaction(ctx context.Context, ops ...*protocol.Operation) (*protocol.Transaction, error) {
nonce, err := ee.GetNextNonce(ctx, true)
if err != nil {
return nil, err
}
rcLimit, err := ee.GetRcLimit(ctx)
if err != nil {
return nil, err
}
chainID, err := ee.GetChainID(ctx)
if err != nil {
return nil, err
}
payer := ee.GetPayerAddress()
txn, err := cliutil.CreateSignedTransaction(ctx, ops, ee.Key, nonce, rcLimit, chainID, payer)
if err != nil {
return nil, fmt.Errorf("cannot submit transaction session, %w", err)
}
return txn, nil
}
// CommandDeclaration is a struct that declares a command
type CommandDeclaration struct {
Name string
Description string
Instantiation func(*CommandParseResult) Command
Args []CommandArg
Hidden bool // If true, the command is not shown in the help
}
func (d *CommandDeclaration) String() string {
s := d.Name
for _, arg := range d.Args {
s += fmt.Sprintf(" %s", arg.String())
}
return s
}
// NewCommandDeclaration create a new command declaration
func NewCommandDeclaration(name string, description string, hidden bool,
instantiation func(*CommandParseResult) Command, args ...CommandArg) *CommandDeclaration {
// Ensure optionals are only at the end
req := true
for _, arg := range args {
if !arg.Optional {
if !req {
return nil
}
} else {
req = false
}
}
return &CommandDeclaration{
Name: name,
Description: description,
Hidden: hidden,
Instantiation: instantiation,
Args: args,
}
}
// CommandArg is a struct that holds an argument for a command
type CommandArg struct {
Name string
ArgType CommandArgType
Optional bool
}
// NewCommandArg creates a new command argument
func NewCommandArg(name string, argType CommandArgType) *CommandArg {
return &CommandArg{
Name: name,
ArgType: argType,
Optional: false,
}
}
// NewOptionalCommandArg creates a new optional command argument
func NewOptionalCommandArg(name string, argType CommandArgType) *CommandArg {
return &CommandArg{
Name: name,
ArgType: argType,
Optional: true,
}
}
func (arg *CommandArg) String() string {
filling := fmt.Sprintf("%s:%s", arg.Name, arg.ArgType.String())
var val string
if arg.Optional {
val = "[" + filling + "]"
} else {
val = "<" + filling + ">"
}
return val
}
// InterpretResults is a struct that holds the results of a multi-command interpretation
type InterpretResults struct {
Results []string
}
// NewInterpretResults creates a new InterpretResults object
func NewInterpretResults() *InterpretResults {
ir := &InterpretResults{}
ir.Results = make([]string, 0)
return ir
}
// AddResult adds a result to the InterpretResults
func (ir *InterpretResults) AddResult(result ...string) {
ir.Results = append(ir.Results, result...)
}
// Print prints the results of a command interpretation
func (ir *InterpretResults) Print() {
for _, result := range ir.Results {
fmt.Println(result)
}
// If there were results, skip a line at the end for readability
if len(ir.Results) > 0 {
fmt.Println("")
}
}
// Interpret interprets and executes the results of a command parse
func (pr *ParseResults) Interpret(ee *ExecutionEnvironment) *InterpretResults {
output := NewInterpretResults()
for _, inv := range pr.CommandResults {
cmd := inv.Instantiate()
result, err := cmd.Execute(context.Background(), ee)
if err != nil {
output.AddResult(err.Error())
} else {
output.AddResult(result.Message...)
}
}
return output
}
// ParseResultMetrics is a struct that holds various data about the parse results
// It is useful for interactive mode suggestions and error reporting
type ParseResultMetrics struct {
CurrentResultIndex int
CurrentArg int
CurrentParamType CommandArgType
}
// Metrics is a function that returns a ParseResultMetrics object
func (pr *ParseResults) Metrics() *ParseResultMetrics {
if len(pr.CommandResults) == 0 {
return &ParseResultMetrics{CurrentResultIndex: 0, CurrentArg: -1, CurrentParamType: CmdNameArg}
}
index := len(pr.CommandResults) - 1
arg := pr.CommandResults[index].CurrentArg
if pr.CommandResults[index].Termination == CommandTermination {
index++
arg = -1
}
// Calculated the type of param
pType := CmdNameArg
if arg >= 0 {
// If there is a declaration, find the type of the param
if pr.CommandResults[index].Decl != nil {
pType = pr.CommandResults[index].Decl.Args[arg].ArgType
} else { // Otherwise it is an invalid command
pType = NoArg
}
}
return &ParseResultMetrics{CurrentResultIndex: index, CurrentArg: arg, CurrentParamType: pType}
}
// ParseAndInterpret is a helper function to parse and interpret the given command string
func ParseAndInterpret(parser *CommandParser, ee *ExecutionEnvironment, input string) *InterpretResults {
result, err := parser.Parse(input)
if err != nil {
o := NewInterpretResults()
o.AddResult(err.Error())
metrics := result.Metrics()
// Display help for the command if it is a valid command
if len(result.CommandResults) > 0 && result.CommandResults[metrics.CurrentResultIndex].Decl != nil {
o.AddResult("Usage: " + result.CommandResults[metrics.CurrentResultIndex].Decl.String())
} else {
o.AddResult("Type \"list\" for a list of commands.")
}
return o
}
return result.Interpret(ee)
}