-
Notifications
You must be signed in to change notification settings - Fork 151
/
treasury_output.go
319 lines (253 loc) · 7.96 KB
/
treasury_output.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
package utxo
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/serializer/v2/marshalutil"
iotago "github.com/iotaledger/iota.go/v3"
)
const (
// A prefix which denotes a spent treasury output.
// Do not modify the value since we're writing this as a bool.
TreasuryOutputSpentPrefix = 1
// A prefix which denotes an unspent treasury output.
// Do not modify the value since we're writing this as a bool.
TreasuryOutputUnspentPrefix = 0
)
var (
// ErrInvalidTreasuryState is returned when the state of the treasury is invalid.
ErrInvalidTreasuryState = errors.New("invalid treasury state")
)
// TreasuryOutput represents the output of a treasury transaction.
type TreasuryOutput struct {
// The ID of the milestone which generated this output.
MilestoneID iotago.MilestoneID
// The amount residing on this output.
Amount uint64
// Whether this output was already spent
Spent bool
}
type jsonTreasuryOutput struct {
MilestoneID string `json:"milestoneId"`
Amount string `json:"amount"`
}
func (t *TreasuryOutput) MarshalJSON() ([]byte, error) {
return json.Marshal(&jsonTreasuryOutput{
MilestoneID: t.MilestoneID.ToHex(),
Amount: iotago.EncodeUint64(t.Amount),
})
}
func (t *TreasuryOutput) UnmarshalJSON(bytes []byte) error {
j := &jsonTreasuryOutput{}
if err := json.Unmarshal(bytes, j); err != nil {
return err
}
if len(j.MilestoneID) == 0 {
return errors.New("missing milestone ID")
}
milestoneID, err := iotago.DecodeHex(j.MilestoneID)
if err != nil {
return err
}
if len(milestoneID) != iotago.MilestoneIDLength {
return fmt.Errorf("invalid milestone ID length: %d", len(milestoneID))
}
copy(t.MilestoneID[:], milestoneID)
t.Amount, err = iotago.DecodeUint64(j.Amount)
if err != nil {
return fmt.Errorf("invalid amount: %w", err)
}
return nil
}
func (t *TreasuryOutput) KVStorableKey() (key []byte) {
return marshalutil.New(34).
WriteByte(UTXOStoreKeyPrefixTreasuryOutput). // 1 byte
WriteBool(t.Spent). // 1 byte
WriteBytes(t.MilestoneID[:]). // 32 bytes
Bytes()
}
func (t *TreasuryOutput) KVStorableValue() (value []byte) {
return marshalutil.New(8).
WriteUint64(t.Amount). // 8 bytes
Bytes()
}
func (t *TreasuryOutput) kvStorableLoad(_ *Manager, key []byte, value []byte) error {
keyExt := marshalutil.New(key)
// skip prefix
if _, err := keyExt.ReadByte(); err != nil {
return err
}
spent, err := keyExt.ReadBool()
if err != nil {
return err
}
milestoneID, err := keyExt.ReadBytes(iotago.MilestoneIDLength)
if err != nil {
return err
}
copy(t.MilestoneID[:], milestoneID)
val := marshalutil.New(value)
t.Amount, err = val.ReadUint64()
if err != nil {
return err
}
t.Spent = spent
return nil
}
// stores the given treasury output.
func storeTreasuryOutput(output *TreasuryOutput, mutations kvstore.BatchedMutations) error {
return mutations.Set(output.KVStorableKey(), output.KVStorableValue())
}
// deletes the given treasury output.
func deleteTreasuryOutput(output *TreasuryOutput, mutations kvstore.BatchedMutations) error {
return mutations.Delete(output.KVStorableKey())
}
// marks the given treasury output as spent.
func markTreasuryOutputAsSpent(output *TreasuryOutput, mutations kvstore.BatchedMutations) error {
outputCopy := *output
outputCopy.Spent = false
if err := mutations.Delete(outputCopy.KVStorableKey()); err != nil {
return err
}
outputCopy.Spent = true
return mutations.Set(outputCopy.KVStorableKey(), outputCopy.KVStorableValue())
}
// marks the given treasury output as unspent.
func markTreasuryOutputAsUnspent(output *TreasuryOutput, mutations kvstore.BatchedMutations) error {
outputCopy := *output
outputCopy.Spent = true
if err := mutations.Delete(outputCopy.KVStorableKey()); err != nil {
return err
}
outputCopy.Spent = false
return mutations.Set(outputCopy.KVStorableKey(), outputCopy.KVStorableValue())
}
func (u *Manager) readSpentTreasuryOutputWithoutLocking(msHash []byte) (*TreasuryOutput, error) {
key := append([]byte{UTXOStoreKeyPrefixTreasuryOutput, TreasuryOutputSpentPrefix}, msHash...)
val, err := u.utxoStorage.Get(key)
if err != nil {
return nil, err
}
to := &TreasuryOutput{}
if err := to.kvStorableLoad(u, key, val); err != nil {
return nil, err
}
return to, nil
}
func (u *Manager) readUnspentTreasuryOutputWithoutLocking(msHash []byte) (*TreasuryOutput, error) {
key := append([]byte{UTXOStoreKeyPrefixTreasuryOutput, TreasuryOutputUnspentPrefix}, msHash...)
val, err := u.utxoStorage.Get(key)
if err != nil {
return nil, err
}
to := &TreasuryOutput{}
if err := to.kvStorableLoad(u, key, val); err != nil {
return nil, err
}
return to, nil
}
// StoreUnspentTreasuryOutput stores the given unspent treasury output and also deletes
// any existing unspent one in the same procedure.
func (u *Manager) StoreUnspentTreasuryOutput(to *TreasuryOutput) error {
if to.Spent {
panic("provided spent output to persist as new unspent treasury output")
}
mutations, err := u.utxoStorage.Batched()
if err != nil {
return err
}
existing, err := u.UnspentTreasuryOutputWithoutLocking()
if err == nil {
if err = mutations.Delete(existing.KVStorableKey()); err != nil {
mutations.Cancel()
return err
}
}
if err := mutations.Set(to.KVStorableKey(), to.KVStorableValue()); err != nil {
mutations.Cancel()
return err
}
return mutations.Commit()
}
// UnspentTreasuryOutputWithoutLocking returns the unspent treasury output.
func (u *Manager) UnspentTreasuryOutputWithoutLocking() (*TreasuryOutput, error) {
var i int
var innerErr error
var unspentTreasuryOutput *TreasuryOutput
if err := u.utxoStorage.Iterate([]byte{UTXOStoreKeyPrefixTreasuryOutput, TreasuryOutputUnspentPrefix}, func(key kvstore.Key, value kvstore.Value) bool {
i++
unspentTreasuryOutput = &TreasuryOutput{}
if err := unspentTreasuryOutput.kvStorableLoad(u, key, value); err != nil {
innerErr = err
return false
}
return true
}); err != nil {
return nil, err
}
if innerErr != nil {
return nil, innerErr
}
switch {
case i > 1:
return nil, fmt.Errorf("%w: more than one unspent treasury output exists", ErrInvalidTreasuryState)
case i == 0:
return nil, fmt.Errorf("%w: no treasury output exists", ErrInvalidTreasuryState)
}
return unspentTreasuryOutput, nil
}
// TreasuryOutputConsumer is a function that consumes an output.
// Returning false from this function indicates to abort the iteration.
type TreasuryOutputConsumer func(output *TreasuryOutput) bool
// ForEachTreasuryOutput iterates over all stored treasury outputs.
func (u *Manager) ForEachTreasuryOutput(consumer TreasuryOutputConsumer, options ...IterateOption) error {
opt := iterateOptions(options)
if opt.readLockLedger {
u.ReadLockLedger()
defer u.ReadUnlockLedger()
}
var innerErr error
var i int
if err := u.utxoStorage.Iterate([]byte{UTXOStoreKeyPrefixTreasuryOutput}, func(key kvstore.Key, value kvstore.Value) bool {
if (opt.maxResultCount > 0) && (i >= opt.maxResultCount) {
return false
}
i++
output := &TreasuryOutput{}
if err := output.kvStorableLoad(u, key, value); err != nil {
innerErr = err
return false
}
return consumer(output)
}); err != nil {
return err
}
return innerErr
}
func (u *Manager) ForEachSpentTreasuryOutput(consumer TreasuryOutputConsumer, options ...IterateOption) error {
opt := iterateOptions(options)
if opt.readLockLedger {
u.ReadLockLedger()
defer u.ReadUnlockLedger()
}
var innerErr error
var i int
if err := u.utxoStorage.Iterate([]byte{UTXOStoreKeyPrefixTreasuryOutput, TreasuryOutputSpentPrefix}, func(key kvstore.Key, value kvstore.Value) bool {
if (opt.maxResultCount > 0) && (i >= opt.maxResultCount) {
return false
}
i++
output := &TreasuryOutput{}
if err := output.kvStorableLoad(u, key, value); err != nil {
innerErr = err
return false
}
return consumer(output)
}); err != nil {
return err
}
return innerErr
}
// code guards.
var _ kvStorable = &TreasuryOutput{}