-
Notifications
You must be signed in to change notification settings - Fork 178
/
uuids.go
110 lines (93 loc) · 2.39 KB
/
uuids.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
package environment
import (
"encoding/binary"
"fmt"
"github.com/onflow/flow-go/fvm/state"
"github.com/onflow/flow-go/module/trace"
"github.com/onflow/flow-go/utils/slices"
)
const keyUUID = "uuid"
type UUIDGenerator interface {
GenerateUUID() (uint64, error)
}
type ParseRestrictedUUIDGenerator struct {
txnState *state.TransactionState
impl UUIDGenerator
}
func NewParseRestrictedUUIDGenerator(
txnState *state.TransactionState,
impl UUIDGenerator,
) UUIDGenerator {
return ParseRestrictedUUIDGenerator{
txnState: txnState,
impl: impl,
}
}
func (generator ParseRestrictedUUIDGenerator) GenerateUUID() (uint64, error) {
return parseRestrict1Ret(
generator.txnState,
"GenerateUUID",
generator.impl.GenerateUUID)
}
type uUIDGenerator struct {
tracer *Tracer
meter Meter
txnState *state.TransactionState
}
func NewUUIDGenerator(
tracer *Tracer,
meter Meter,
txnState *state.TransactionState,
) *uUIDGenerator {
return &uUIDGenerator{
tracer: tracer,
meter: meter,
txnState: txnState,
}
}
// GetUUID reads uint64 byte value for uuid from the state
func (generator *uUIDGenerator) getUUID() (uint64, error) {
stateBytes, err := generator.txnState.Get(
"",
keyUUID,
generator.txnState.EnforceLimits())
if err != nil {
return 0, fmt.Errorf("cannot get uuid byte from state: %w", err)
}
bytes := slices.EnsureByteSliceSize(stateBytes, 8)
return binary.BigEndian.Uint64(bytes), nil
}
// SetUUID sets a new uint64 byte value
func (generator *uUIDGenerator) setUUID(uuid uint64) error {
bytes := make([]byte, 8)
binary.BigEndian.PutUint64(bytes, uuid)
err := generator.txnState.Set(
"",
keyUUID,
bytes,
generator.txnState.EnforceLimits())
if err != nil {
return fmt.Errorf("cannot set uuid byte to state: %w", err)
}
return nil
}
// GenerateUUID generates a new uuid and persist the data changes into state
func (generator *uUIDGenerator) GenerateUUID() (uint64, error) {
defer generator.tracer.StartExtensiveTracingSpanFromRoot(
trace.FVMEnvGenerateUUID).End()
err := generator.meter.MeterComputation(
ComputationKindGenerateUUID,
1)
if err != nil {
return 0, fmt.Errorf("generate uuid failed: %w", err)
}
uuid, err := generator.getUUID()
if err != nil {
return 0, fmt.Errorf("cannot generate UUID: %w", err)
}
err = generator.setUUID(uuid + 1)
if err != nil {
return 0, fmt.Errorf("cannot generate UUID: %w", err)
}
return uuid, nil
}