-
Notifications
You must be signed in to change notification settings - Fork 118
/
storage.go
305 lines (274 loc) · 6.62 KB
/
storage.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
// Copyright (C) 2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package storage
import (
"context"
"encoding/binary"
"errors"
"fmt"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/hashing"
smath "github.com/ava-labs/avalanchego/utils/math"
"github.com/ava-labs/hypersdk/codec"
"github.com/ava-labs/hypersdk/consts"
"github.com/ava-labs/hypersdk/fees"
"github.com/ava-labs/hypersdk/state"
mconsts "github.com/ava-labs/hypersdk/examples/morpheusvm/consts"
)
type ReadState func(context.Context, [][]byte) ([][]byte, []error)
// Metadata
// 0x0/ (tx)
// -> [txID] => timestamp
//
// State
// / (height) => store in root
// -> [heightPrefix] => height
// 0x0/ (balance)
// -> [owner] => balance
// 0x1/ (hypersdk-height)
// 0x2/ (hypersdk-timestamp)
// 0x3/ (hypersdk-fee)
// 0x4/ (hypersdk-incoming warp)
// 0x5/ (hypersdk-outgoing warp)
const (
// metaDB
txPrefix = 0x0
// stateDB
balancePrefix = 0x0
heightPrefix = 0x1
timestampPrefix = 0x2
feePrefix = 0x3
incomingWarpPrefix = 0x4
outgoingWarpPrefix = 0x5
)
const (
BalanceChunks uint16 = 1
balanceAddrLen = 20 // Ethereum compatible address length
)
var (
failureByte = byte(0x0)
successByte = byte(0x1)
heightKey = []byte{heightPrefix}
timestampKey = []byte{timestampPrefix}
feeKey = []byte{feePrefix}
)
// [txPrefix] + [txID]
func TxKey(id ids.ID) (k []byte) {
k = make([]byte, 1+consts.IDLen)
k[0] = txPrefix
copy(k[1:], id[:])
return
}
func StoreTransaction(
_ context.Context,
db database.KeyValueWriter,
id ids.ID,
t int64,
success bool,
units fees.Dimensions,
fee uint64,
) error {
k := TxKey(id)
v := make([]byte, consts.Uint64Len+1+fees.DimensionsLen+consts.Uint64Len)
binary.BigEndian.PutUint64(v, uint64(t))
if success {
v[consts.Uint64Len] = successByte
} else {
v[consts.Uint64Len] = failureByte
}
copy(v[consts.Uint64Len+1:], units.Bytes())
binary.BigEndian.PutUint64(v[consts.Uint64Len+1+fees.DimensionsLen:], fee)
return db.Put(k, v)
}
func GetTransaction(
_ context.Context,
db database.KeyValueReader,
id ids.ID,
) (bool, int64, bool, fees.Dimensions, uint64, error) {
k := TxKey(id)
v, err := db.Get(k)
if errors.Is(err, database.ErrNotFound) {
return false, 0, false, fees.Dimensions{}, 0, nil
}
if err != nil {
return false, 0, false, fees.Dimensions{}, 0, err
}
t := int64(binary.BigEndian.Uint64(v))
success := true
if v[consts.Uint64Len] == failureByte {
success = false
}
d, err := fees.UnpackDimensions(v[consts.Uint64Len+1 : consts.Uint64Len+1+fees.DimensionsLen])
if err != nil {
return false, 0, false, fees.Dimensions{}, 0, err
}
fee := binary.BigEndian.Uint64(v[consts.Uint64Len+1+fees.DimensionsLen:])
return true, t, success, d, fee, nil
}
// [balancePrefix] + last [balanceAddrLen] bytes of [hashed] + [BalanceChunks]
// it's expected that [hashed] the of the hash of the address
func balanceKey(hashed []byte) (k []byte) {
k = make([]byte, 1+balanceAddrLen+consts.Uint16Len)
k[0] = balancePrefix
copy(k[1:], hashed[len(hashed)-balanceAddrLen:])
binary.BigEndian.PutUint16(k[1+balanceAddrLen:], BalanceChunks)
return k
}
func BalanceKey(addr codec.Address) (k []byte) {
hashed := hashing.ComputeHash256(addr[:])
return balanceKey(hashed)
}
// If locked is 0, then account does not exist
func GetBalance(
ctx context.Context,
im state.Immutable,
addr codec.Address,
) (uint64, error) {
_, bal, _, err := getBalance(ctx, im, addr)
return bal, err
}
func GetBalanceHashed(
ctx context.Context,
im state.Immutable,
hashed []byte,
) (uint64, error) {
k := balanceKey(hashed)
bal, _, err := innerGetBalance(im.GetValue(ctx, k))
return bal, err
}
func getBalance(
ctx context.Context,
im state.Immutable,
addr codec.Address,
) ([]byte, uint64, bool, error) {
k := BalanceKey(addr)
bal, exists, err := innerGetBalance(im.GetValue(ctx, k))
return k, bal, exists, err
}
// Used to serve RPC queries
func GetBalanceFromState(
ctx context.Context,
f ReadState,
addr codec.Address,
) (uint64, error) {
k := BalanceKey(addr)
values, errs := f(ctx, [][]byte{k})
bal, _, err := innerGetBalance(values[0], errs[0])
return bal, err
}
func innerGetBalance(
v []byte,
err error,
) (uint64, bool, error) {
if errors.Is(err, database.ErrNotFound) {
return 0, false, nil
}
if err != nil {
return 0, false, err
}
return binary.BigEndian.Uint64(v), true, nil
}
func SetBalance(
ctx context.Context,
mu state.Mutable,
addr codec.Address,
balance uint64,
) error {
k := BalanceKey(addr)
return setBalance(ctx, mu, k, balance)
}
func SetBalanceHashed(
ctx context.Context,
mu state.Mutable,
hashed []byte,
balance uint64,
) error {
k := balanceKey(hashed)
return setBalance(ctx, mu, k, balance)
}
func setBalance(
ctx context.Context,
mu state.Mutable,
key []byte,
balance uint64,
) error {
return mu.Insert(ctx, key, binary.BigEndian.AppendUint64(nil, balance))
}
func AddBalance(
ctx context.Context,
mu state.Mutable,
addr codec.Address,
amount uint64,
create bool,
) error {
key, bal, exists, err := getBalance(ctx, mu, addr)
if err != nil {
return err
}
// Don't add balance if account doesn't exist. This
// can be useful when processing fee refunds.
if !exists && !create {
return nil
}
nbal, err := smath.Add64(bal, amount)
if err != nil {
return fmt.Errorf(
"%w: could not add balance (bal=%d, addr=%v, amount=%d)",
ErrInvalidBalance,
bal,
codec.MustAddressBech32(mconsts.HRP, addr),
amount,
)
}
return setBalance(ctx, mu, key, nbal)
}
func SubBalance(
ctx context.Context,
mu state.Mutable,
addr codec.Address,
amount uint64,
) error {
key, bal, _, err := getBalance(ctx, mu, addr)
if err != nil {
return err
}
nbal, err := smath.Sub(bal, amount)
if err != nil {
return fmt.Errorf(
"%w: could not subtract balance (bal=%d, addr=%v, amount=%d)",
ErrInvalidBalance,
bal,
codec.MustAddressBech32(mconsts.HRP, addr),
amount,
)
}
if nbal == 0 {
// If there is no balance left, we should delete the record instead of
// setting it to 0.
return mu.Remove(ctx, key)
}
return setBalance(ctx, mu, key, nbal)
}
func HeightKey() (k []byte) {
return heightKey
}
func TimestampKey() (k []byte) {
return timestampKey
}
func FeeKey() (k []byte) {
return feeKey
}
func IncomingWarpKeyPrefix(sourceChainID ids.ID, msgID ids.ID) (k []byte) {
k = make([]byte, 1+consts.IDLen*2)
k[0] = incomingWarpPrefix
copy(k[1:], sourceChainID[:])
copy(k[1+consts.IDLen:], msgID[:])
return k
}
func OutgoingWarpKeyPrefix(txID ids.ID) (k []byte) {
k = make([]byte, 1+consts.IDLen)
k[0] = outgoingWarpPrefix
copy(k[1:], txID[:])
return k
}