forked from wanchain/go-wanchain
/
ota_storage.go
461 lines (375 loc) · 12.6 KB
/
ota_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
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
// Copyright 2018 Wanchain Foundation Ltd
package vm
import (
"bytes"
"errors"
"fmt"
"math/big"
"math/rand"
"strconv"
"github.com/wanchain/go-wanchain/common"
"github.com/wanchain/go-wanchain/crypto"
"github.com/wanchain/go-wanchain/log"
)
var (
ErrUnknown = errors.New("unknown error")
ErrInvalidOTAAddr = errors.New("invalid OTA addrss")
ErrInvalidOTAAX = errors.New("invalid OTA AX")
ErrOTAExistAlready = errors.New("OTA exist already")
ErrOTABalanceIsZero = errors.New("OTA balance is 0")
)
// OTABalance2ContractAddr convert ota balance to ota storage address
//
// 1 wancoin --> (bigint)1000000000000000000 --> "0x0000000000000000000001000000000000000000"
//
func OTABalance2ContractAddr(balance *big.Int) common.Address {
if balance == nil {
return common.Address{}
}
return common.HexToAddress(balance.String())
// return common.BigToAddress(balance)
}
// GetAXFromWanAddr retrieve ota AX from ota WanAddr
func GetAXFromWanAddr(otaWanAddr []byte) ([]byte, error) {
if len(otaWanAddr) != common.WAddressLength {
return nil, ErrInvalidOTAAddr
}
return otaWanAddr[1 : 1+common.HashLength], nil
}
// IsAXPointToWanAddr check whether AX point to otaWanAddr or not
func IsAXPointToWanAddr(AX []byte, otaWanAddr []byte) bool {
findAX, err := GetAXFromWanAddr(otaWanAddr)
if err != nil {
return false
}
return bytes.Equal(findAX, AX)
}
// GetOtaBalanceFromAX retrieve ota balance from ota AX
func GetOtaBalanceFromAX(statedb StateDB, otaAX []byte) (*big.Int, error) {
if statedb == nil {
return nil, ErrUnknown
}
if len(otaAX) != common.HashLength {
return nil, ErrInvalidOTAAX
}
balance := statedb.GetStateByteArray(otaBalanceStorageAddr, common.BytesToHash(otaAX))
if len(balance) == 0 {
return common.Big0, nil
}
return new(big.Int).SetBytes(balance), nil
}
// SetOtaBalanceToAX set ota balance as 'balance'. Overwrite if ota balance exist already.
func SetOtaBalanceToAX(statedb StateDB, otaAX []byte, balance *big.Int) error {
if statedb == nil || balance == nil {
return ErrUnknown
}
if len(otaAX) != common.HashLength {
return ErrInvalidOTAAX
}
statedb.SetStateByteArray(otaBalanceStorageAddr, common.BytesToHash(otaAX), balance.Bytes())
return nil
}
// ChechOTAExist checks the OTA exist or not.
//
// In order to avoid additional ota have conflict with existing,
// even if AX exist in balance storage already, will return true.
func CheckOTAAXExist(statedb StateDB, otaAX []byte) (exist bool, balance *big.Int, err error) {
if statedb == nil {
return false, nil, ErrUnknown
}
if len(otaAX) != common.HashLength {
return false, nil, ErrInvalidOTAAX
}
balance, err = GetOtaBalanceFromAX(statedb, otaAX[:common.HashLength])
if err != nil {
return false, nil, err
}
if balance.Cmp(common.Big0) == 0 {
return false, nil, nil
}
return true, balance, nil
}
func CheckOTALongAddrExist(statedb StateDB, otaLongAddr []byte) (exist bool, balance *big.Int, err error) {
if statedb == nil {
return false, nil, ErrUnknown
}
if len(otaLongAddr) != 33 {
return false, nil, ErrInvalidOTAAX
}
otaAX := otaLongAddr[1 : 1+common.HashLength]
if err != nil {
return false, nil, err
}
balance, err = GetOtaBalanceFromAX(statedb, otaAX)
if err != nil {
return false, nil, err
}
if balance.Cmp(common.Big0) == 0 {
return false, nil, nil
}
mptAddr := OTABalance2ContractAddr(balance)
otaStored := statedb.GetStateByteArray(mptAddr, common.BytesToHash(otaAX))
fmt.Println(common.ToHex(mptAddr.Bytes()))
fmt.Println(common.ToHex(otaLongAddr))
if otaStored == nil {
return false, nil, nil
}
if !bytes.Equal(otaLongAddr, otaStored[:33]) {
return false, nil, nil
}
return true, balance, nil
}
func BatCheckOTAExist(statedb StateDB, otaLongAddrs [][]byte) (exist bool, balance *big.Int, unexistOta []byte, err error) {
if statedb == nil || len(otaLongAddrs) == 0 {
return false, nil, nil, ErrUnknown
}
for _, otaLongAddr := range otaLongAddrs {
if len(otaLongAddr) != 33 {
return false, nil, otaLongAddr, ErrInvalidOTAAX
}
exist, balanceTmp, err := CheckOTALongAddrExist(statedb, otaLongAddr)
if err != nil {
return false, nil, otaLongAddr, err
} else if !exist {
return false, nil, otaLongAddr, errors.New("ota doesn't exist:" + common.ToHex(otaLongAddr))
} else if balanceTmp.Cmp(common.Big0) == 0 {
return false, nil, otaLongAddr, errors.New("ota balance is 0! ota:" + common.ToHex(otaLongAddr))
} else if balance == nil {
balance = balanceTmp
continue
} else if balance.Cmp(balanceTmp) != 0 {
return false, nil, otaLongAddr, errors.New("otas have different balances! ota:" + common.ToHex(otaLongAddr))
}
}
return true, balance, nil, nil
}
func GetUnspendOTATotalBalance(statedb StateDB) (*big.Int, error) {
if statedb == nil {
return nil, ErrUnknown
}
totalOTABalance, totalSpendedOTABalance := big.NewInt(0), big.NewInt(0)
// total history OTA balance (include spended)
statedb.ForEachStorageByteArray(otaBalanceStorageAddr, func(key common.Hash, value []byte) bool {
if len(value) == 0 {
log.Warn("total ota balance. value is empoty!", "key", key.String())
return true
}
balance := new(big.Int).SetBytes(value)
totalOTABalance.Add(totalOTABalance, balance)
log.Debug("total ota balance.", "key", key.String(), "balance:", balance.String())
return true
})
// total spended OTA balance
statedb.ForEachStorageByteArray(otaImageStorageAddr, func(key common.Hash, value []byte) bool {
if len(value) == 0 {
log.Warn("total spended ota balance. value is empoty!", "key", key.String())
return true
}
balance := new(big.Int).SetBytes(value)
totalSpendedOTABalance.Add(totalSpendedOTABalance, balance)
log.Debug("total spended ota balance.", "key", key.String(), "balance:", balance.String())
return true
})
log.Debug("total unspended OTA balance", "total history OTA balance:", totalOTABalance.String(), "total spended OTA balance:", totalSpendedOTABalance.String())
return totalOTABalance.Sub(totalOTABalance, totalSpendedOTABalance), nil
}
// setOTA storage ota info, include balance and WanAddr. Overwrite if ota exist already.
func setOTA(statedb StateDB, balance *big.Int, otaWanAddr []byte) error {
if statedb == nil || balance == nil {
return ErrUnknown
}
if len(otaWanAddr) != common.WAddressLength {
return ErrInvalidOTAAddr
}
otaAX, _ := GetAXFromWanAddr(otaWanAddr)
//balanceOld, err := GetOtaBalanceFromAX(statedb, otaAX)
//if err != nil {
// return err
//}
//
//if balanceOld != nil && balanceOld.Cmp(common.Big0) != 0 {
// return errors.New("ota balance is not 0! old balance:" + balanceOld.String())
//}
mptAddr := OTABalance2ContractAddr(balance)
statedb.SetStateByteArray(mptAddr, common.BytesToHash(otaAX), otaWanAddr)
return SetOtaBalanceToAX(statedb, otaAX, balance)
}
// AddOTAIfNotExist storage ota info if doesn't exist already.
func AddOTAIfNotExist(statedb StateDB, balance *big.Int, otaWanAddr []byte) (bool, error) {
if statedb == nil || balance == nil {
return false, ErrUnknown
}
if len(otaWanAddr) != common.WAddressLength {
return false, ErrInvalidOTAAddr
}
otaAX, _ := GetAXFromWanAddr(otaWanAddr)
otaAddrKey := common.BytesToHash(otaAX)
exist, _, err := CheckOTAAXExist(statedb, otaAddrKey[:])
if err != nil {
return false, err
}
if exist {
return false, ErrOTAExistAlready
}
err = setOTA(statedb, balance, otaWanAddr)
if err != nil {
return false, err
}
return true, nil
}
// GetOTAInfoFromAX retrieve ota info, include balance and WanAddr
func GetOTAInfoFromAX(statedb StateDB, otaAX []byte) (otaWanAddr []byte, balance *big.Int, err error) {
if statedb == nil {
return nil, nil, ErrUnknown
}
if len(otaAX) < common.HashLength {
return nil, nil, ErrInvalidOTAAX
}
otaAddrKey := common.BytesToHash(otaAX)
balance, err = GetOtaBalanceFromAX(statedb, otaAddrKey[:])
if err != nil {
return nil, nil, err
}
if balance == nil || balance.Cmp(common.Big0) == 0 {
return nil, nil, ErrOTABalanceIsZero
}
mptAddr := OTABalance2ContractAddr(balance)
otaValue := statedb.GetStateByteArray(mptAddr, otaAddrKey)
if otaValue != nil && len(otaValue) != 0 {
return otaValue, balance, nil
}
return nil, balance, nil
}
type GetOTASetEnv struct {
otaAX []byte
setNum int
getNum int
loopTimes int
rnd int
otaWanAddrSet [][]byte
}
func (env *GetOTASetEnv) OTAInSet(ota []byte) bool {
for _, exist := range env.otaWanAddrSet {
if bytes.Equal(exist, ota) {
return true
}
}
return false
}
func (env *GetOTASetEnv) UpdateRnd() {
env.rnd = rand.Intn(100) + 1
}
func (env *GetOTASetEnv) IsSetFull() bool {
return env.getNum >= env.setNum
}
func (env *GetOTASetEnv) RandomSelOTA(value []byte) bool {
env.loopTimes++
if env.loopTimes%env.rnd == 0 {
env.otaWanAddrSet = append(env.otaWanAddrSet, value)
env.getNum++
env.UpdateRnd()
return true
} else {
return false
}
}
// doOTAStorageTravelCallBack implement ota mpt travel call back
func doOTAStorageTravelCallBack(env *GetOTASetEnv, value []byte) (bool, error) {
// find self, return true to continue travel loop
if IsAXPointToWanAddr(env.otaAX, value) {
return true, nil
}
// ota contained in set already, return true to continue travel loop
if env.OTAInSet(value) {
return true, nil
}
// random select
// if set full already, return false to stop travel loop
if bGet := env.RandomSelOTA(value); bGet {
return !env.IsSetFull(), nil
} else {
return true, nil
}
}
// GetOTASet retrieve the setNum of same balance OTA address of the input OTA setting by otaAX, and ota balance.
// Rules:
// 1: The result can't contain otaAX self;
// 2: The result can't contain duplicate items;
// 3: No ota exist in the mpt, return error;
// 4: OTA total count in the mpt less or equal to the setNum, return error(returned set must
// can't contain otaAX self, so need more exist ota in mpt);
// 5: If find invalid ota wanaddr, return error;
// 6: Travel the ota mpt.Record loop exist ota cumulative times as loopTimes.
// Generate a random number as rnd.
// If loopTimes%rnd == 0, collect current exist ota to result set and update the rnd.
// Loop checking exist ota and loop traveling ota mpt, untile collect enough ota or find error.
//
func GetOTASet(statedb StateDB, otaAX []byte, setNum int) (otaWanAddrs [][]byte, balance *big.Int, err error) {
if statedb == nil {
return nil, nil, ErrUnknown
}
if len(otaAX) != common.HashLength {
return nil, nil, ErrInvalidOTAAX
}
balance, err = GetOtaBalanceFromAX(statedb, otaAX)
if err != nil {
return nil, nil, err
} else if balance == nil || balance.Cmp(common.Big0) == 0 {
return nil, nil, errors.New("can't find ota address balance!")
}
mptAddr := OTABalance2ContractAddr(balance)
log.Debug("GetOTASet", "mptAddr", common.ToHex(mptAddr[:]))
env := GetOTASetEnv{otaAX, setNum, 0, 0, 0, nil}
env.otaWanAddrSet = make([][]byte, 0, setNum)
env.UpdateRnd()
mptEleCount := 0 // total number of ota containing in mpt
for {
statedb.ForEachStorageByteArray(mptAddr, func(key common.Hash, value []byte) bool {
mptEleCount++
if len(value) != common.WAddressLength {
log.Error("invalid OTA address!", "balance", balance, "value", value)
err = errors.New(fmt.Sprint("invalid OTA address! balance:", balance, ", ota:", value))
return false
}
bContinue, err := doOTAStorageTravelCallBack(&env, value)
if err != nil {
return false
} else {
return bContinue
}
})
if env.IsSetFull() {
return env.otaWanAddrSet, balance, nil
} else if err != nil {
return nil, nil, err
} else if mptEleCount == 0 {
return nil, balance, errors.New("no ota exist! balance:" + balance.String())
} else if setNum >= mptEleCount {
return nil, balance, errors.New("too more required ota number! balance:" + balance.String() +
", exist count:" + strconv.Itoa(mptEleCount))
} else {
continue
}
}
}
// CheckOTAImageExist checks ota image key exist already or not
func CheckOTAImageExist(statedb StateDB, otaImage []byte) (bool, []byte, error) {
if statedb == nil || len(otaImage) == 0 {
return false, nil, errors.New("invalid input param!")
}
otaImageKey := crypto.Keccak256Hash(otaImage)
otaImageValue := statedb.GetStateByteArray(otaImageStorageAddr, otaImageKey)
if otaImageValue != nil && len(otaImageValue) != 0 {
return true, otaImageValue, nil
}
return false, nil, nil
}
// AddOTAImage storage ota image key. Overwrite if exist already.
func AddOTAImage(statedb StateDB, otaImage []byte, value []byte) error {
if statedb == nil || len(otaImage) == 0 || len(value) == 0 {
return errors.New("invalid input param!")
}
otaImageKey := crypto.Keccak256Hash(otaImage)
statedb.SetStateByteArray(otaImageStorageAddr, otaImageKey, value)
return nil
}