-
Notifications
You must be signed in to change notification settings - Fork 12
/
types.go
552 lines (475 loc) · 16.5 KB
/
types.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
package types
import (
"bytes"
"encoding/hex"
"fmt"
"math"
"math/big"
"sort"
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/functionx/fx-core/v7/contract"
fxtypes "github.com/functionx/fx-core/v7/types"
)
func NewDelegateAmount(amount sdkmath.Int) sdk.Coin {
return sdk.NewCoin(fxtypes.DefaultDenom, amount)
}
// --- ERC20Token --- //
func NewERC20Token(amount sdkmath.Int, contract string) ERC20Token {
return ERC20Token{Amount: amount, Contract: contract}
}
// ValidateBasic permforms stateless validation
func (m *ERC20Token) ValidateBasic() error {
if err := contract.ValidateEthereumAddress(m.Contract); err != nil {
return errorsmod.Wrap(err, "invalid contract address")
}
if !m.Amount.IsPositive() {
return errorsmod.Wrap(ErrInvalid, "amount")
}
return nil
}
type ERC20Tokens []ERC20Token
func (e ERC20Tokens) GetContracts() []gethcommon.Address {
contracts := make([]gethcommon.Address, 0, len(e))
for _, token := range e {
contracts = append(contracts, gethcommon.HexToAddress(token.Contract))
}
return contracts
}
func (e ERC20Tokens) GetAmounts() []sdkmath.Int {
amounts := make([]sdkmath.Int, 0, len(e))
for _, token := range e {
amounts = append(amounts, token.Amount)
}
return amounts
}
// --- BRIDGE VALIDATOR(S) --- //
// ValidateBasic performs stateless checks on validity
func (m *BridgeValidator) ValidateBasic() error {
if m.Power == 0 {
return errorsmod.Wrap(ErrEmpty, "power")
}
if err := contract.ValidateEthereumAddress(m.ExternalAddress); err != nil {
return errorsmod.Wrap(ErrInvalid, "external address")
}
return nil
}
// BridgeValidators is the sorted set of validator data for Ethereum bridge MultiSig set
type BridgeValidators []BridgeValidator
func (b BridgeValidators) Len() int {
return len(b)
}
func (b BridgeValidators) Less(i, j int) bool {
if b[i].Power == b[j].Power {
// Secondary sort on eth address in case powers are equal
return bytes.Compare([]byte(b[i].ExternalAddress), []byte(b[j].ExternalAddress)) == -1
}
return b[i].Power > b[j].Power
}
func (b BridgeValidators) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
// PowerDiff returns the difference in power between two bridge validator sets
// note this is Gravity bridge power *not* Cosmos voting power. Cosmos voting
// power is based on the absolute number of tokens in the staking pool at any given
// time Gravity bridge power is normalized using the equation.
//
// validators cosmos voting power / total cosmos voting power in this block = gravity bridge power / u32_max
//
// As an example if someone has 52% of the Cosmos voting power when a validator set is created their Gravity
// bridge voting power is u32_max * .52
//
// Normalized voting power dramatically reduces how often we have to produce new validator set updates. For example
// if the total on chain voting power increases by 1% due to inflation, we shouldn't have to generate a new validator
// set, after all the validators retained their relative percentages during inflation and normalized Gravity bridge power
// shows no difference.
func (b BridgeValidators) PowerDiff(c BridgeValidators) float64 {
powers := map[string]int64{}
// loop over b and initialize the map with their powers
for _, bv := range b {
powers[bv.ExternalAddress] = int64(bv.Power)
}
// subtract c powers from powers in the map, initializing
// uninitialized keys with negative numbers
for _, bv := range c {
if val, ok := powers[bv.ExternalAddress]; ok {
powers[bv.ExternalAddress] = val - int64(bv.Power)
} else {
powers[bv.ExternalAddress] = -int64(bv.Power)
}
}
var delta float64
for _, v := range powers {
// NOTE: we care about the absolute value of the changes
delta += math.Abs(float64(v))
}
return math.Abs(delta / float64(math.MaxUint32))
}
// TotalPower returns the total power in the bridge validator set
func (b BridgeValidators) TotalPower() (out uint64) {
for _, v := range b {
out += v.Power
}
return
}
// HasDuplicates returns true if there are duplicates in the set
func (b BridgeValidators) HasDuplicates() bool {
m := make(map[string]struct{}, len(b))
for i := range b {
m[b[i].ExternalAddress] = struct{}{}
}
return len(m) != len(b)
}
// GetPowers returns only the power values for all members
func (b BridgeValidators) GetPowers() []uint64 {
r := make([]uint64, len(b))
for i := range b {
r[i] = b[i].Power
}
return r
}
// ValidateBasic performs stateless checks
func (b BridgeValidators) ValidateBasic() error {
if len(b) == 0 {
return ErrEmpty
}
for i := range b {
if err := b[i].ValidateBasic(); err != nil {
return errorsmod.Wrapf(err, "member %d", i)
}
}
if b.HasDuplicates() {
return errorsmod.Wrap(ErrDuplicate, "address")
}
return nil
}
func (b BridgeValidators) Equal(o BridgeValidators) bool {
if len(b) != len(o) {
return false
}
for i, bv := range b {
ov := o[i]
if bv.Power != ov.Power || bv.ExternalAddress != ov.ExternalAddress {
return false
}
}
return true
}
// --- OracleSet(S) --- //
// NewOracleSet returns a new OracleSet
func NewOracleSet(nonce, height uint64, members BridgeValidators) *OracleSet {
sort.Sort(members)
return &OracleSet{
Nonce: nonce,
Members: members,
Height: height,
}
}
// GetCheckpoint returns the checkpoint
func (m *OracleSet) GetCheckpoint(gravityIDStr string) ([]byte, error) {
// the contract argument is not a arbitrary length array but a fixed length 32 byte
// array, therefore we have to utf8 encode the string (the default in this case) and
// then copy the variable length encoded data into a fixed length array. This function
// will panic if gravityId is too long to fit in 32 bytes
gravityID, err := fxtypes.StrToByte32(gravityIDStr)
if err != nil {
return nil, errorsmod.Wrap(err, "parse gravity id")
}
checkpoint, err := fxtypes.StrToByte32("checkpoint")
if err != nil {
return nil, err
}
memberAddresses := make([]gethcommon.Address, len(m.Members))
convertedPowers := make([]*big.Int, len(m.Members))
for i, m := range m.Members {
memberAddresses[i] = gethcommon.HexToAddress(m.ExternalAddress)
convertedPowers[i] = big.NewInt(int64(m.Power))
}
// the word 'checkpoint' needs to be the same as the 'name' above in the checkpointAbiJson
// but other than that it's a constant that has no impact on the output. This is because
// it gets encoded as a function name which we must then discard.
packBytes, packErr := contract.GetFxBridgeABI().Pack("oracleSetCheckpoint", gravityID, checkpoint, big.NewInt(int64(m.Nonce)), memberAddresses, convertedPowers)
// this should never happen outside of test since any case that could crash on encoding
// should be filtered above.
if packErr != nil {
return nil, errorsmod.Wrap(err, "packing checkpoint")
}
// we hash the resulting encoded bytes discarding the first 4 bytes these 4 bytes are the constant
// method name 'checkpoint'. If you where to replace the checkpoint constant in this code you would
// then need to adjust how many bytes you truncate off the front to get the output of abi.encode()
hash := crypto.Keccak256Hash(packBytes[4:])
return hash.Bytes(), nil
}
func (m *OracleSet) Equal(o *OracleSet) (bool, error) {
if m.Height != o.Height {
return false, errorsmod.Wrap(ErrInvalid, "oracle set heights mismatch")
}
if m.Nonce != o.Nonce {
return false, errorsmod.Wrap(ErrInvalid, "oracle set nonce mismatch")
}
if !BridgeValidators(m.Members).Equal(o.Members) {
return false, errorsmod.Wrap(ErrInvalid, "oracle set members mismatch")
}
return true, nil
}
func (m *OracleSet) GetTotalPower() uint64 {
if m == nil {
return 0
}
totalPower := uint64(0)
for _, member := range m.Members {
totalPower += member.Power
}
return totalPower
}
func (m *OracleSet) GetBridgePower(externalAddress string) (uint64, bool) {
if m == nil {
return 0, false
}
for _, member := range m.Members {
if externalAddress == member.ExternalAddress {
return member.Power, true
}
}
return 0, false
}
type OracleSets []*OracleSet
func (s OracleSets) Len() int {
return len(s)
}
func (s OracleSets) Less(i, j int) bool {
return s[i].Nonce > s[j].Nonce
}
func (s OracleSets) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// --- OutgoingTxBatch --- //
type OutgoingTxBatches []*OutgoingTxBatch
func (b OutgoingTxBatches) Len() int {
return len(b)
}
func (b OutgoingTxBatches) Less(i, j int) bool {
return b[i].BatchNonce > b[j].BatchNonce
}
func (b OutgoingTxBatches) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
// GetFees returns the total fees contained within a given batch
func (m *OutgoingTxBatch) GetFees() sdkmath.Int {
sum := sdkmath.ZeroInt()
for _, t := range m.Transactions {
sum = sum.Add(t.Fee.Amount)
}
return sum
}
// GetCheckpoint gets the checkpoint signature from the given outgoing tx batch
func (m *OutgoingTxBatch) GetCheckpoint(gravityIDString string) ([]byte, error) {
// the contract argument is not a arbitrary length array but a fixed length 32 byte
// array, therefore we have to utf8 encode the string (the default in this case) and
// then copy the variable length encoded data into a fixed length array. This function
// will panic if gravityId is too long to fit in 32 bytes
gravityID, err := fxtypes.StrToByte32(gravityIDString)
if err != nil {
return nil, errorsmod.Wrap(err, "parse gravity id")
}
// Create the methodName argument which salts the signature
batchMethodName, err := fxtypes.StrToByte32("transactionBatch")
if err != nil {
return nil, err
}
// Run through the elements of the batch and serialize them
txAmounts := make([]*big.Int, len(m.Transactions))
txDestinations := make([]gethcommon.Address, len(m.Transactions))
txFees := make([]*big.Int, len(m.Transactions))
for i, tx := range m.Transactions {
txAmounts[i] = tx.Token.Amount.BigInt()
txDestinations[i] = gethcommon.HexToAddress(tx.DestAddress)
txFees[i] = tx.Fee.Amount.BigInt()
}
// the methodName needs to be the same as the 'name' above in the checkpointAbiJson
// but other than that it's a constant that has no impact on the output. This is because
// it gets encoded as a function name which we must then discard.
abiEncodedBatch, err := contract.GetFxBridgeABI().Pack("submitBatchCheckpoint",
gravityID,
batchMethodName,
txAmounts,
txDestinations,
txFees,
big.NewInt(int64(m.BatchNonce)),
gethcommon.HexToAddress(m.TokenContract),
big.NewInt(int64(m.BatchTimeout)),
gethcommon.HexToAddress(m.FeeReceive),
)
// this should never happen outside of test since any case that could crash on encoding
// should be filtered above.
if err != nil {
return nil, errorsmod.Wrap(err, "packing checkpoint")
}
// we hash the resulting encoded bytes discarding the first 4 bytes these 4 bytes are the constant
// method name 'checkpoint'. If you where to replace the checkpoint constant in this code you would
// then need to adjust how many bytes you truncate off the front to get the output of abi.encode()
return crypto.Keccak256Hash(abiEncodedBatch[4:]).Bytes(), nil
}
// --- Oracle(S) --- //
func (m *Oracle) GetOracle() sdk.AccAddress {
return sdk.MustAccAddressFromBech32(m.OracleAddress)
}
func (m *Oracle) GetBridger() sdk.AccAddress {
return sdk.MustAccAddressFromBech32(m.BridgerAddress)
}
func (m *Oracle) GetValidator() sdk.ValAddress {
addr, err := sdk.ValAddressFromBech32(m.DelegateValidator)
if err != nil {
panic(err)
}
return addr
}
func (m *Oracle) GetSlashAmount(slashFraction sdk.Dec) sdkmath.Int {
slashAmount := sdk.NewDecFromInt(m.DelegateAmount).Mul(slashFraction).MulInt64(m.SlashTimes).TruncateInt()
slashAmount = sdkmath.MinInt(slashAmount, m.DelegateAmount)
slashAmount = sdkmath.MaxInt(slashAmount, sdkmath.ZeroInt())
return slashAmount
}
func (m *Oracle) GetPower() sdkmath.Int {
return m.DelegateAmount.Quo(sdk.DefaultPowerReduction)
}
func (m *Oracle) GetDelegateAddress(moduleName string) sdk.AccAddress {
data := append(m.GetOracle(), []byte(moduleName)...)
return crypto.Keccak256(data)[12:]
}
type Oracles []Oracle
func (o Oracles) Len() int {
return len(o)
}
func (o Oracles) Less(i, j int) bool {
return o[i].DelegateAmount.Sub(o[j].DelegateAmount).IsPositive()
}
func (o Oracles) Swap(i, j int) {
o[i], o[j] = o[j], o[i]
}
func MinBatchFeeToBaseFees(ms []MinBatchFee) map[string]sdkmath.Int {
kv := make(map[string]sdkmath.Int, len(ms))
for _, m := range ms {
if m.BaseFee.IsNil() || m.BaseFee.IsNegative() {
continue
}
kv[m.TokenContract] = m.BaseFee
}
return kv
}
type OutgoingTransferTxs []*OutgoingTransferTx
func (txs OutgoingTransferTxs) TotalFee() sdkmath.Int {
totalFee := sdkmath.NewInt(0)
for _, tx := range txs {
totalFee = totalFee.Add(tx.Fee.Amount)
}
return totalFee
}
// GetCheckpoint gets the checkpoint signature from the given outgoing bridge call
func (m *OutgoingBridgeCall) GetCheckpoint(gravityIDString string) ([]byte, error) {
// the contract argument is not a arbitrary length array but a fixed length 32 byte
// array, therefore we have to utf8 encode the string (the default in this case) and
// then copy the variable length encoded data into a fixed length array. This function
// will panic if gravityId is too long to fit in 32 bytes
gravityID, err := fxtypes.StrToByte32(gravityIDString)
if err != nil {
return nil, errorsmod.Wrap(err, "parse gravity id")
}
// Create the methodName argument which salts the signature
bridgeCallMethodName, err := fxtypes.StrToByte32("bridgeCall")
if err != nil {
return nil, err
}
dataBytes, err := hex.DecodeString(m.Data)
if err != nil {
return nil, errorsmod.Wrap(err, "parse data")
}
memoBytes, err := hex.DecodeString(m.Memo)
if err != nil {
return nil, errorsmod.Wrap(err, "parse memo")
}
contracts := make([]gethcommon.Address, 0, len(m.Tokens))
amounts := make([]*big.Int, 0, len(m.Tokens))
for _, token := range m.Tokens {
contracts = append(contracts, gethcommon.HexToAddress(token.Contract))
amounts = append(amounts, token.Amount.BigInt())
}
// the methodName needs to be the same as the 'name' above in the checkpointAbiJson
// but other than that it's a constant that has no impact on the output. This is because
// it gets encoded as a function name which we must then discard.
abiEncodedBatch, err := contract.GetFxBridgeABI().Pack("bridgeCallCheckpoint",
gravityID,
bridgeCallMethodName,
gethcommon.HexToAddress(m.Sender),
gethcommon.HexToAddress(m.Receiver),
contracts,
amounts,
gethcommon.HexToAddress(m.To),
dataBytes,
memoBytes,
big.NewInt(int64(m.Nonce)),
big.NewInt(int64(m.Timeout)),
big.NewInt(int64(m.EventNonce)),
)
// this should never happen outside of test since any case that could crash on encoding
// should be filtered above.
if err != nil {
return nil, errorsmod.Wrap(err, "packing checkpoint")
}
// we hash the resulting encoded bytes discarding the first 4 bytes these 4 bytes are the constant
// method name 'checkpoint'. If you where to replace the checkpoint constant in this code you would
// then need to adjust how many bytes you truncate off the front to get the output of abi.encode()
return crypto.Keccak256Hash(abiEncodedBatch[4:]).Bytes(), nil
}
func NewPendingOutgoingTx(txID uint64, sender sdk.AccAddress, receiver string, tokenContract string, amount, fee sdk.Coin, rewawrds sdk.Coins) PendingOutgoingTransferTx {
return PendingOutgoingTransferTx{
Id: txID,
Sender: sender.String(),
DestAddress: receiver,
TokenContract: tokenContract,
Token: amount,
Fee: fee,
Rewards: rewawrds,
}
}
func NewBridgeDenom(moduleName string, token string) string {
return fmt.Sprintf("%s%s", moduleName, token)
}
func NewERC20Tokens(module string, tokenAddrs []gethcommon.Address, tokenAmounts []*big.Int) ([]ERC20Token, error) {
if len(tokenAddrs) != len(tokenAmounts) {
return nil, fmt.Errorf("invalid length")
}
tokens := make([]ERC20Token, 0)
for i := 0; i < len(tokenAddrs); i++ {
contractAddr := ExternalAddrToStr(module, tokenAddrs[i].Bytes())
amount := sdkmath.NewIntFromBigInt(tokenAmounts[i])
found := false
for j := 0; j < len(tokens); j++ {
if contractAddr == tokens[j].Contract {
tokens[j].Amount = tokens[j].Amount.Add(amount)
found = true
break
}
}
if !found {
tokens = append(tokens, ERC20Token{
Contract: contractAddr,
Amount: amount,
})
}
}
return tokens, nil
}
func (m *MsgBridgeCallClaim) GetERC20Tokens() []ERC20Token {
erc20Tokens := make([]ERC20Token, 0, len(m.TokenContracts))
for i, tokenContract := range m.TokenContracts {
erc20Tokens = append(erc20Tokens, ERC20Token{
Contract: tokenContract,
Amount: m.Amounts[i],
})
}
return erc20Tokens
}