-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
248 lines (216 loc) · 7.28 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
package types
import (
"encoding/binary"
"fmt"
math "math"
"math/big"
"sort"
"strconv"
"strings"
sdk "github.com/ci123chain/ci123chain/pkg/abci/types"
sdkerrors "github.com/ci123chain/ci123chain/pkg/abci/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 (b *BridgeValidator) ValidateBasic() error {
if b.Power == 0 {
return sdkerrors.Wrap(ErrEmpty, "power")
}
if err := ValidateEthAddress(b.EthereumAddress); err != nil {
return sdkerrors.Wrap(err, "ethereum address")
}
if b.EthereumAddress == "" {
return sdkerrors.Wrap(ErrEmpty, "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 EthAddrGreaterThan(b[i].EthereumAddress, b[j].EthereumAddress)
}
return b[i].Power > b[j].Power
})
}
// PowerDiff returns the difference in power between two bridge validator sets
// TODO: this needs to be potentially refactored
func (b BridgeValidators) PowerDiff(c BridgeValidators) float64 {
powers := map[string]int64{}
var totalB int64
// loop over b and initialize the map with their powers
for _, bv := range b {
powers[bv.EthereumAddress] = int64(bv.Power)
totalB += 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.EthereumAddress]; ok {
powers[bv.EthereumAddress] = val - int64(bv.Power)
} else {
powers[bv.EthereumAddress] = -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(totalB))
}
// 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].EthereumAddress] = 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 {
// TODO: check if the set is sorted here?
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(ErrDuplicate, "addresses")
}
return nil
}
// NewValset returns a new valset
func NewValset(nonce, height uint64, members BridgeValidators) *Valset {
members.Sort()
var mem []*BridgeValidator
for _, val := range members {
mem = append(mem, val)
}
return &Valset{Nonce: uint64(nonce), Members: mem, Height: height}
}
// GetCheckpoint returns the checkpoint
func (v Valset) GetCheckpoint(gravityIDstring string) []byte {
// TODO replace hardcoded "foo" here with a getter to retrieve the correct gravityID from the store
// this will work for now because 'foo' is the test gravityID we are using
// var gravityIDString = "foo"
// error case here should not occur outside of testing since the above is a constant
contractAbi, abiErr := abi.JSON(strings.NewReader(ValsetCheckpointABIJSON))
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(gravityIDstring)
if err != nil {
panic(err)
}
checkpointBytes := []uint8("checkpoint")
var checkpoint [32]uint8
copy(checkpoint[:], checkpointBytes[:])
memberAddresses := make([]gethcommon.Address, len(v.Members))
convertedPowers := make([]*big.Int, len(v.Members))
for i, m := range v.Members {
memberAddresses[i] = gethcommon.HexToAddress(m.EthereumAddress)
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(v.Nonce)), memberAddresses, convertedPowers)
//fmt.Println("----------------")
//fmt.Println(gravityIDstring)
//fmt.Println(gravityID)
//fmt.Println(checkpoint)
//fmt.Println(v.Nonce)
//fmt.Println(memberAddresses)
//fmt.Println(convertedPowers)
//fmt.Println("----------------")
//fmt.Println(bytes)
//fmt.Println(string(bytes))
//fmt.Println(bytes[4:])
//fmt.Println(string(bytes[4:]))
//fmt.Println("----------------")
// 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()
}
// WithoutEmptyMembers returns a new Valset without member that have 0 power or an empty Ethereum address.
func (v *Valset) WithoutEmptyMembers() *Valset {
if v == nil {
return nil
}
r := Valset{Nonce: v.Nonce, Members: make([]*BridgeValidator, 0, len(v.Members))}
for i := range v.Members {
if err := v.Members[i].ValidateBasic(); err == nil {
r.Members = append(r.Members, v.Members[i])
}
}
return &r
}
// Valsets is a collection of valset
type Valsets []*Valset
func (v Valsets) Len() int {
return len(v)
}
func (v Valsets) Less(i, j int) bool {
return v[i].Nonce > v[j].Nonce
}
func (v Valsets) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
}
// GetFees returns the total fees contained within a given batch
func (b OutgoingTxBatch) GetFees() sdk.Int {
sum := sdk.ZeroInt()
for _, t := range b.Transactions {
sum.Add(t.Erc20Fee.Amount)
}
return sum
}