-
Notifications
You must be signed in to change notification settings - Fork 199
/
transactionCostEstimator.go
220 lines (187 loc) · 6.26 KB
/
transactionCostEstimator.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
package transaction
import (
"fmt"
"math/big"
"strconv"
"strings"
"sync"
"github.com/ElrondNetwork/elrond-go-core/core/check"
"github.com/ElrondNetwork/elrond-go-core/data/transaction"
"github.com/ElrondNetwork/elrond-go/facade"
"github.com/ElrondNetwork/elrond-go/process"
"github.com/ElrondNetwork/elrond-go/process/smartContract"
"github.com/ElrondNetwork/elrond-go/process/txsimulator"
"github.com/ElrondNetwork/elrond-go/sharding"
"github.com/ElrondNetwork/elrond-go/state"
vmcommon "github.com/ElrondNetwork/elrond-vm-common"
)
const dummySignature = "01010101"
type transactionCostEstimator struct {
accounts state.AccountsAdapter
shardCoordinator sharding.Coordinator
txTypeHandler process.TxTypeHandler
feeHandler process.FeeHandler
txSimulator facade.TransactionSimulatorProcessor
mutExecution sync.RWMutex
}
// NewTransactionCostEstimator will create a new transaction cost estimator
func NewTransactionCostEstimator(
txTypeHandler process.TxTypeHandler,
feeHandler process.FeeHandler,
txSimulator facade.TransactionSimulatorProcessor,
accounts state.AccountsAdapter,
shardCoordinator sharding.Coordinator,
) (*transactionCostEstimator, error) {
if check.IfNil(txTypeHandler) {
return nil, process.ErrNilTxTypeHandler
}
if check.IfNil(feeHandler) {
return nil, process.ErrNilEconomicsFeeHandler
}
if check.IfNil(txSimulator) {
return nil, txsimulator.ErrNilTxSimulatorProcessor
}
if check.IfNil(shardCoordinator) {
return nil, process.ErrNilShardCoordinator
}
if check.IfNil(accounts) {
return nil, process.ErrNilAccountsAdapter
}
return &transactionCostEstimator{
txTypeHandler: txTypeHandler,
feeHandler: feeHandler,
txSimulator: txSimulator,
accounts: accounts,
shardCoordinator: shardCoordinator,
}, nil
}
// ComputeTransactionGasLimit will calculate how many gas units a transaction will consume
func (tce *transactionCostEstimator) ComputeTransactionGasLimit(tx *transaction.Transaction) (*transaction.CostResponse, error) {
tce.mutExecution.RLock()
defer tce.mutExecution.RUnlock()
txType, _ := tce.txTypeHandler.ComputeTransactionType(tx)
switch txType {
case process.SCDeployment, process.SCInvoking, process.BuiltInFunctionCall, process.MoveBalance:
return tce.simulateTransactionCost(tx, txType)
case process.RelayedTx, process.RelayedTxV2:
// TODO implement in the next PR
return &transaction.CostResponse{
GasUnits: 0,
ReturnMessage: "cannot compute cost of the relayed transaction",
}, nil
default:
return &transaction.CostResponse{
GasUnits: 0,
ReturnMessage: process.ErrWrongTransaction.Error(),
}, nil
}
}
func (tce *transactionCostEstimator) simulateTransactionCost(tx *transaction.Transaction, txType process.TransactionType) (*transaction.CostResponse, error) {
err := tce.addMissingFieldsIfNeeded(tx)
if err != nil {
return nil, err
}
res, err := tce.txSimulator.ProcessTx(tx)
if err != nil {
return &transaction.CostResponse{
GasUnits: 0,
ReturnMessage: err.Error(),
}, nil
}
isMoveBalanceOk := txType == process.MoveBalance && res.FailReason == ""
if isMoveBalanceOk {
return &transaction.CostResponse{
GasUnits: tce.feeHandler.ComputeGasLimit(tx),
ReturnMessage: "",
}, nil
}
if res.FailReason != "" {
return &transaction.CostResponse{
GasUnits: 0,
ReturnMessage: res.FailReason,
}, nil
}
if res.VMOutput == nil {
return &transaction.CostResponse{
GasUnits: 0,
ReturnMessage: process.ErrNilVMOutput.Error(),
SmartContractResults: nil,
}, nil
}
if res.VMOutput.ReturnCode == vmcommon.Ok {
return &transaction.CostResponse{
GasUnits: computeGasUnitsBasedOnVMOutput(tx, res.VMOutput),
ReturnMessage: "",
SmartContractResults: res.ScResults,
}, nil
}
return &transaction.CostResponse{
GasUnits: 0,
ReturnMessage: fmt.Sprintf("%s %s", res.VMOutput.ReturnCode.String(), res.VMOutput.ReturnMessage),
SmartContractResults: res.ScResults,
}, nil
}
func computeGasUnitsBasedOnVMOutput(tx *transaction.Transaction, vmOutput *vmcommon.VMOutput) uint64 {
isTooMuchGasProvided := strings.Contains(vmOutput.ReturnMessage, smartContract.TooMuchGasProvidedMessage)
if !isTooMuchGasProvided {
return tx.GasLimit - vmOutput.GasRemaining
}
return tx.GasLimit - extractGasRemainedFromMessage(vmOutput.ReturnMessage)
}
func extractGasRemainedFromMessage(message string) uint64 {
splitMessage := strings.Split(message, "gas remained = ")
if len(splitMessage) < 2 {
log.Warn("extractGasRemainedFromMessage", "error", "cannot split message", "message", message)
return 0
}
gasValue, err := strconv.ParseUint(splitMessage[1], 10, 64)
if err != nil {
log.Warn("extractGasRemainedFromMessage", "error", err.Error())
return 0
}
return gasValue
}
func (tce *transactionCostEstimator) addMissingFieldsIfNeeded(tx *transaction.Transaction) error {
if tx.GasPrice == 0 {
tx.GasPrice = tce.feeHandler.MinGasPrice()
}
if len(tx.Signature) == 0 {
tx.Signature = []byte(dummySignature)
}
if tx.GasLimit == 0 {
var err error
tx.GasLimit, err = tce.getTxGasLimit(tx)
return err
}
return nil
}
func (tce *transactionCostEstimator) getTxGasLimit(tx *transaction.Transaction) (uint64, error) {
selfShardID := tce.shardCoordinator.SelfId()
maxGasLimitPerBlock := tce.feeHandler.MaxGasLimitPerBlock(selfShardID) - 1
senderShardID := tce.shardCoordinator.ComputeId(tx.SndAddr)
if tce.shardCoordinator.SelfId() != senderShardID {
return maxGasLimitPerBlock, nil
}
accountHandler, err := tce.accounts.LoadAccount(tx.SndAddr)
if err != nil {
return 0, err
}
if check.IfNil(accountHandler) {
return 0, process.ErrInsufficientFee
}
accountSender, ok := accountHandler.(state.UserAccountHandler)
if !ok {
return 0, process.ErrInsufficientFee
}
accountSenderBalance := accountSender.GetBalance()
tx.GasLimit = maxGasLimitPerBlock
txFee := tce.feeHandler.ComputeTxFee(tx)
if txFee.Cmp(accountSenderBalance) > 0 && big.NewInt(0).Cmp(accountSenderBalance) != 0 {
return tce.feeHandler.ComputeGasLimitBasedOnBalance(tx, accountSenderBalance)
}
return maxGasLimitPerBlock, nil
}
// IsInterfaceNil returns true if there is no value under the interface
func (tce *transactionCostEstimator) IsInterfaceNil() bool {
return tce == nil
}