-
Notifications
You must be signed in to change notification settings - Fork 177
/
transaction_state.go
479 lines (397 loc) · 13.1 KB
/
transaction_state.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
package state
import (
"fmt"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/flow-go/fvm/meter"
"github.com/onflow/flow-go/fvm/storage/snapshot"
"github.com/onflow/flow-go/model/flow"
)
// Opaque identifier used for Restarting nested transactions
type NestedTransactionId struct {
state *ExecutionState
}
func (id NestedTransactionId) StateForTestingOnly() *ExecutionState {
return id.state
}
type Meter interface {
MeterComputation(kind common.ComputationKind, intensity uint) error
ComputationIntensities() meter.MeteredComputationIntensities
TotalComputationLimit() uint
TotalComputationUsed() uint64
MeterMemory(kind common.MemoryKind, intensity uint) error
MemoryIntensities() meter.MeteredMemoryIntensities
TotalMemoryEstimate() uint64
InteractionUsed() uint64
MeterEmittedEvent(byteSize uint64) error
TotalEmittedEventBytes() uint64
// RunWithAllLimitsDisabled runs f with limits disabled
RunWithAllLimitsDisabled(f func())
}
// NestedTransactionPreparer provides active transaction states and facilitates
// common state management operations.
type NestedTransactionPreparer interface {
Meter
// NumNestedTransactions returns the number of uncommitted nested
// transactions. Note that the main transaction is not considered a
// nested transaction.
NumNestedTransactions() int
// IsParseRestricted returns true if the current nested transaction is in
// parse resticted access mode.
IsParseRestricted() bool
MainTransactionId() NestedTransactionId
// IsCurrent returns true if the provide id refers to the current (nested)
// transaction.
IsCurrent(id NestedTransactionId) bool
// InterimReadSet returns the current read set aggregated from all
// outstanding nested transactions.
InterimReadSet() map[flow.RegisterID]struct{}
// FinalizeMainTransaction finalizes the main transaction and returns
// its execution snapshot. The finalized main transaction will not accept
// any new commits after this point. This returns an error if there are
// outstanding nested transactions.
FinalizeMainTransaction() (*snapshot.ExecutionSnapshot, error)
// BeginNestedTransaction creates a unrestricted nested transaction within
// the current unrestricted (nested) transaction. The meter parameters are
// inherited from the current transaction. This returns error if the
// current nested transaction is program restricted.
BeginNestedTransaction() (
NestedTransactionId,
error,
)
// BeginNestedTransactionWithMeterParams creates a unrestricted nested
// transaction within the current unrestricted (nested) transaction, using
// the provided meter parameters. This returns error if the current nested
// transaction is program restricted.
BeginNestedTransactionWithMeterParams(
params meter.MeterParameters,
) (
NestedTransactionId,
error,
)
// BeginParseRestrictedNestedTransaction creates a restricted nested
// transaction within the current (nested) transaction. The meter
// parameters are inherited from the current transaction.
BeginParseRestrictedNestedTransaction(
location common.AddressLocation,
) (
NestedTransactionId,
error,
)
// CommitNestedTransaction commits the changes in the current unrestricted
// nested transaction to the parent (nested) transaction. This returns
// error if the expectedId does not match the current nested transaction.
// This returns the committed execution snapshot otherwise.
//
// Note: The returned committed execution snapshot may be reused by another
// transaction via AttachAndCommitNestedTransaction to update the
// transaction bookkeeping, but the caller must manually invalidate the
// state.
// USE WITH EXTREME CAUTION.
CommitNestedTransaction(
expectedId NestedTransactionId,
) (
*snapshot.ExecutionSnapshot,
error,
)
// CommitParseRestrictedNestedTransaction commits the changes in the
// current restricted nested transaction to the parent (nested)
// transaction. This returns error if the specified location does not
// match the tracked location. This returns the committed execution
// snapshot otherwise.
//
// Note: The returned committed execution snapshot may be reused by another
// transaction via AttachAndCommitNestedTransaction to update the
// transaction bookkeeping, but the caller must manually invalidate the
// state.
// USE WITH EXTREME CAUTION.
CommitParseRestrictedNestedTransaction(
location common.AddressLocation,
) (
*snapshot.ExecutionSnapshot,
error,
)
// AttachAndCommitNestedTransaction commits the changes from the cached
// nested transaction execution snapshot to the current (nested)
// transaction.
AttachAndCommitNestedTransaction(
cachedSnapshot *snapshot.ExecutionSnapshot,
) error
// RestartNestedTransaction merges all changes that belongs to the nested
// transaction about to be restart (for spock/meter bookkeeping), then
// wipes its view changes.
RestartNestedTransaction(
id NestedTransactionId,
) error
Get(id flow.RegisterID) (flow.RegisterValue, error)
Set(id flow.RegisterID, value flow.RegisterValue) error
}
type nestedTransactionStackFrame struct {
*ExecutionState
// When nil, the subtransaction will have unrestricted access to the runtime
// environment. When non-nil, the subtransaction will only have access to
// the parts of the runtime environment necessary for importing/parsing the
// program, specifically, environment.ContractReader and
// environment.Programs.
parseRestriction *common.AddressLocation
}
type transactionState struct {
// NOTE: The first frame is always the main transaction, and is not
// poppable during the course of the transaction.
nestedTransactions []nestedTransactionStackFrame
}
// NewTransactionState constructs a new state transaction which manages nested
// transactions.
func NewTransactionState(
snapshot snapshot.StorageSnapshot,
params StateParameters,
) NestedTransactionPreparer {
startState := NewExecutionState(snapshot, params)
return &transactionState{
nestedTransactions: []nestedTransactionStackFrame{
nestedTransactionStackFrame{
ExecutionState: startState,
parseRestriction: nil,
},
},
}
}
func (txnState *transactionState) current() nestedTransactionStackFrame {
return txnState.nestedTransactions[txnState.NumNestedTransactions()]
}
func (txnState *transactionState) NumNestedTransactions() int {
return len(txnState.nestedTransactions) - 1
}
func (txnState *transactionState) IsParseRestricted() bool {
return txnState.current().parseRestriction != nil
}
func (txnState *transactionState) MainTransactionId() NestedTransactionId {
return NestedTransactionId{
state: txnState.nestedTransactions[0].ExecutionState,
}
}
func (txnState *transactionState) IsCurrent(id NestedTransactionId) bool {
return txnState.current().ExecutionState == id.state
}
func (txnState *transactionState) InterimReadSet() map[flow.RegisterID]struct{} {
sizeEstimate := 0
for _, frame := range txnState.nestedTransactions {
sizeEstimate += frame.readSetSize()
}
result := make(map[flow.RegisterID]struct{}, sizeEstimate)
// Note: the interim read set must be accumulated in reverse order since
// the parent frame's write set will override the child frame's read set.
for i := len(txnState.nestedTransactions) - 1; i >= 0; i-- {
txnState.nestedTransactions[i].interimReadSet(result)
}
return result
}
func (txnState *transactionState) FinalizeMainTransaction() (
*snapshot.ExecutionSnapshot,
error,
) {
if len(txnState.nestedTransactions) > 1 {
return nil, fmt.Errorf(
"cannot finalize with outstanding nested transaction(s)")
}
return txnState.nestedTransactions[0].Finalize(), nil
}
func (txnState *transactionState) BeginNestedTransaction() (
NestedTransactionId,
error,
) {
if txnState.IsParseRestricted() {
return NestedTransactionId{}, fmt.Errorf(
"cannot begin a unrestricted nested transaction inside a " +
"program restricted nested transaction",
)
}
child := txnState.current().NewChild()
txnState.push(child, nil)
return NestedTransactionId{
state: child,
}, nil
}
func (txnState *transactionState) BeginNestedTransactionWithMeterParams(
params meter.MeterParameters,
) (
NestedTransactionId,
error,
) {
if txnState.IsParseRestricted() {
return NestedTransactionId{}, fmt.Errorf(
"cannot begin a unrestricted nested transaction inside a " +
"program restricted nested transaction",
)
}
child := txnState.current().NewChildWithMeterParams(params)
txnState.push(child, nil)
return NestedTransactionId{
state: child,
}, nil
}
func (txnState *transactionState) BeginParseRestrictedNestedTransaction(
location common.AddressLocation,
) (
NestedTransactionId,
error,
) {
child := txnState.current().NewChild()
txnState.push(child, &location)
return NestedTransactionId{
state: child,
}, nil
}
func (txnState *transactionState) push(
child *ExecutionState,
location *common.AddressLocation,
) {
txnState.nestedTransactions = append(
txnState.nestedTransactions,
nestedTransactionStackFrame{
ExecutionState: child,
parseRestriction: location,
},
)
}
func (txnState *transactionState) pop(op string) (*ExecutionState, error) {
if len(txnState.nestedTransactions) < 2 {
return nil, fmt.Errorf("cannot %s the main transaction", op)
}
child := txnState.current()
txnState.nestedTransactions = txnState.nestedTransactions[:len(txnState.nestedTransactions)-1]
return child.ExecutionState, nil
}
func (txnState *transactionState) mergeIntoParent() (
*snapshot.ExecutionSnapshot,
error,
) {
childState, err := txnState.pop("commit")
if err != nil {
return nil, err
}
childSnapshot := childState.Finalize()
err = txnState.current().Merge(childSnapshot)
if err != nil {
return nil, err
}
return childSnapshot, nil
}
func (txnState *transactionState) CommitNestedTransaction(
expectedId NestedTransactionId,
) (
*snapshot.ExecutionSnapshot,
error,
) {
if !txnState.IsCurrent(expectedId) {
return nil, fmt.Errorf(
"cannot commit unexpected nested transaction: id mismatch",
)
}
if txnState.IsParseRestricted() {
// This is due to a programming error.
return nil, fmt.Errorf(
"cannot commit unexpected nested transaction: parse restricted",
)
}
return txnState.mergeIntoParent()
}
func (txnState *transactionState) CommitParseRestrictedNestedTransaction(
location common.AddressLocation,
) (
*snapshot.ExecutionSnapshot,
error,
) {
currentFrame := txnState.current()
if currentFrame.parseRestriction == nil ||
*currentFrame.parseRestriction != location {
// This is due to a programming error.
return nil, fmt.Errorf(
"cannot commit unexpected nested transaction %v != %v",
currentFrame.parseRestriction,
location,
)
}
return txnState.mergeIntoParent()
}
func (txnState *transactionState) AttachAndCommitNestedTransaction(
cachedSnapshot *snapshot.ExecutionSnapshot,
) error {
return txnState.current().Merge(cachedSnapshot)
}
func (txnState *transactionState) RestartNestedTransaction(
id NestedTransactionId,
) error {
// NOTE: We need to verify the id is valid before any merge operation or
// else we would accidently merge everything into the main transaction.
found := false
for _, frame := range txnState.nestedTransactions {
if frame.ExecutionState == id.state {
found = true
break
}
}
if !found {
return fmt.Errorf(
"cannot restart nested transaction: nested transaction not found")
}
for txnState.current().ExecutionState != id.state {
_, err := txnState.mergeIntoParent()
if err != nil {
return fmt.Errorf("cannot restart nested transaction: %w", err)
}
}
return txnState.current().DropChanges()
}
func (txnState *transactionState) Get(
id flow.RegisterID,
) (
flow.RegisterValue,
error,
) {
return txnState.current().Get(id)
}
func (txnState *transactionState) Set(
id flow.RegisterID,
value flow.RegisterValue,
) error {
return txnState.current().Set(id, value)
}
func (txnState *transactionState) MeterComputation(
kind common.ComputationKind,
intensity uint,
) error {
return txnState.current().MeterComputation(kind, intensity)
}
func (txnState *transactionState) MeterMemory(
kind common.MemoryKind,
intensity uint,
) error {
return txnState.current().MeterMemory(kind, intensity)
}
func (txnState *transactionState) ComputationIntensities() meter.MeteredComputationIntensities {
return txnState.current().ComputationIntensities()
}
func (txnState *transactionState) TotalComputationLimit() uint {
return txnState.current().TotalComputationLimit()
}
func (txnState *transactionState) TotalComputationUsed() uint64 {
return txnState.current().TotalComputationUsed()
}
func (txnState *transactionState) MemoryIntensities() meter.MeteredMemoryIntensities {
return txnState.current().MemoryIntensities()
}
func (txnState *transactionState) TotalMemoryEstimate() uint64 {
return txnState.current().TotalMemoryEstimate()
}
func (txnState *transactionState) InteractionUsed() uint64 {
return txnState.current().InteractionUsed()
}
func (txnState *transactionState) MeterEmittedEvent(byteSize uint64) error {
return txnState.current().MeterEmittedEvent(byteSize)
}
func (txnState *transactionState) TotalEmittedEventBytes() uint64 {
return txnState.current().TotalEmittedEventBytes()
}
func (txnState *transactionState) RunWithAllLimitsDisabled(f func()) {
txnState.current().RunWithAllLimitsDisabled(f)
}