-
Notifications
You must be signed in to change notification settings - Fork 39
/
evm_facade.go
373 lines (328 loc) · 12.3 KB
/
evm_facade.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
package evm
import (
"context"
"errors"
"fmt"
"math/big"
_ "unsafe"
"github.com/ethereum/go-ethereum/core/tracing"
"github.com/holiman/uint256"
"github.com/ten-protocol/go-ten/go/config"
// unsafe package imported in order to link to a private function in go-ethereum.
// This allows us to customize the message generated from a signed transaction and inject custom gas logic.
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/params"
"github.com/ten-protocol/go-ten/go/common"
"github.com/ten-protocol/go-ten/go/common/errutil"
"github.com/ten-protocol/go-ten/go/common/gethencoding"
"github.com/ten-protocol/go-ten/go/common/log"
"github.com/ten-protocol/go-ten/go/common/measure"
"github.com/ten-protocol/go-ten/go/enclave/core"
"github.com/ten-protocol/go-ten/go/enclave/crypto"
"github.com/ten-protocol/go-ten/go/enclave/storage"
gethcommon "github.com/ethereum/go-ethereum/common"
gethcore "github.com/ethereum/go-ethereum/core"
gethlog "github.com/ethereum/go-ethereum/log"
gethrpc "github.com/ten-protocol/go-ten/lib/gethfork/rpc"
)
var ErrGasNotEnoughForL1 = errors.New("gas limit too low to pay for execution and l1 fees")
type TxExecResult struct {
Receipt *types.Receipt
CreatedContracts []*gethcommon.Address
Err error
}
// ExecuteTransactions
// header - the header of the rollup where this transaction will be included
// fromTxIndex - for the receipts and events, the evm needs to know for each transaction the order in which it was executed in the block.
func ExecuteTransactions(
ctx context.Context,
txs common.L2PricedTransactions,
s *state.StateDB,
header *common.BatchHeader,
storage storage.Storage,
gethEncodingService gethencoding.EncodingService,
chainConfig *params.ChainConfig,
config config.EnclaveConfig,
fromTxIndex int,
noBaseFee bool,
batchGasLimit uint64,
logger gethlog.Logger,
) (map[common.TxHash]*TxExecResult, error) {
chain, vmCfg := initParams(storage, gethEncodingService, config, noBaseFee, logger)
gp := gethcore.GasPool(batchGasLimit)
zero := uint64(0)
usedGas := &zero
result := map[common.TxHash]*TxExecResult{}
ethHeader, err := gethEncodingService.CreateEthHeaderForBatch(ctx, header)
if err != nil {
logger.Error("Could not convert to eth header", log.ErrKey, err)
return nil, err
}
hash := header.Hash()
// tCountRollback - every time a transaction errors out, rather than producing a receipt
// we push back the index in the "block" (batch) it will have. This means that errored out transactions
// will be shunted by their follow up successful transaction.
// This also means the mix digest can be the same for two transactions, but
// as the error one reverts and cant mutate the state in order to push back the counter
// this should not open up any attack vectors on the randomness.
tCountRollback := 0
for i, t := range txs {
txResult := &TxExecResult{}
result[t.Tx.Hash()] = txResult
r, createdContracts, err := executeTransaction(
s,
chainConfig,
chain,
&gp,
ethHeader,
t,
usedGas,
vmCfg,
(fromTxIndex+i)-tCountRollback,
hash,
header.Number.Uint64(),
)
if err != nil {
tCountRollback++
txResult.Err = err
// only log tx execution errors if they are unexpected
logFailedTx := logger.Info
if errors.Is(err, gethcore.ErrNonceTooHigh) || errors.Is(err, gethcore.ErrNonceTooLow) || errors.Is(err, gethcore.ErrFeeCapTooLow) || errors.Is(err, ErrGasNotEnoughForL1) {
logFailedTx = logger.Debug
}
logFailedTx("Failed to execute tx:", log.TxKey, t.Tx.Hash(), log.CtrErrKey, err)
continue
}
logReceipt(r, logger)
txResult.Receipt = r
txResult.CreatedContracts = createdContracts
}
s.Finalise(true)
return result, nil
}
const (
BalanceDecreaseL1Payment tracing.BalanceChangeReason = 100
BalanceIncreaseL1Payment tracing.BalanceChangeReason = 101
BalanceRevertDecreaseL1Payment tracing.BalanceChangeReason = 102
BalanceRevertIncreaseL1Payment tracing.BalanceChangeReason = 103
)
func executeTransaction(
s *state.StateDB,
cc *params.ChainConfig,
chain *ObscuroChainContext,
gp *gethcore.GasPool,
header *types.Header,
t common.L2PricedTransaction,
usedGas *uint64,
vmCfg vm.Config,
tCount int,
batchHash common.L2BatchHash,
batchHeight uint64,
) (*types.Receipt, []*gethcommon.Address, error) {
var createdContracts []*gethcommon.Address
rules := cc.Rules(big.NewInt(0), true, 0)
from, err := types.Sender(types.LatestSigner(cc), t.Tx)
if err != nil {
return nil, nil, err
}
s.Prepare(rules, from, gethcommon.Address{}, t.Tx.To(), nil, nil)
snap := s.Snapshot()
s.SetTxContext(t.Tx.Hash(), tCount)
s.SetLogger(&tracing.Hooks{
// called when the code of a contract changes.
OnCodeChange: func(addr gethcommon.Address, prevCodeHash gethcommon.Hash, prevCode []byte, codeHash gethcommon.Hash, code []byte) {
// only proceed for new deployments.
if len(prevCode) > 0 {
return
}
createdContracts = append(createdContracts, &addr)
},
})
defer s.SetLogger(nil)
before := header.MixDigest
// calculate a random value per transaction
header.MixDigest = crypto.CalculateTxRnd(before.Bytes(), tCount)
applyTx := func(
config *params.ChainConfig,
bc gethcore.ChainContext,
author *gethcommon.Address,
gp *gethcore.GasPool,
statedb *state.StateDB,
header *types.Header,
tx common.L2PricedTransaction,
usedGas *uint64,
cfg vm.Config,
) (*types.Receipt, error) {
msg, err := gethcore.TransactionToMessage(tx.Tx, types.MakeSigner(config, header.Number, header.Time), header.BaseFee)
if err != nil {
return nil, err
}
l1cost := tx.PublishingCost
l1Gas := big.NewInt(0)
hasL1Cost := l1cost.Cmp(big.NewInt(0)) != 0
// If a transaction has to be published on the l1, it will have an l1 cost
if hasL1Cost {
l1Gas.Div(l1cost, header.BaseFee) // TotalCost/CostPerGas = Gas
l1Gas.Add(l1Gas, big.NewInt(1)) // Cover from leftover from the division
// The gas limit of the transaction (evm message) should always be higher than the gas overhead
// used to cover the l1 cost
// todo - this check has to be added to the mempool as well
if msg.GasLimit < l1Gas.Uint64() {
return nil, fmt.Errorf("%w. Want at least: %d have: %d", ErrGasNotEnoughForL1, l1Gas, msg.GasLimit)
}
// Remove the gas overhead for l1 publishing from the gas limit in order to define
// the actual gas limit for execution
msg.GasLimit -= l1Gas.Uint64()
// Remove the l1 cost from the sender
// and pay it to the coinbase of the batch
statedb.SubBalance(msg.From, uint256.MustFromBig(l1cost), BalanceDecreaseL1Payment)
statedb.AddBalance(header.Coinbase, uint256.MustFromBig(l1cost), BalanceIncreaseL1Payment)
}
// Create a new context to be used in the EVM environment
blockContext := gethcore.NewEVMBlockContext(header, bc, author)
vmenv := vm.NewEVM(blockContext, vm.TxContext{BlobHashes: tx.Tx.BlobHashes(), GasPrice: header.BaseFee}, statedb, config, cfg)
var receipt *types.Receipt
receipt, err = gethcore.ApplyTransactionWithEVM(msg, config, gp, statedb, header.Number, header.Hash(), tx.Tx, usedGas, vmenv)
if err != nil {
// If the transaction has l1 cost, then revert the funds exchange
// as it will not be published on error (no receipt condition)
if hasL1Cost {
statedb.SubBalance(header.Coinbase, uint256.MustFromBig(l1cost), BalanceRevertIncreaseL1Payment)
statedb.AddBalance(msg.From, uint256.MustFromBig(l1cost), BalanceRevertDecreaseL1Payment)
}
return receipt, err
}
// Do not increase the balance of zero address as it is the contract deployment address.
// Doing so might cause weird interactions.
if header.Coinbase.Big().Cmp(gethcommon.Big0) != 0 {
gasUsed := big.NewInt(0).SetUint64(receipt.GasUsed)
executionGasCost := big.NewInt(0).Mul(gasUsed, header.BaseFee)
// As the baseFee is burned, we add it back to the coinbase.
// Geth should automatically add the tips.
statedb.AddBalance(header.Coinbase, uint256.MustFromBig(executionGasCost), tracing.BalanceDecreaseGasBuy)
}
receipt.GasUsed += l1Gas.Uint64()
return receipt, err
}
receipt, err := applyTx(cc, chain, nil, gp, s, header, t, usedGas, vmCfg)
// adjust the receipt to point to the right batch hash
if receipt != nil {
receipt.Logs = s.GetLogs(t.Tx.Hash(), batchHeight, batchHash)
receipt.BlockHash = batchHash
receipt.BlockNumber = big.NewInt(int64(batchHeight))
for _, l := range receipt.Logs {
l.BlockHash = batchHash
}
}
header.MixDigest = before
if err != nil {
s.RevertToSnapshot(snap)
return receipt, nil, err
}
return receipt, createdContracts, nil
}
func logReceipt(r *types.Receipt, logger gethlog.Logger) {
if logger.Enabled(context.Background(), gethlog.LevelTrace) {
logger.Trace("Receipt", log.TxKey, r.TxHash, "Result", receiptToString(r))
}
}
func receiptToString(r *types.Receipt) string {
receiptJSON, err := r.MarshalJSON()
if err != nil {
if r.Status == types.ReceiptStatusFailed {
return "Unsuccessful (status != 1) (but could not print receipt as JSON)"
}
return "Successfully executed (but could not print receipt as JSON)"
}
if r.Status == types.ReceiptStatusFailed {
return fmt.Sprintf("Unsuccessful (status != 1). Receipt: %s", string(receiptJSON))
}
return fmt.Sprintf("Successfully executed. Receipt: %s", string(receiptJSON))
}
// ExecuteObsCall - executes the eth_call call
func ExecuteObsCall(
ctx context.Context,
msg *gethcore.Message,
s *state.StateDB,
header *common.BatchHeader,
storage storage.Storage,
gethEncodingService gethencoding.EncodingService,
chainConfig *params.ChainConfig,
gasEstimationCap uint64,
config config.EnclaveConfig,
logger gethlog.Logger,
) (*gethcore.ExecutionResult, error) {
noBaseFee := true
if header.BaseFee != nil && header.BaseFee.Cmp(gethcommon.Big0) != 0 && msg.GasPrice.Cmp(gethcommon.Big0) != 0 {
noBaseFee = false
}
defer core.LogMethodDuration(logger, measure.NewStopwatch(), "evm_facade.go:ObsCall()")
gp := gethcore.GasPool(gasEstimationCap)
gp.SetGas(gasEstimationCap)
chain, vmCfg := initParams(storage, gethEncodingService, config, noBaseFee, nil)
ethHeader, err := gethEncodingService.CreateEthHeaderForBatch(ctx, header)
if err != nil {
return nil, err
}
blockContext := gethcore.NewEVMBlockContext(ethHeader, chain, nil)
// sets TxKey.origin
txContext := gethcore.NewEVMTxContext(msg)
vmenv := vm.NewEVM(blockContext, txContext, s, chainConfig, vmCfg)
result, err := gethcore.ApplyMessage(vmenv, msg, &gp)
// Follow the same error check structure as in geth
// 1 - vmError / stateDB err check
// 2 - evm.Cancelled() todo (#1576) - support the ability to cancel function call if it takes too long
// 3 - error check the ApplyMessage
// Read the error stored in the database.
if dbErr := s.Error(); dbErr != nil {
return nil, newErrorWithReasonAndCode(dbErr)
}
// If the result contains a revert reason, try to unpack and return it.
if result != nil && len(result.Revert()) > 0 {
return nil, newRevertError(result)
}
if err != nil {
// also return the result as the result can be evaluated on some errors like ErrIntrinsicGas
logger.Debug(fmt.Sprintf("Error applying msg %v:", msg), log.CtrErrKey, err)
return result, err
}
return result, nil
}
func initParams(storage storage.Storage, gethEncodingService gethencoding.EncodingService, config config.EnclaveConfig, noBaseFee bool, l gethlog.Logger) (*ObscuroChainContext, vm.Config) {
vmCfg := vm.Config{
NoBaseFee: noBaseFee,
}
return NewObscuroChainContext(storage, gethEncodingService, config, l), vmCfg
}
func newErrorWithReasonAndCode(err error) error {
result := &errutil.DataError{
Err: err.Error(),
}
var e gethrpc.Error
ok := errors.As(err, &e)
if ok {
result.Code = e.ErrorCode()
}
var de gethrpc.DataError
ok = errors.As(err, &de)
if ok {
result.Reason = de.ErrorData()
}
return result
}
func newRevertError(result *gethcore.ExecutionResult) error {
reason, errUnpack := abi.UnpackRevert(result.Revert())
err := errors.New("execution reverted")
if errUnpack == nil {
err = fmt.Errorf("execution reverted: %v", reason)
}
return &errutil.DataError{
Err: err.Error(),
Reason: hexutil.Encode(result.Revert()),
Code: 3, // todo - magic number, really needs thought around the value and made a constant
}
}