-
Notifications
You must be signed in to change notification settings - Fork 202
/
transactionSimulator.go
289 lines (248 loc) · 8.98 KB
/
transactionSimulator.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
package transactionEvaluator
import (
"encoding/hex"
"sync"
"github.com/multiversx/mx-chain-core-go/core"
"github.com/multiversx/mx-chain-core-go/core/check"
"github.com/multiversx/mx-chain-core-go/data/block"
"github.com/multiversx/mx-chain-core-go/data/receipt"
"github.com/multiversx/mx-chain-core-go/data/smartContractResult"
"github.com/multiversx/mx-chain-core-go/data/transaction"
"github.com/multiversx/mx-chain-core-go/hashing"
"github.com/multiversx/mx-chain-core-go/marshal"
"github.com/multiversx/mx-chain-go/node/external/transactionAPI"
"github.com/multiversx/mx-chain-go/process"
txSimData "github.com/multiversx/mx-chain-go/process/transactionEvaluator/data"
"github.com/multiversx/mx-chain-go/sharding"
"github.com/multiversx/mx-chain-go/storage"
logger "github.com/multiversx/mx-chain-logger-go"
vmcommon "github.com/multiversx/mx-chain-vm-common-go"
)
var log = logger.GetOrCreate("process/txSimulator")
// ArgsTxSimulator holds the arguments required for creating a new transaction simulator
type ArgsTxSimulator struct {
TransactionProcessor TransactionProcessor
IntermediateProcContainer process.IntermediateProcessorContainer
AddressPubKeyConverter core.PubkeyConverter
ShardCoordinator sharding.Coordinator
VMOutputCacher storage.Cacher
Hasher hashing.Hasher
Marshalizer marshal.Marshalizer
DataFieldParser DataFieldParser
}
type refundHandler interface {
IsRefund(input transactionAPI.RefundDetectorInput) bool
}
type transactionSimulator struct {
mutOperation sync.Mutex
txProcessor TransactionProcessor
intermProcContainer process.IntermediateProcessorContainer
addressPubKeyConverter core.PubkeyConverter
shardCoordinator sharding.Coordinator
vmOutputCacher storage.Cacher
hasher hashing.Hasher
marshalizer marshal.Marshalizer
refundDetector refundHandler
dataFieldParser DataFieldParser
}
// NewTransactionSimulator returns a new instance of a transactionSimulator
func NewTransactionSimulator(args ArgsTxSimulator) (*transactionSimulator, error) {
if check.IfNil(args.TransactionProcessor) {
return nil, ErrNilTxSimulatorProcessor
}
if check.IfNil(args.IntermediateProcContainer) {
return nil, ErrNilIntermediateProcessorContainer
}
if check.IfNil(args.AddressPubKeyConverter) {
return nil, ErrNilPubkeyConverter
}
if check.IfNil(args.ShardCoordinator) {
return nil, ErrNilShardCoordinator
}
if check.IfNil(args.VMOutputCacher) {
return nil, ErrNilCacher
}
if check.IfNil(args.Marshalizer) {
return nil, ErrNilMarshalizer
}
if check.IfNil(args.Hasher) {
return nil, ErrNilHasher
}
if check.IfNilReflect(args.DataFieldParser) {
return nil, ErrNilDataFieldParser
}
return &transactionSimulator{
txProcessor: args.TransactionProcessor,
intermProcContainer: args.IntermediateProcContainer,
addressPubKeyConverter: args.AddressPubKeyConverter,
shardCoordinator: args.ShardCoordinator,
vmOutputCacher: args.VMOutputCacher,
marshalizer: args.Marshalizer,
hasher: args.Hasher,
refundDetector: transactionAPI.NewRefundDetector(),
dataFieldParser: args.DataFieldParser,
}, nil
}
// ProcessTx will process the transaction in a special environment, where state-writing is not allowed
func (ts *transactionSimulator) ProcessTx(tx *transaction.Transaction) (*txSimData.SimulationResultsWithVMOutput, error) {
ts.mutOperation.Lock()
defer ts.mutOperation.Unlock()
txStatus := transaction.TxStatusPending
failReason := ""
retCode, err := ts.txProcessor.ProcessTransaction(tx)
if err != nil {
failReason = err.Error()
txStatus = transaction.TxStatusFail
} else {
if retCode == vmcommon.Ok {
txStatus = transaction.TxStatusSuccess
}
}
results := &txSimData.SimulationResultsWithVMOutput{
SimulationResults: transaction.SimulationResults{
Status: txStatus,
FailReason: failReason,
},
}
err = ts.addIntermediateTxsToResult(results)
if err != nil {
return nil, err
}
vmOutput, ok := ts.getVMOutputOfTx(tx)
if ok {
results.VMOutput = vmOutput
}
ts.addLogsFromVmOutput(results, vmOutput)
return results, nil
}
func (ts *transactionSimulator) addLogsFromVmOutput(results *txSimData.SimulationResultsWithVMOutput, vmOutput *vmcommon.VMOutput) {
if vmOutput == nil || len(vmOutput.Logs) == 0 {
return
}
results.Logs = &transaction.ApiLogs{
Events: make([]*transaction.Events, 0, len(vmOutput.Logs)),
}
for _, entry := range vmOutput.Logs {
results.Logs.Events = append(results.Logs.Events, &transaction.Events{
Address: ts.addressPubKeyConverter.SilentEncode(entry.Address, log),
Identifier: string(entry.Identifier),
Topics: entry.Topics,
Data: entry.GetFirstDataItem(),
})
}
}
func (ts *transactionSimulator) getVMOutputOfTx(tx *transaction.Transaction) (*vmcommon.VMOutput, bool) {
txHash, err := core.CalculateHash(ts.marshalizer, ts.hasher, tx)
if err != nil {
return nil, false
}
defer ts.vmOutputCacher.Remove(txHash)
vmOutputInterface, ok := ts.vmOutputCacher.Get(txHash)
if !ok || check.IfNilReflect(vmOutputInterface) {
return nil, false
}
vmOutput, ok := vmOutputInterface.(*vmcommon.VMOutput)
if !ok {
return nil, false
}
return vmOutput, true
}
func (ts *transactionSimulator) addIntermediateTxsToResult(result *txSimData.SimulationResultsWithVMOutput) error {
defer func() {
processorsKeys := ts.intermProcContainer.Keys()
for _, procKey := range processorsKeys {
processor, errGetProc := ts.intermProcContainer.Get(procKey)
if errGetProc != nil || processor == nil {
continue
}
processor.CreateBlockStarted()
}
}()
scrForwarder, err := ts.intermProcContainer.Get(block.SmartContractResultBlock)
if err != nil {
return err
}
scResults := make(map[string]*transaction.ApiSmartContractResult)
for hash, value := range scrForwarder.GetAllCurrentFinishedTxs() {
scr, ok := value.(*smartContractResult.SmartContractResult)
if !ok {
continue
}
scResults[hex.EncodeToString([]byte(hash))] = ts.adaptSmartContractResult(scr)
}
result.ScResults = scResults
if ts.shardCoordinator.SelfId() == core.MetachainShardId {
return nil
}
receiptsForwarder, err := ts.intermProcContainer.Get(block.ReceiptBlock)
if err != nil {
return err
}
receipts := make(map[string]*transaction.ApiReceipt)
for hash, value := range receiptsForwarder.GetAllCurrentFinishedTxs() {
rcpt, ok := value.(*receipt.Receipt)
if !ok {
continue
}
receipts[hex.EncodeToString([]byte(hash))] = ts.adaptReceipt(rcpt)
}
result.Receipts = receipts
return nil
}
func (ts *transactionSimulator) adaptSmartContractResult(scr *smartContractResult.SmartContractResult) *transaction.ApiSmartContractResult {
isRefund := ts.refundDetector.IsRefund(transactionAPI.RefundDetectorInput{
Value: scr.Value.String(),
Data: scr.Data,
ReturnMessage: string(scr.ReturnMessage),
GasLimit: scr.GasLimit,
})
res := ts.dataFieldParser.Parse(scr.Data, scr.SndAddr, scr.RcvAddr, ts.shardCoordinator.NumberOfShards())
receiversEncoded, err := ts.addressPubKeyConverter.EncodeSlice(res.Receivers)
if err != nil {
log.Warn("transactionSimulator.adaptSmartContractResult: cannot encode receivers slice", "error", err)
}
resScr := &transaction.ApiSmartContractResult{
Nonce: scr.Nonce,
Value: scr.Value,
RcvAddr: ts.addressPubKeyConverter.SilentEncode(scr.RcvAddr, log),
SndAddr: ts.addressPubKeyConverter.SilentEncode(scr.SndAddr, log),
RelayedValue: scr.RelayedValue,
Code: hex.EncodeToString(scr.Code),
Data: string(scr.Data),
PrevTxHash: hex.EncodeToString(scr.PrevTxHash),
OriginalTxHash: hex.EncodeToString(scr.OriginalTxHash),
GasLimit: scr.GasLimit,
GasPrice: scr.GasPrice,
CallType: scr.CallType,
CodeMetadata: hex.EncodeToString(scr.CodeMetadata),
ReturnMessage: string(scr.ReturnMessage),
IsRefund: isRefund,
Operation: res.Operation,
Function: res.Function,
ESDTValues: res.ESDTValues,
Tokens: res.Tokens,
Receivers: receiversEncoded,
ReceiversShardIDs: res.ReceiversShardID,
IsRelayed: res.IsRelayed,
}
if scr.OriginalSender != nil {
resScr.OriginalSender = ts.addressPubKeyConverter.SilentEncode(scr.OriginalSender, log)
}
if scr.RelayerAddr != nil {
resScr.RelayerAddr = ts.addressPubKeyConverter.SilentEncode(scr.RelayerAddr, log)
}
return resScr
}
func (ts *transactionSimulator) adaptReceipt(rcpt *receipt.Receipt) *transaction.ApiReceipt {
receiptSenderAddress := ts.addressPubKeyConverter.SilentEncode(rcpt.SndAddr, log)
return &transaction.ApiReceipt{
Value: rcpt.Value,
SndAddr: receiptSenderAddress,
Data: string(rcpt.Data),
TxHash: hex.EncodeToString(rcpt.TxHash),
}
}
// IsInterfaceNil returns true if there is no value under the interface
func (ts *transactionSimulator) IsInterfaceNil() bool {
return ts == nil
}