-
Notifications
You must be signed in to change notification settings - Fork 175
/
env.go
527 lines (424 loc) · 13.5 KB
/
env.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package fvm
import (
"encoding/binary"
"errors"
"fmt"
"math/rand"
"github.com/onflow/cadence"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/onflow/cadence/runtime"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/flow-go/fvm/state"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/storage"
)
var _ runtime.Interface = &hostEnv{}
var _ runtime.HighLevelStorage = &hostEnv{}
type hostEnv struct {
ctx Context
ledger state.Ledger
accounts *state.Accounts
uuidGenerator *UUIDGenerator
runtime.Metrics
events []cadence.Event
logs []string
transactionEnv *transactionEnv
rng *rand.Rand
}
func newEnvironment(ctx Context, ledger state.Ledger) *hostEnv {
accounts := state.NewAccounts(ledger, ctx.Chain)
uuids := state.NewUUIDs(ledger)
uuidGenerator := NewUUIDGenerator(uuids)
env := &hostEnv{
ctx: ctx,
ledger: ledger,
Metrics: &noopMetricsCollector{},
accounts: accounts,
uuidGenerator: uuidGenerator,
}
if ctx.BlockHeader != nil {
env.seedRNG(ctx.BlockHeader)
}
if ctx.Metrics != nil {
env.Metrics = &metricsCollector{ctx.Metrics}
}
return env
}
func (e *hostEnv) seedRNG(header *flow.Header) {
// Seed the random number generator with entropy created from the block header ID. The random number generator will
// be used by the UnsafeRandom function.
id := header.ID()
source := rand.NewSource(int64(binary.BigEndian.Uint64(id[:])))
e.rng = rand.New(source)
}
func (e *hostEnv) setTransaction(vm *VirtualMachine, tx *flow.TransactionBody) {
e.transactionEnv = newTransactionEnv(
vm,
e.ctx,
e.ledger,
e.accounts,
tx,
)
}
func (e *hostEnv) getEvents() []cadence.Event {
return e.events
}
func (e *hostEnv) getLogs() []string {
return e.logs
}
func (e *hostEnv) GetValue(owner, key []byte) ([]byte, error) {
v, _ := e.ledger.Get(
string(owner),
"", // TODO: Remove empty controller key
string(key),
)
return v, nil
}
func (e *hostEnv) SetValue(owner, key, value []byte) error {
e.ledger.Set(
string(owner),
"", // TODO: Remove empty controller key
string(key),
value,
)
return nil
}
func (e *hostEnv) ValueExists(owner, key []byte) (exists bool, err error) {
v, err := e.GetValue(owner, key)
if err != nil {
return false, err
}
return len(v) > 0, nil
}
func (e *hostEnv) ResolveImport(location runtime.Location) ([]byte, error) {
addressLocation, ok := location.(runtime.AddressLocation)
if !ok {
return nil, nil
}
address := flow.BytesToAddress(addressLocation)
code, err := e.accounts.GetCode(address)
if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return nil, err
}
if code == nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return nil, fmt.Errorf("no code deployed at address %s", address)
}
return code, nil
}
func (e *hostEnv) GetCachedProgram(location ast.Location) (*ast.Program, error) {
if e.ctx.ASTCache == nil {
return nil, nil
}
program, err := e.ctx.ASTCache.GetProgram(location)
if program != nil {
// Program was found within cache, do an explicit ledger register touch
// to ensure consistent reads during chunk verification.
if addressLocation, ok := location.(runtime.AddressLocation); ok {
address := flow.BytesToAddress(addressLocation)
e.accounts.TouchCode(address)
}
}
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return program, err
}
func (e *hostEnv) CacheProgram(location ast.Location, program *ast.Program) error {
if e.ctx.ASTCache == nil {
return nil
}
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return e.ctx.ASTCache.SetProgram(location, program)
}
func (e *hostEnv) Log(message string) {
e.logs = append(e.logs, message)
}
func (e *hostEnv) EmitEvent(event cadence.Event) {
e.events = append(e.events, event)
}
func (e *hostEnv) GenerateUUID() uint64 {
uuid, err := e.uuidGenerator.GenerateUUID()
if err != nil {
// TODO - Return error once Cadence interface accommodates it
panic(fmt.Errorf("cannot get UUID: %w", err))
}
return uuid
}
func (e *hostEnv) GetComputationLimit() uint64 {
if e.transactionEnv != nil {
return e.transactionEnv.GetComputationLimit()
}
return e.ctx.GasLimit
}
func (e *hostEnv) DecodeArgument(b []byte, t cadence.Type) (cadence.Value, error) {
return jsoncdc.Decode(b)
}
func (e *hostEnv) Events() []cadence.Event {
return e.events
}
func (e *hostEnv) Logs() []string {
return e.logs
}
func (e *hostEnv) VerifySignature(
signature []byte,
tag string,
message []byte,
rawPublicKey []byte,
rawSigAlgo string,
rawHashAlgo string,
) bool {
valid, err := verifySignatureFromRuntime(
e.ctx.SignatureVerifier,
signature,
tag,
message,
rawPublicKey,
rawSigAlgo,
rawHashAlgo,
)
if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
panic(err)
}
return valid
}
func (e *hostEnv) HighLevelStorageEnabled() bool {
return e.ctx.SetValueHandler != nil
}
func (e *hostEnv) SetCadenceValue(owner common.Address, key string, value cadence.Value) error {
return e.ctx.SetValueHandler(flow.Address(owner), key, value)
}
// Block Environment Functions
// GetCurrentBlockHeight returns the current block height.
func (e *hostEnv) GetCurrentBlockHeight() uint64 {
if e.ctx.BlockHeader == nil {
panic("GetCurrentBlockHeight is not supported by this environment")
}
return e.ctx.BlockHeader.Height
}
// UnsafeRandom returns a random uint64, where the process of random number derivation is not cryptographically
// secure.
func (e *hostEnv) UnsafeRandom() uint64 {
if e.rng == nil {
panic("UnsafeRandom is not supported by this environment")
}
buf := make([]byte, 8)
_, _ = e.rng.Read(buf) // Always succeeds, no need to check error
return binary.LittleEndian.Uint64(buf)
}
func runtimeBlockFromHeader(header *flow.Header) runtime.Block {
return runtime.Block{
Height: header.Height,
View: header.View,
Hash: runtime.BlockHash(header.ID()),
Timestamp: header.Timestamp.UnixNano(),
}
}
// GetBlockAtHeight returns the block at the given height.
func (e *hostEnv) GetBlockAtHeight(height uint64) (runtime.Block, bool, error) {
if e.ctx.Blocks == nil {
panic("GetBlockAtHeight is not supported by this environment")
}
if e.ctx.BlockHeader != nil && height == e.ctx.BlockHeader.Height {
return runtimeBlockFromHeader(e.ctx.BlockHeader), true, nil
}
block, err := e.ctx.Blocks.ByHeight(height)
// TODO: remove dependency on storage
if errors.Is(err, storage.ErrNotFound) {
return runtime.Block{}, false, nil
} else if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return runtime.Block{}, false, fmt.Errorf("unexpected failure of GetBlockAtHeight, height %v: %w", height, err)
}
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return runtimeBlockFromHeader(block.Header), true, nil
}
// Transaction Environment Functions
func (e *hostEnv) CreateAccount(payer runtime.Address) (address runtime.Address, err error) {
if e.transactionEnv == nil {
panic("CreateAccount is not supported by this environment")
}
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return e.transactionEnv.CreateAccount(payer)
}
func (e *hostEnv) AddAccountKey(address runtime.Address, publicKey []byte) error {
if e.transactionEnv == nil {
panic("AddAccountKey is not supported by this environment")
}
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return e.transactionEnv.AddAccountKey(address, publicKey)
}
func (e *hostEnv) RemoveAccountKey(address runtime.Address, index int) (publicKey []byte, err error) {
if e.transactionEnv == nil {
panic("RemoveAccountKey is not supported by this environment")
}
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return e.transactionEnv.RemoveAccountKey(address, index)
}
func (e *hostEnv) UpdateAccountCode(address runtime.Address, code []byte) (err error) {
if e.transactionEnv == nil {
panic("UpdateAccountCode is not supported by this environment")
}
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return e.transactionEnv.UpdateAccountCode(address, code)
}
func (e *hostEnv) GetSigningAccounts() []runtime.Address {
if e.transactionEnv == nil {
panic("GetSigningAccounts is not supported by this environment")
}
return e.transactionEnv.GetSigningAccounts()
}
// Transaction Environment
type transactionEnv struct {
vm *VirtualMachine
ctx Context
ledger state.Ledger
accounts *state.Accounts
tx *flow.TransactionBody
authorizers []runtime.Address
}
func newTransactionEnv(
vm *VirtualMachine,
ctx Context,
ledger state.Ledger,
accounts *state.Accounts,
tx *flow.TransactionBody,
) *transactionEnv {
return &transactionEnv{
vm: vm,
ctx: ctx,
ledger: ledger,
accounts: accounts,
tx: tx,
}
}
func (e *transactionEnv) GetSigningAccounts() []runtime.Address {
if e.authorizers == nil {
e.authorizers = make([]runtime.Address, len(e.tx.Authorizers))
for i, auth := range e.tx.Authorizers {
e.authorizers[i] = runtime.Address(auth)
}
}
return e.authorizers
}
func (e *transactionEnv) GetComputationLimit() uint64 {
return e.tx.GasLimit
}
func (e *transactionEnv) CreateAccount(payer runtime.Address) (address runtime.Address, err error) {
if e.ctx.ServiceAccountEnabled {
err = e.vm.invokeMetaTransaction(
e.ctx,
deductAccountCreationFeeTransaction(
flow.Address(payer),
e.ctx.Chain.ServiceAddress(),
e.ctx.RestrictedAccountCreationEnabled,
),
e.ledger,
)
if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return address, err
}
}
var flowAddress flow.Address
flowAddress, err = e.accounts.Create(nil)
if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return address, err
}
if e.ctx.ServiceAccountEnabled {
err = e.vm.invokeMetaTransaction(
e.ctx,
initFlowTokenTransaction(flowAddress, e.ctx.Chain.ServiceAddress()),
e.ledger,
)
if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return address, err
}
}
return runtime.Address(flowAddress), nil
}
// AddAccountKey adds a public key to an existing account.
//
// This function returns an error if the specified account does not exist or
// if the key insertion fails.
func (e *transactionEnv) AddAccountKey(address runtime.Address, encodedPublicKey []byte) (err error) {
accountAddress := flow.Address(address)
var ok bool
ok, err = e.accounts.Exists(accountAddress)
if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return err
}
if !ok {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return fmt.Errorf("account with address %s does not exist", address)
}
var publicKey flow.AccountPublicKey
publicKey, err = flow.DecodeRuntimeAccountPublicKey(encodedPublicKey, 0)
if err != nil {
return fmt.Errorf("cannot decode runtime public account key: %w", err)
}
err = e.accounts.AppendPublicKey(accountAddress, publicKey)
if err != nil {
return fmt.Errorf("failed to add public key to account: %w", err)
}
return nil
}
// RemoveAccountKey revokes a public key by index from an existing account.
//
// This function returns an error if the specified account does not exist, the
// provided key is invalid, or if key revoking fails.
func (e *transactionEnv) RemoveAccountKey(address runtime.Address, keyIndex int) (encodedPublicKey []byte, err error) {
accountAddress := flow.Address(address)
var ok bool
ok, err = e.accounts.Exists(accountAddress)
if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return nil, err
}
if !ok {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return nil, fmt.Errorf("account with address %s does not exist", address)
}
if keyIndex < 0 {
return nil, fmt.Errorf("key index must be positve, received %d", keyIndex)
}
var publicKey flow.AccountPublicKey
publicKey, err = e.accounts.GetPublicKey(accountAddress, uint64(keyIndex))
if err != nil {
return nil, err
}
// mark this key as revoked
publicKey.Revoked = true
encodedPublicKey, err = e.accounts.SetPublicKey(accountAddress, uint64(keyIndex), publicKey)
if err != nil {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202 {
return nil, fmt.Errorf("failed to revoke account key: %w", err)
}
return encodedPublicKey, nil
}
// UpdateAccountCode updates the deployed code on an existing account.
//
// This function returns an error if the specified account does not exist or is
// not a valid signing account.
func (e *transactionEnv) UpdateAccountCode(address runtime.Address, code []byte) (err error) {
accountAddress := flow.Address(address)
// currently, every transaction that sets account code (deploys/updates contracts)
// must be signed by the service account
if e.ctx.RestrictedDeploymentEnabled && !e.isAuthorizer(runtime.Address(e.ctx.Chain.ServiceAddress())) {
// TODO: improve error passing https://github.com/onflow/cadence/issues/202
return fmt.Errorf("code deployment requires authorization from the service account")
}
return e.accounts.SetCode(accountAddress, code)
}
func (e *transactionEnv) isAuthorizer(address runtime.Address) bool {
for _, accountAddress := range e.GetSigningAccounts() {
if accountAddress == address {
return true
}
}
return false
}