-
Notifications
You must be signed in to change notification settings - Fork 176
/
handler.go
348 lines (293 loc) · 9.33 KB
/
handler.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
package handler
import (
"bytes"
gethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/flow-go/fvm/environment"
"github.com/onflow/flow-go/fvm/errors"
"github.com/onflow/flow-go/fvm/evm/types"
)
// ContractHandler is responsible for triggering calls to emulator, metering,
// event emission and updating the block
//
// TODO and Warning: currently database keeps a copy of roothash, and if after
// commiting the changes by the evm we want to revert in this code we need to reset that
// or we should always do all the checks and return before calling the emulator,
// after that should be only event emissions and computation usage updates.
// thats another reason we first check the computation limit before using.
// in the future we might benefit from a view style of access to db passed as
// a param to the emulator.
type ContractHandler struct {
flowTokenAddress common.Address
blockstore types.BlockStore
addressAllocator types.AddressAllocator
backend types.Backend
emulator types.Emulator
}
func (h *ContractHandler) FlowTokenAddress() common.Address {
return h.flowTokenAddress
}
var _ types.ContractHandler = &ContractHandler{}
func NewContractHandler(
flowTokenAddress common.Address,
blockstore types.BlockStore,
addressAllocator types.AddressAllocator,
backend types.Backend,
emulator types.Emulator,
) *ContractHandler {
return &ContractHandler{
flowTokenAddress: flowTokenAddress,
blockstore: blockstore,
addressAllocator: addressAllocator,
backend: backend,
emulator: emulator,
}
}
// AllocateAddress allocates an address to be used by the bridged accounts
func (h *ContractHandler) AllocateAddress() types.Address {
target, err := h.addressAllocator.AllocateAddress()
handleError(err)
return target
}
// AccountByAddress returns the account for the given address,
// if isAuthorized is set, account is controlled by the FVM (bridged accounts)
func (h *ContractHandler) AccountByAddress(addr types.Address, isAuthorized bool) types.Account {
return newAccount(h, addr, isAuthorized)
}
// LastExecutedBlock returns the last executed block
func (h *ContractHandler) LastExecutedBlock() *types.Block {
block, err := h.blockstore.LatestBlock()
handleError(err)
return block
}
// Run runs an rlpencoded evm transaction and
// collects the gas fees and pay it to the coinbase address provided.
func (h *ContractHandler) Run(rlpEncodedTx []byte, coinbase types.Address) {
// step 1 - transaction decoding
encodedLen := uint(len(rlpEncodedTx))
err := h.backend.MeterComputation(environment.ComputationKindRLPDecoding, encodedLen)
handleError(err)
tx := gethTypes.Transaction{}
err = tx.DecodeRLP(
rlp.NewStream(
bytes.NewReader(rlpEncodedTx),
uint64(encodedLen)))
handleError(err)
// step 2 - run transaction
h.checkGasLimit(types.GasLimit(tx.Gas()))
ctx := h.getBlockContext()
ctx.GasFeeCollector = coinbase
blk, err := h.emulator.NewBlockView(ctx)
handleError(err)
res, err := blk.RunTransaction(&tx)
h.meterGasUsage(res)
handleError(err)
// step 3 - update block proposal
bp, err := h.blockstore.BlockProposal()
handleError(err)
txHash := tx.Hash()
bp.AppendTxHash(txHash)
// step 4 - emit events
h.emitEvent(types.NewTransactionExecutedEvent(
bp.Height,
rlpEncodedTx,
txHash,
res,
))
h.emitEvent(types.NewBlockExecutedEvent(bp))
// step 5 - commit block proposal
err = h.blockstore.CommitBlockProposal()
handleError(err)
}
func (h *ContractHandler) checkGasLimit(limit types.GasLimit) {
// check gas limit against what has been left on the transaction side
if !h.backend.ComputationAvailable(environment.ComputationKindEVMGasUsage, uint(limit)) {
handleError(types.ErrInsufficientComputation)
}
}
func (h *ContractHandler) meterGasUsage(res *types.Result) {
if res != nil {
err := h.backend.MeterComputation(environment.ComputationKindEVMGasUsage, uint(res.GasConsumed))
handleError(err)
}
}
func (h *ContractHandler) emitEvent(event *types.Event) {
ev, err := event.Payload.CadenceEvent()
handleError(err)
err = h.backend.EmitEvent(ev)
handleError(err)
}
func (h *ContractHandler) getBlockContext() types.BlockContext {
bp, err := h.blockstore.BlockProposal()
handleError(err)
return types.BlockContext{
BlockNumber: bp.Height,
DirectCallBaseGasUsage: types.DefaultDirectCallBaseGasUsage,
}
}
type Account struct {
isAuthorized bool
address types.Address
fch *ContractHandler
}
// newAccount creates a new evm account
func newAccount(fch *ContractHandler, addr types.Address, isAuthorized bool) *Account {
return &Account{
isAuthorized: isAuthorized,
fch: fch,
address: addr,
}
}
// Address returns the address associated with the bridged account
func (a *Account) Address() types.Address {
return a.address
}
// Balance returns the balance of this bridged account
//
// TODO: we might need to meter computation for read only operations as well
// currently the storage limits is enforced
func (a *Account) Balance() types.Balance {
ctx := a.fch.getBlockContext()
blk, err := a.fch.emulator.NewReadOnlyBlockView(ctx)
handleError(err)
bl, err := blk.BalanceOf(a.address)
handleError(err)
balance, err := types.NewBalanceFromAttoFlow(bl)
handleError(err)
return balance
}
// Deposit deposits the token from the given vault into the flow evm main vault
// and update the account balance with the new amount
func (a *Account) Deposit(v *types.FLOWTokenVault) {
cfg := a.fch.getBlockContext()
a.fch.checkGasLimit(types.GasLimit(cfg.DirectCallBaseGasUsage))
call := types.NewDepositCall(
a.address,
v.Balance().ToAttoFlow(),
)
a.executeAndHandleCall(a.fch.getBlockContext(), call, v.Balance().ToAttoFlow().Uint64(), false)
}
// Withdraw deducts the balance from the account and
// withdraw and return flow token from the Flex main vault.
func (a *Account) Withdraw(b types.Balance) *types.FLOWTokenVault {
a.checkAuthorized()
cfg := a.fch.getBlockContext()
a.fch.checkGasLimit(types.GasLimit(cfg.DirectCallBaseGasUsage))
// check balance of flex vault
bp, err := a.fch.blockstore.BlockProposal()
handleError(err)
if b.ToAttoFlow().Uint64() > bp.TotalSupply {
handleError(types.ErrInsufficientTotalSupply)
}
call := types.NewWithdrawCall(
a.address,
b.ToAttoFlow(),
)
a.executeAndHandleCall(a.fch.getBlockContext(), call, b.ToAttoFlow().Uint64(), true)
return types.NewFlowTokenVault(b)
}
// Transfer transfers tokens between accounts
func (a *Account) Transfer(to types.Address, balance types.Balance) {
a.checkAuthorized()
ctx := a.fch.getBlockContext()
a.fch.checkGasLimit(types.GasLimit(ctx.DirectCallBaseGasUsage))
call := types.NewTransferCall(
a.address,
to,
balance.ToAttoFlow(),
)
a.executeAndHandleCall(ctx, call, 0, false)
}
// Deploy deploys a contract to the EVM environment
// the new deployed contract would be at the returned address and
// the contract data is not controlled by the caller accounts
func (a *Account) Deploy(code types.Code, gaslimit types.GasLimit, balance types.Balance) types.Address {
a.checkAuthorized()
a.fch.checkGasLimit(gaslimit)
call := types.NewDeployCall(
a.address,
code,
uint64(gaslimit),
balance.ToAttoFlow(),
)
res := a.executeAndHandleCall(a.fch.getBlockContext(), call, 0, false)
return types.Address(res.DeployedContractAddress)
}
// Call calls a smart contract function with the given data
// it would limit the gas used according to the limit provided
// given it doesn't goes beyond what Flow transaction allows.
// the balance would be deducted from the OFA account and would be transferred to the target address
func (a *Account) Call(to types.Address, data types.Data, gaslimit types.GasLimit, balance types.Balance) types.Data {
a.checkAuthorized()
a.fch.checkGasLimit(gaslimit)
call := types.NewContractCall(
a.address,
to,
data,
uint64(gaslimit),
balance.ToAttoFlow(),
)
res := a.executeAndHandleCall(a.fch.getBlockContext(), call, 0, false)
return res.ReturnedValue
}
func (a *Account) executeAndHandleCall(
ctx types.BlockContext,
call *types.DirectCall,
totalSupplyDiff uint64,
deductSupplyDiff bool,
) *types.Result {
// execute the call
blk, err := a.fch.emulator.NewBlockView(ctx)
handleError(err)
res, err := blk.DirectCall(call)
a.fch.meterGasUsage(res)
handleError(err)
// update block proposal
callHash, err := call.Hash()
if err != nil {
err = types.NewFatalError(err)
handleError(err)
}
bp, err := a.fch.blockstore.BlockProposal()
handleError(err)
bp.AppendTxHash(callHash)
if deductSupplyDiff {
bp.TotalSupply -= totalSupplyDiff
} else {
// TODO: add overflow errors (even though we might never get there)
bp.TotalSupply += totalSupplyDiff
}
// emit events
encoded, err := call.Encode()
handleError(err)
a.fch.emitEvent(
types.NewTransactionExecutedEvent(
bp.Height,
encoded,
callHash,
res,
),
)
a.fch.emitEvent(types.NewBlockExecutedEvent(bp))
// commit block proposal
err = a.fch.blockstore.CommitBlockProposal()
handleError(err)
return res
}
func (a *Account) checkAuthorized() {
// check if account is authorized (i.e. is a bridged account)
if !a.isAuthorized {
handleError(types.ErrUnAuthroizedMethodCall)
}
}
func handleError(err error) {
if err == nil {
return
}
if types.IsAFatalError(err) {
// don't wrap it
panic(err)
}
panic(errors.NewEVMError(err))
}