-
Notifications
You must be signed in to change notification settings - Fork 12
/
types.go
293 lines (251 loc) · 8.37 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
package types
import (
"encoding/binary"
"fmt"
math "math"
"math/big"
"sort"
"strconv"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/ethereum/go-ethereum/accounts/abi"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)
// UInt64FromBytes create uint from binary big endian representation
func UInt64FromBytes(s []byte) uint64 {
return binary.BigEndian.Uint64(s)
}
// UInt64Bytes uses the SDK byte marshaling to encode a uint64
func UInt64Bytes(n uint64) []byte {
return sdk.Uint64ToBigEndian(n)
}
// UInt64FromString to parse out a uint64 for a nonce
func UInt64FromString(s string) (uint64, error) {
return strconv.ParseUint(s, 10, 64)
}
//////////////////////////////////////
// BRIDGE VALIDATOR(S) //
//////////////////////////////////////
// ValidateBasic performs stateless checks on validity
func (m *BridgeValidator) ValidateBasic() error {
if m.Power == 0 {
return sdkerrors.Wrap(ErrEmpty, "power")
}
if err := ValidateExternalAddress(m.ExternalAddress); err != nil {
return sdkerrors.Wrap(err, "ethereum address")
}
if m.ExternalAddress == "" {
return sdkerrors.Wrap(ErrEmpty, "external address")
}
return nil
}
// BridgeValidators is the sorted set of validator data for Ethereum bridge MultiSig set
type BridgeValidators []*BridgeValidator
// Sort sorts the validators by power
func (b BridgeValidators) Sort() {
sort.Slice(b, func(i, j int) bool {
if b[i].Power == b[j].Power {
// Secondary sort on eth address in case powers are equal
return ExternalAddrLessThan(b[i].ExternalAddress, b[j].ExternalAddress)
}
return b[i].Power > b[j].Power
})
}
// 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 sdkerrors.Wrapf(err, "member %d", i)
}
}
if b.HasDuplicates() {
return sdkerrors.Wrap(ErrInvalid, "addresses")
}
return nil
}
//////////////////////////////////////
// OracleSet(S) //
//////////////////////////////////////
// NewOracleSet returns a new OracleSet
func NewOracleSet(nonce, height uint64, members BridgeValidators) *OracleSet {
members.Sort()
var mem []*BridgeValidator
for _, val := range members {
mem = append(mem, val)
}
return &OracleSet{
Nonce: nonce,
Members: mem,
Height: height,
}
}
// GetCheckpoint returns the checkpoint
func (m OracleSet) GetCheckpoint(gravityIDStr string) []byte {
// error case here should not occur outside of testing since the above is a constant
contractAbi, abiErr := abi.JSON(strings.NewReader(OracleSetCheckpointABIJSON))
if abiErr != nil {
panic("Bad ABI constant!")
}
// 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 := StrToFixByteArray(gravityIDStr)
if err != nil {
panic(err)
}
checkpointBytes := []uint8("checkpoint")
var checkpoint [32]uint8
copy(checkpoint[:], checkpointBytes[:])
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.
bytes, packErr := contractAbi.Pack("checkpoint", 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 {
panic(fmt.Sprintf("Error packing checkpoint! %s/n", packErr))
}
// 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(bytes[4:])
return hash.Bytes()
}
type OracleSets []*OracleSet
func (v OracleSets) Len() int {
return len(v)
}
func (v OracleSets) Less(i, j int) bool {
return v[i].Nonce > v[j].Nonce
}
func (v OracleSets) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
}
//////////////////////////////////////
// OutgoingTxBatch //
//////////////////////////////////////
type OutgoingTxBatches []*OutgoingTxBatch
func (v OutgoingTxBatches) Len() int {
return len(v)
}
func (v OutgoingTxBatches) Less(i, j int) bool {
return v[i].BatchNonce > v[j].BatchNonce
}
func (v OutgoingTxBatches) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
}
// GetFees returns the total fees contained within a given batch
func (m OutgoingTxBatch) GetFees() sdk.Int {
sum := sdk.ZeroInt()
for _, t := range m.Transactions {
sum.Add(t.Fee.Amount)
}
return sum
}
//////////////////////////////////////
// Oracle(S) //
//////////////////////////////////////
func (m Oracle) GetOracle() sdk.AccAddress {
if m.OracleAddress == "" {
return nil
}
addr, err := sdk.AccAddressFromBech32(m.OracleAddress)
if err != nil {
panic(err)
}
return addr
}
func (m Oracle) GetPower() sdk.Int {
return m.DepositAmount.Amount.Quo(sdk.PowerReduction)
}
type Oracles []Oracle
func (v Oracles) Len() int {
return len(v)
}
func (v Oracles) Less(i, j int) bool {
return v[i].DepositAmount.Amount.Sub(v[j].DepositAmount.Amount).IsPositive()
}
func (v Oracles) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
}
func MinBatchFeeToBaseFees(ms []MinBatchFee) map[string]sdk.Int {
kv := make(map[string]sdk.Int, len(ms))
for _, m := range ms {
if m.BaseFee.IsNil() || m.BaseFee.IsNegative() {
continue
}
kv[m.TokenContract] = m.BaseFee
}
return kv
}