-
Notifications
You must be signed in to change notification settings - Fork 135
/
utils.go
347 lines (297 loc) · 7.52 KB
/
utils.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
// Copyright 2024 Coinbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log"
"math/big"
"github.com/mitchellh/mapstructure"
)
// ConstructPartialBlockIdentifier constructs a *PartialBlockIdentifier
// from a *BlockIdentifier.
//
// It is useful to have this helper when making block requests
// with the fetcher.
func ConstructPartialBlockIdentifier(
blockIdentifier *BlockIdentifier,
) *PartialBlockIdentifier {
return &PartialBlockIdentifier{
Hash: &blockIdentifier.Hash,
Index: &blockIdentifier.Index,
}
}
// hashBytes returns a hex-encoded sha256 hash of the provided
// byte slice.
func hashBytes(data []byte) string {
h := sha256.New()
_, err := h.Write(data)
if err != nil {
log.Fatal(fmt.Errorf("unable to hash data %s: %w", string(data), err))
}
return fmt.Sprintf("%x", h.Sum(nil))
}
// Hash returns a deterministic hash for any interface.
// This works because Golang's JSON marshaler sorts all map keys, recursively.
// Source: https://golang.org/pkg/encoding/json/#Marshal
// Inspiration:
// https://github.com/onsi/gomega/blob/c0be49994280db30b6b68390f67126d773bc5558/matchers/match_json_matcher.go#L16
//
// It is important to note that any interface that is a slice
// or contains slices will not be equal if the slice ordering is
// different.
func Hash(i interface{}) string {
// Convert interface to JSON object (not necessarily ordered if struct
// contains json.RawMessage)
a, err := json.Marshal(i)
if err != nil {
log.Fatal(fmt.Errorf("unable to marshal %+v: %w", i, err))
}
// Convert JSON object to interface (all json.RawMessage converted to go types)
var b interface{}
if err := json.Unmarshal(a, &b); err != nil {
log.Fatal(fmt.Errorf("unable to unmarshal %+v: %w", a, err))
}
// Convert interface to JSON object (all map keys ordered)
c, err := json.Marshal(b)
if err != nil {
log.Fatal(fmt.Errorf("unable to marshal %+v: %w", b, err))
}
return hashBytes(c)
}
// BigInt returns a *big.Int representation of a value.
func BigInt(value string) (*big.Int, error) {
parsedVal, ok := new(big.Int).SetString(value, 10)
if !ok {
return nil, fmt.Errorf("%s is not an integer", value)
}
return parsedVal, nil
}
// AmountValue returns a *big.Int representation of an
// Amount.Value or an error.
func AmountValue(amount *Amount) (*big.Int, error) {
if amount == nil {
return nil, errors.New("amount value cannot be nil")
}
return BigInt(amount.Value)
}
// AddValues adds string amounts using
// big.Int.
func AddValues(
a string,
b string,
) (string, error) {
aVal, err := BigInt(a)
if err != nil {
return "", err
}
bVal, err := BigInt(b)
if err != nil {
return "", err
}
newVal := new(big.Int).Add(aVal, bVal)
return newVal.String(), nil
}
// SubtractValues subtracts a-b using
// big.Int.
func SubtractValues(
a string,
b string,
) (string, error) {
aVal, err := BigInt(a)
if err != nil {
return "", err
}
bVal, err := BigInt(b)
if err != nil {
return "", err
}
newVal := new(big.Int).Sub(aVal, bVal)
return newVal.String(), nil
}
// MultiplyValues multiplies a*b using
// big.Int.
func MultiplyValues(
a string,
b string,
) (string, error) {
aVal, err := BigInt(a)
if err != nil {
return "", err
}
bVal, err := BigInt(b)
if err != nil {
return "", err
}
newVal := new(big.Int).Mul(aVal, bVal)
return newVal.String(), nil
}
// DivideValues divides a/b using
// big.Int.
func DivideValues(
a string,
b string,
) (string, error) {
aVal, err := BigInt(a)
if err != nil {
return "", err
}
bVal, err := BigInt(b)
if err != nil {
return "", err
}
newVal := new(big.Int).Div(aVal, bVal)
return newVal.String(), nil
}
// NegateValue flips the sign of a value.
func NegateValue(
val string,
) (string, error) {
existing, err := BigInt(val)
if err != nil {
return "", err
}
return new(big.Int).Neg(existing).String(), nil
}
// AccountString returns a human-readable representation of a
// *AccountIdentifier.
func AccountString(account *AccountIdentifier) string {
if account.SubAccount == nil {
return account.Address
}
if account.SubAccount.Metadata == nil {
return fmt.Sprintf(
"%s:%s",
account.Address,
account.SubAccount.Address,
)
}
return fmt.Sprintf(
"%s:%s:%+v",
account.Address,
account.SubAccount.Address,
account.SubAccount.Metadata,
)
}
// CurrencyString returns a human-readable representation
// of a *Currency.
func CurrencyString(currency *Currency) string {
if currency.Metadata == nil {
return fmt.Sprintf("%s:%d", currency.Symbol, currency.Decimals)
}
return fmt.Sprintf(
"%s:%d:%+v",
currency.Symbol,
currency.Decimals,
currency.Metadata,
)
}
// PrettyPrintStruct marshals a struct to JSON and returns
// it as a string.
func PrettyPrintStruct(val interface{}) string {
prettyStruct, err := json.MarshalIndent(
val,
"",
" ",
)
if err != nil {
log.Fatal(err)
}
return string(prettyStruct)
}
// PrintStruct marshals a struct to JSON and returns
// it as a string without newlines.
func PrintStruct(val interface{}) string {
str, err := json.Marshal(
val,
)
if err != nil {
log.Fatal(err)
}
return string(str)
}
// MarshalMap attempts to marshal an interface into a map[string]interface{}.
// This function is used similarly to json.Marshal.
func MarshalMap(input interface{}) (map[string]interface{}, error) {
if input == nil {
return nil, nil
}
// Only create output if input is not nil, otherwise we will
// return a map for a nil input.
output := map[string]interface{}{}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: "json",
Result: &output,
})
if err != nil {
return nil, err
}
if err := decoder.Decode(input); err != nil {
return nil, err
}
return output, nil
}
// UnmarshalMap attempts to unmarshal a map[string]interface{} into an
// interface. This function is used similarly to json.Unmarshal.
func UnmarshalMap(metadata map[string]interface{}, output interface{}) error {
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: "json",
Result: output,
})
if err != nil {
return err
}
return decoder.Decode(metadata)
}
// ExtractAmount returns the Amount from a slice of Balance
// pertaining to an AccountAndCurrency.
func ExtractAmount(
balances []*Amount,
currency *Currency,
) *Amount {
for _, b := range balances {
if Hash(b.Currency) != Hash(currency) {
continue
}
return b
}
// return a 0 amount if currency isn't found in balances
return &Amount{Value: "0", Currency: currency}
}
// String returns a pointer to the
// string passed as an argument.
func String(s string) *string {
return &s
}
// Int64 returns a pointer to the
// int64 passed as an argument.
func Int64(i int64) *int64 {
return &i
}
// Bool returns a pointer to the
// bool passed as an argument.
func Bool(b bool) *bool {
return &b
}
// OperatorP returns a pointer to the
// Operator passed as an argument.
//
// We can't just use Operator because
// the types package already declares
// the Operator type.
func OperatorP(o Operator) *Operator {
return &o
}