-
Notifications
You must be signed in to change notification settings - Fork 82
/
impawnUtil.go
431 lines (404 loc) · 11.2 KB
/
impawnUtil.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
package types
import (
"bytes"
"errors"
"fmt"
"math/big"
"github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/common/hexutil"
"github.com/truechain/truechain-engineering-code/crypto"
"github.com/truechain/truechain-engineering-code/params"
)
var (
baseUnit = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
fbaseUnit = new(big.Float).SetFloat64(float64(baseUnit.Int64()))
mixImpawn = new(big.Int).Mul(big.NewInt(1000), baseUnit)
Base = new(big.Int).SetUint64(10000)
InvalidFee = big.NewInt(65535)
// StakingAddress is defined as Address('truestaking')
// i.e. contractAddress = 0x000000000000000000747275657374616b696E67
StakingAddress = common.BytesToAddress([]byte("truestaking"))
MixEpochCount = 2
FoundationAddress = common.HexToAddress("0xDA79B1C2645750c655D848e04c27E2cD9d263C48")
)
var (
ErrInvalidParam = errors.New("Invalid Param")
ErrOverEpochID = errors.New("Over epoch id")
ErrNotSequential = errors.New("epoch id not sequential")
ErrInvalidEpochInfo = errors.New("Invalid epoch info")
ErrNotFoundEpoch = errors.New("cann't found the epoch info")
ErrInvalidStaking = errors.New("Invalid staking account")
ErrMatchEpochID = errors.New("wrong match epoch id in a reward block")
ErrNotStaking = errors.New("Not match the staking account")
ErrNotDelegation = errors.New("Not match the delegation account")
ErrNotMatchEpochInfo = errors.New("the epoch info is not match with accounts")
ErrNotElectionTime = errors.New("not time to election the next committee")
ErrAmountOver = errors.New("the amount more than staking amount")
ErrDelegationSelf = errors.New("Cann't delegation myself")
ErrRedeemAmount = errors.New("wrong redeem amount")
ErrForbidAddress = errors.New("Forbidding Address")
ErrRepeatPk = errors.New("repeat PK on staking tx")
)
const (
// StateStakingOnce can be election only once
StateStakingOnce uint8 = 1 << iota
// StateStakingAuto can be election in every epoch
StateStakingAuto
StateStakingCancel
// StateRedeem can be redeem real time (after MaxRedeemHeight block)
StateRedeem
// StateRedeemed flag the asset which is staking in the height is redeemed
StateRedeemed
)
const (
OpQueryStaking uint8 = 1 << iota
OpQueryLocked
OpQueryCancelable
)
type SummayEpochInfo struct {
EpochID uint64
SaCount uint64
DaCount uint64
BeginHeight uint64
EndHeight uint64
AllAmount *big.Int
}
type ImpawnSummay struct {
LastReward uint64
Accounts uint64
AllAmount *big.Int
Infos []*SummayEpochInfo
}
func ToJSON(ii *ImpawnSummay) map[string]interface{} {
item := make(map[string]interface{})
item["lastRewardHeight"] = ii.LastReward
item["AccountsCounts"] = ii.Accounts
item["currentAllStaking"] = (*hexutil.Big)(ii.AllAmount)
items := make([]map[string]interface{}, 0, 0)
for _, val := range ii.Infos {
info := make(map[string]interface{})
info["EpochID"] = val.EpochID
info["SaCount"] = val.SaCount
info["DaCount"] = val.DaCount
info["BeginHeight"] = val.BeginHeight
info["EndHeight"] = val.EndHeight
info["AllAmount"] = (*hexutil.Big)(val.AllAmount)
items = append(items, info)
}
item["EpochInfos"] = items
return item
}
type RewardInfo struct {
Address common.Address `json:"Address"`
Amount *big.Int `json:"Amount"`
Staking *big.Int `json:"Staking"`
}
func (e *RewardInfo) clone() *RewardInfo {
return &RewardInfo{
Address: e.Address,
Amount: new(big.Int).Set(e.Amount),
Staking: new(big.Int).Set(e.Staking),
}
}
func (e *RewardInfo) String() string {
return fmt.Sprintf("[Address:%v,Amount:%s\n]", e.Address.String(), ToTrue(e.Amount).Text('f', 8))
}
func FetchOne(sas []*SARewardInfos, addr common.Address) []*RewardInfo {
items := make([]*RewardInfo, 0, 0)
for _, val := range sas {
if len(val.Items) > 0 {
saAddr := val.getSaAddress()
if bytes.Equal(saAddr.Bytes(), addr.Bytes()) {
items = mergeRewardInfos(items, val.Items)
}
}
}
return items
}
func mergeRewardInfos(items1, itmes2 []*RewardInfo) []*RewardInfo {
for _, v1 := range itmes2 {
found := false
for _, v2 := range items1 {
if bytes.Equal(v1.Address.Bytes(), v2.Address.Bytes()) {
found = true
v2.Amount = new(big.Int).Add(v2.Amount, v1.Amount)
}
}
if !found {
items1 = append(items1, v1)
}
}
return items1
}
type SARewardInfos struct {
Items []*RewardInfo `json:"Items"`
}
func (s *SARewardInfos) clone() *SARewardInfos {
var res SARewardInfos
for _,v := range s.Items {
res.Items = append(res.Items,v.clone())
}
return &res
}
func (s *SARewardInfos) getSaAddress() common.Address {
if len(s.Items) > 0 {
return s.Items[0].Address
}
return common.Address{}
}
func (s *SARewardInfos) String() string {
var ss string
for _, v := range s.Items {
ss += v.String()
}
return ss
}
type TimedChainReward struct {
St uint64
Number uint64
Reward *ChainReward
}
type ChainReward struct {
Height uint64
St uint64
Foundation *RewardInfo `json:"developerReward"`
CoinBase *RewardInfo `json:"blockminer"`
FruitBase []*RewardInfo `json:"fruitminer"`
CommitteeBase []*SARewardInfos `json:"committeeReward"`
}
func CloneChainReward(reward *ChainReward) *ChainReward {
var res ChainReward
res.Height,res.St = reward.Height,reward.St
res.Foundation = reward.Foundation.clone()
res.CoinBase = reward.CoinBase.clone()
for _,v := range reward.FruitBase {
res.FruitBase = append(res.FruitBase,v.clone())
}
for _,v := range reward.CommitteeBase {
res.CommitteeBase = append(res.CommitteeBase,v.clone())
}
return &res
}
type BalanceInfo struct {
Address common.Address `json:"address"`
Valid *big.Int `json:"valid"`
Lock *big.Int `json:"lock"`
}
type BlockBalance struct {
Balance []*BalanceInfo `json:"addrWithBalance" gencodec:"required"`
}
func (s *BlockBalance) ToMap() map[common.Address]*BalanceInfo {
infos := make(map[common.Address]*BalanceInfo)
for _, v := range s.Balance {
infos[v.Address] = v
}
return infos
}
func ToBalanceInfos(items map[common.Address]*BalanceInfo) []*BalanceInfo {
infos := make([]*BalanceInfo, 0, 0)
for k, v := range items {
infos = append(infos, &BalanceInfo{
Address: k,
Valid: new(big.Int).Set(v.Valid),
Lock: new(big.Int).Set(v.Lock),
})
}
return infos
}
func NewChainReward(height, tt uint64, found, coin *RewardInfo, fruits []*RewardInfo, committee []*SARewardInfos) *ChainReward {
return &ChainReward{
Height: height,
St: tt,
Foundation: found,
CoinBase: coin,
FruitBase: fruits,
CommitteeBase: committee,
}
}
func ToRewardInfos1(items map[common.Address]*big.Int) []*RewardInfo {
infos := make([]*RewardInfo, 0, 0)
for k, v := range items {
infos = append(infos, &RewardInfo{
Address: k,
Amount: new(big.Int).Set(v),
})
}
return infos
}
func ToRewardInfos2(items map[common.Address]*big.Int) []*SARewardInfos {
infos := make([]*SARewardInfos, 0, 0)
for k, v := range items {
items := []*RewardInfo{&RewardInfo{
Address: k,
Amount: new(big.Int).Set(v),
}}
infos = append(infos, &SARewardInfos{
Items: items,
})
}
return infos
}
func MergeReward(map1, map2 map[common.Address]*big.Int) map[common.Address]*big.Int {
for k, v := range map2 {
if vv, ok := map1[k]; ok {
map1[k] = new(big.Int).Add(vv, v)
} else {
map1[k] = v
}
}
return map1
}
type EpochIDInfo struct {
EpochID uint64
BeginHeight uint64
EndHeight uint64
}
func (e *EpochIDInfo) isValid() bool {
if e.EpochID < 0 {
return false
}
if e.EpochID == 0 && params.DposForkPoint+1 != e.BeginHeight {
return false
}
if e.BeginHeight < 0 || e.EndHeight <= 0 || e.EndHeight <= e.BeginHeight {
return false
}
return true
}
func (e *EpochIDInfo) String() string {
return fmt.Sprintf("[id:%v,begin:%v,end:%v]", e.EpochID, e.BeginHeight, e.EndHeight)
}
// the key is epochid if StakingValue as a locked asset,otherwise key is block height if StakingValue as a staking asset
type StakingValue struct {
Value map[uint64]*big.Int
}
type LockedItem struct {
Amount *big.Int
Locked bool
}
// LockedValue,the key of Value is epochid
type LockedValue struct {
Value map[uint64]*LockedItem
}
func (s *StakingValue) ToLockedValue(height uint64) *LockedValue {
res := make(map[uint64]*LockedItem)
for k, v := range s.Value {
item := &LockedItem{
Amount: new(big.Int).Set(v),
Locked: !IsUnlocked(k, height),
}
res[k] = item
}
return &LockedValue{
Value: res,
}
}
func toReward(val *big.Float) *big.Int {
val = val.Mul(val, fbaseUnit)
ii, _ := val.Int64()
return big.NewInt(ii)
}
func ToTrue(val *big.Int) *big.Float {
return new(big.Float).Quo(new(big.Float).SetInt(val), fbaseUnit)
}
func FromBlock(block *SnailBlock) (begin, end uint64) {
begin, end = 0, 0
l := len(block.Fruits())
if l > 0 {
begin, end = block.Fruits()[0].FastNumber().Uint64(), block.Fruits()[l-1].FastNumber().Uint64()
}
return
}
func GetFirstEpoch() *EpochIDInfo {
return &EpochIDInfo{
EpochID: params.FirstNewEpochID,
BeginHeight: params.DposForkPoint + 1,
EndHeight: params.DposForkPoint + params.NewEpochLength,
}
}
func GetPreFirstEpoch() *EpochIDInfo {
return &EpochIDInfo{
EpochID: params.FirstNewEpochID - 1,
BeginHeight: 0,
EndHeight: params.DposForkPoint,
}
}
func GetEpochFromHeight(hh uint64) *EpochIDInfo {
if hh <= params.DposForkPoint {
return GetPreFirstEpoch()
}
first := GetFirstEpoch()
if hh <= first.EndHeight {
return first
}
var eid uint64
if (hh-first.EndHeight)%params.NewEpochLength == 0 {
eid = (hh-first.EndHeight)/params.NewEpochLength + first.EpochID
} else {
eid = (hh-first.EndHeight)/params.NewEpochLength + first.EpochID + 1
}
return GetEpochFromID(eid)
}
func GetEpochFromID(eid uint64) *EpochIDInfo {
preFirst := GetPreFirstEpoch()
if preFirst.EpochID == eid {
return preFirst
}
first := GetFirstEpoch()
if first.EpochID >= eid {
return first
}
return &EpochIDInfo{
EpochID: eid,
BeginHeight: first.EndHeight + (eid-first.EpochID-1)*params.NewEpochLength + 1,
EndHeight: first.EndHeight + (eid-first.EpochID)*params.NewEpochLength,
}
}
func GetEpochFromRange(begin, end uint64) []*EpochIDInfo {
if end == 0 || begin > end || (begin < params.DposForkPoint && end < params.DposForkPoint) {
return nil
}
var ids []*EpochIDInfo
e1 := GetEpochFromHeight(begin)
e := uint64(0)
if e1 != nil {
ids = append(ids, e1)
e = e1.EndHeight
} else {
e = params.DposForkPoint
}
for e < end {
e2 := GetEpochFromHeight(e + 1)
if e1.EpochID != e2.EpochID {
ids = append(ids, e2)
}
e = e2.EndHeight
}
if len(ids) == 0 {
return nil
}
return ids
}
func CopyVotePk(pk []byte) []byte {
cc := make([]byte, len(pk))
copy(cc, pk)
return cc
}
func ValidPk(pk []byte) error {
_, err := crypto.UnmarshalPubkey(pk)
return err
}
func MinCalcRedeemHeight(eid uint64) uint64 {
e := GetEpochFromID(eid + 1)
return e.BeginHeight + params.MaxRedeemHeight + 1
}
func ForbidAddress(addr common.Address) error {
if bytes.Equal(addr[:], StakingAddress[:]) {
return errors.New(fmt.Sprint("addr error:", addr, ErrForbidAddress))
}
return nil
}
func IsUnlocked(eid, height uint64) bool {
e := GetEpochFromID(eid + 1)
return height > e.BeginHeight+params.MaxRedeemHeight
}