-
Notifications
You must be signed in to change notification settings - Fork 175
/
uuids.go
214 lines (183 loc) · 6.14 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
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
package environment
import (
"crypto/sha256"
"encoding/binary"
"fmt"
"github.com/rs/zerolog"
"github.com/onflow/flow-go/fvm/storage/state"
"github.com/onflow/flow-go/fvm/tracing"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module/trace"
"github.com/onflow/flow-go/utils/slices"
)
// uuid is partitioned with 3rd byte for compatibility reasons.
// (database types and Javascript safe integer limits)
//
// counter(C) is 7 bytes, paritition(P) is 1 byte
// uuid is assembled by first reading the counter from the register value of the partitioned register,
// and then left shifting the 6th and 7th byte, and placing the partition byte at 6th byte:
// C7 C6 P C5 C4 C3 C2 C1
//
// Until resource ids start filling the bits above the 48th one, dapps will have enough time
// to switch to a larger data type.
const (
// The max value for any is uuid partition is MaxUint56, since one byte
// in the uuid is used for partitioning.
MaxUint56 = (uint64(1) << 56) - 1
// Start warning when there's only a single high bit left. This should give
// us plenty of time to migrate to larger counters.
Uint56OverflowWarningThreshold = (uint64(1) << 55) - 1
)
type UUIDGenerator interface {
GenerateUUID() (uint64, error)
}
type ParseRestrictedUUIDGenerator struct {
txnState state.NestedTransactionPreparer
impl UUIDGenerator
}
func NewParseRestrictedUUIDGenerator(
txnState state.NestedTransactionPreparer,
impl UUIDGenerator,
) UUIDGenerator {
return ParseRestrictedUUIDGenerator{
txnState: txnState,
impl: impl,
}
}
func (generator ParseRestrictedUUIDGenerator) GenerateUUID() (uint64, error) {
return parseRestrict1Ret(
generator.txnState,
trace.FVMEnvGenerateUUID,
generator.impl.GenerateUUID)
}
type uUIDGenerator struct {
tracer tracing.TracerSpan
log zerolog.Logger
meter Meter
txnState state.NestedTransactionPreparer
blockHeader *flow.Header
txnIndex uint32
initialized bool
partition byte
registerId flow.RegisterID
}
func uuidPartition(blockId flow.Identifier, txnIndex uint32) byte {
// Partitioning by txnIndex ensures temporally neighboring transactions do
// not share registers / conflict with each other.
//
// Since all blocks will have a transaction at txnIndex 0 but not
// necessarily a transaction at txnIndex 255, if we assign partition based
// only on txnIndex, partition 0's counter (and other low-valued
// partitions' counters) will fill up much more quickly than high-valued
// partitions' counters. Therefore, a deterministically random offset is
// used to ensure the partitioned counters are roughly balanced. Any byte
// in the sha hash is sufficiently random/uniform for this purpose (Note that
// block Id is already a sha hash, but its hash implementation may change
// underneath us).
//
// Note that since partition 0 reuses the legacy counter, its counter is
// much further ahead than the other partitions. If partition 0's counter
// is in danager of overflowing, use variants of "the power of two random
// choices" to shed load to other counters.
//
// The explicit mod is not really needed, but is there for completeness.
partitionOffset := sha256.Sum256(blockId[:])[0]
return byte((uint32(partitionOffset) + txnIndex) % 256)
}
func NewUUIDGenerator(
tracer tracing.TracerSpan,
log zerolog.Logger,
meter Meter,
txnState state.NestedTransactionPreparer,
blockHeader *flow.Header,
txnIndex uint32,
) *uUIDGenerator {
return &uUIDGenerator{
tracer: tracer,
log: log,
meter: meter,
txnState: txnState,
blockHeader: blockHeader,
txnIndex: txnIndex,
initialized: false,
}
}
// getCounter reads the uint64 value from the partitioned uuid register.
func (generator *uUIDGenerator) getCounter() (uint64, error) {
stateBytes, err := generator.txnState.Get(generator.registerId)
if err != nil {
return 0, fmt.Errorf(
"cannot get uuid partition %d byte from state: %w",
generator.partition,
err)
}
bytes := slices.EnsureByteSliceSize(stateBytes, 8)
return binary.BigEndian.Uint64(bytes), nil
}
// setCounter sets a new uint56 value into the partitioned uuid register.
func (generator *uUIDGenerator) setCounter(
value uint64,
) error {
if value > Uint56OverflowWarningThreshold {
if value > MaxUint56 {
return fmt.Errorf(
"uuid partition %d overflowed",
generator.partition)
}
generator.log.Warn().
Int("partition", int(generator.partition)).
Uint64("value", value).
Msg("uuid partition is running out of bits")
}
bytes := make([]byte, 8)
binary.BigEndian.PutUint64(bytes, value)
err := generator.txnState.Set(generator.registerId, bytes)
if err != nil {
return fmt.Errorf(
"cannot set uuid %d byte to state: %w",
generator.partition,
err)
}
return nil
}
func (generator *uUIDGenerator) maybeInitializePartition() {
if generator.initialized {
return
}
generator.initialized = true
// NOTE: block header is not set for scripts. We'll just use partition 0 in
// this case.
if generator.blockHeader == nil {
generator.partition = 0
} else {
generator.partition = uuidPartition(
generator.blockHeader.ID(),
generator.txnIndex)
}
generator.registerId = flow.UUIDRegisterID(generator.partition)
}
// GenerateUUID generates a new uuid and persist the data changes into state
func (generator *uUIDGenerator) GenerateUUID() (uint64, error) {
defer generator.tracer.StartExtensiveTracingChildSpan(
trace.FVMEnvGenerateUUID).End()
err := generator.meter.MeterComputation(
ComputationKindGenerateUUID,
1)
if err != nil {
return 0, fmt.Errorf("generate uuid failed: %w", err)
}
generator.maybeInitializePartition()
counter, err := generator.getCounter()
if err != nil {
return 0, fmt.Errorf("cannot generate UUID: %w", err)
}
err = generator.setCounter(counter + 1)
if err != nil {
return 0, fmt.Errorf("cannot generate UUID: %w", err)
}
// Since the partition counter only goes up to MaxUint56, we can use the
// assemble a UUID value with the partition (P) and the counter (C).
// Note: partition (P) is represented by the 6th byte
// (C7 C6) | P | (C5 C4 C3 C2 C1)
return ((counter & 0xFF_FF00_0000_0000) << 8) | (uint64(generator.partition) << 40) | (counter & 0xFF_FFFF_FFFF), nil
}