forked from stellar/go
/
helpers.go
421 lines (330 loc) · 9.68 KB
/
helpers.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
package actions
import (
"mime"
"net/url"
"strconv"
"fmt"
"github.com/go-chi/chi"
"github.com/stellar/go/amount"
"github.com/stellar/go/services/horizon/internal/assets"
"github.com/stellar/go/services/horizon/internal/db2"
"github.com/stellar/go/services/horizon/internal/ledger"
hProblem "github.com/stellar/go/services/horizon/internal/render/problem"
"github.com/stellar/go/services/horizon/internal/toid"
"github.com/stellar/go/strkey"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/support/render/problem"
"github.com/stellar/go/support/time"
"github.com/stellar/go/xdr"
)
const (
// ParamCursor is a query string param name
ParamCursor = "cursor"
// ParamOrder is a query string param name
ParamOrder = "order"
// ParamLimit is a query string param name
ParamLimit = "limit"
)
// GetCursor retrieves a string from either the URLParams, form or query string.
// This method uses the priority (URLParams, Form, Query).
func (base *Base) GetCursor(name string) string {
if base.Err != nil {
return ""
}
cursor := base.GetString(name)
if cursor == "now" {
tid := toid.AfterLedger(ledger.CurrentState().HistoryLatest)
cursor = tid.String()
}
if lei := base.R.Header.Get("Last-Event-ID"); lei != "" {
cursor = lei
}
// In case cursor is negative value, return InvalidField error
cursorInt, err := strconv.Atoi(cursor)
if err == nil && cursorInt < 0 {
msg := fmt.Sprintf("the cursor %d is a negative number: ", cursorInt)
base.SetInvalidField("cursor", errors.New(msg))
}
return cursor
}
// GetString retrieves a string from either the URLParams, form or query string.
// This method uses the priority (URLParams, Form, Query).
func (base *Base) GetString(name string) string {
if base.Err != nil {
return ""
}
fromURL, ok := base.GetURLParam(name)
if ok {
ret, err := url.PathUnescape(fromURL)
if err != nil {
base.SetInvalidField(name, err)
return ""
}
return ret
}
fromForm := base.R.FormValue(name)
if fromForm != "" {
return fromForm
}
return base.R.URL.Query().Get(name)
}
// GetInt64 retrieves an int64 from the action parameter of the given name.
// Populates err if the value is not a valid int64
func (base *Base) GetInt64(name string) int64 {
if base.Err != nil {
return 0
}
asStr := base.GetString(name)
if asStr == "" {
return 0
}
asI64, err := strconv.ParseInt(asStr, 10, 64)
if err != nil {
base.SetInvalidField(name, err)
return 0
}
return asI64
}
// GetInt32 retrieves an int32 from the action parameter of the given name.
// Populates err if the value is not a valid int32
func (base *Base) GetInt32(name string) int32 {
if base.Err != nil {
return 0
}
asStr := base.GetString(name)
if asStr == "" {
return 0
}
asI64, err := strconv.ParseInt(asStr, 10, 32)
if err != nil {
base.SetInvalidField(name, err)
return 0
}
return int32(asI64)
}
// GetLimit retrieves a uint64 limit from the action parameter of the given
// name. Populates err if the value is not a valid limit. Uses the provided
// default value if the limit parameter is a blank string.
func (base *Base) GetLimit(name string, def uint64, max uint64) uint64 {
if base.Err != nil {
return 0
}
limit := base.GetString(name)
if limit == "" {
return def
}
asI64, err := strconv.ParseInt(limit, 10, 64)
if asI64 <= 0 {
err = errors.New("invalid limit: non-positive value provided")
}
if asI64 > int64(max) {
err = errors.Errorf("invalid limit: value provided that is over limit max of %d", max)
}
if err != nil {
base.SetInvalidField(name, err)
return 0
}
return uint64(asI64)
}
// GetPageQuery is a helper that returns a new db.PageQuery struct initialized
// using the results from a call to GetPagingParams()
func (base *Base) GetPageQuery() db2.PageQuery {
if base.Err != nil {
return db2.PageQuery{}
}
cursor := base.GetCursor(ParamCursor)
order := base.GetString(ParamOrder)
limit := base.GetLimit(ParamLimit, db2.DefaultPageSize, db2.MaxPageSize)
if base.Err != nil {
return db2.PageQuery{}
}
r, err := db2.NewPageQuery(cursor, order, limit)
if err != nil {
base.Err = err
}
return r
}
// GetAddress retrieves a stellar address. It confirms the value loaded is a
// valid stellar address, setting an invalid field error if it is not.
func (base *Base) GetAddress(name string) (result string) {
if base.Err != nil {
return
}
result = base.GetString(name)
_, err := strkey.Decode(strkey.VersionByteAccountID, result)
if err != nil {
base.SetInvalidField(name, err)
}
return result
}
// GetAccountID retireves an xdr.AccountID by attempting to decode a stellar
// address at the provided name.
func (base *Base) GetAccountID(name string) (result xdr.AccountId) {
raw, err := strkey.Decode(strkey.VersionByteAccountID, base.GetString(name))
if base.Err != nil {
return
}
if err != nil {
base.SetInvalidField(name, err)
return
}
var key xdr.Uint256
copy(key[:], raw)
result, err = xdr.NewAccountId(xdr.PublicKeyTypePublicKeyTypeEd25519, key)
if err != nil {
base.SetInvalidField(name, err)
return
}
return
}
// GetAmount returns a native amount (i.e. 64-bit integer) by parsing
// the string at the provided name in accordance with the stellar client
// conventions
func (base *Base) GetAmount(name string) (result xdr.Int64) {
var err error
result, err = amount.Parse(base.GetString(name))
if err != nil {
base.SetInvalidField(name, err)
return
}
return
}
// GetPositiveAmount returns a native amount (i.e. 64-bit integer) by parsing
// the string at the provided name in accordance with the stellar client
// conventions. Renders error for negative amounts and zero.
func (base *Base) GetPositiveAmount(name string) (result xdr.Int64) {
result = base.GetAmount(name)
if base.Err != nil {
return
}
if result <= 0 {
base.SetInvalidField(name, errors.New("Value must be positive"))
return xdr.Int64(0)
}
return
}
// GetAssetType is a helper that returns a xdr.AssetType by reading a string
func (base *Base) GetAssetType(name string) xdr.AssetType {
if base.Err != nil {
return xdr.AssetTypeAssetTypeNative
}
r, err := assets.Parse(base.GetString(name))
if base.Err != nil {
return xdr.AssetTypeAssetTypeNative
}
if err != nil {
base.SetInvalidField(name, err)
}
return r
}
// GetAsset decodes an asset from the request fields prefixed by `prefix`. To
// succeed, three prefixed fields must be present: asset_type, asset_code, and
// asset_issuer.
func (base *Base) GetAsset(prefix string) (result xdr.Asset) {
if base.Err != nil {
return
}
var value interface{}
t := base.GetAssetType(prefix + "asset_type")
switch t {
case xdr.AssetTypeAssetTypeCreditAlphanum4:
a := xdr.AssetAlphaNum4{}
a.Issuer = base.GetAccountID(prefix + "asset_issuer")
c := base.GetString(prefix + "asset_code")
if len(c) > len(a.AssetCode) {
base.SetInvalidField(prefix+"asset_code", errors.New("code too long"))
return
}
copy(a.AssetCode[:len(c)], []byte(c))
value = a
case xdr.AssetTypeAssetTypeCreditAlphanum12:
a := xdr.AssetAlphaNum12{}
a.Issuer = base.GetAccountID(prefix + "asset_issuer")
c := base.GetString(prefix + "asset_code")
if len(c) > len(a.AssetCode) {
base.SetInvalidField(prefix+"asset_code", errors.New("code too long"))
return
}
copy(a.AssetCode[:len(c)], []byte(c))
value = a
}
result, err := xdr.NewAsset(t, value)
if err != nil {
panic(err)
}
return
}
// MaybeGetAsset decodes an asset from the request fields as GetAsset does, but
// only if type field is populated. returns an additional boolean reflecting whether
// or not the decoding was performed
func (base *Base) MaybeGetAsset(prefix string) (xdr.Asset, bool) {
if base.Err != nil {
return xdr.Asset{}, false
}
if base.GetString(prefix+"asset_type") == "" {
return xdr.Asset{}, false
}
return base.GetAsset(prefix), true
}
// GetTimeMillis retrieves a TimeMillis from the action parameter of the given name.
// Populates err if the value is not a valid TimeMillis
func (base *Base) GetTimeMillis(name string) (timeMillis time.Millis) {
if base.Err != nil {
return
}
asStr := base.GetString(name)
if asStr == "" {
return
}
timeMillis, err := time.MillisFromString(asStr)
if err != nil {
base.SetInvalidField(name, err)
return
}
return
}
// GetURLParam returns the corresponding URL parameter value from the request
// routing context and an additional boolean reflecting whether or not the
// param was found. This is ported from Chi since the Chi version returns ""
// for params not found. This is undesirable since "" also is a valid url param.
// Ref: https://github.com/go-chi/chi/blob/d132b31857e5922a2cc7963f4fcfd8f46b3f2e97/context.go#L69
func (base *Base) GetURLParam(key string) (string, bool) {
rctx := chi.RouteContext(base.R.Context())
for k := len(rctx.URLParams.Keys) - 1; k >= 0; k-- {
if rctx.URLParams.Keys[k] == key {
return rctx.URLParams.Values[k], true
}
}
return "", false
}
// SetInvalidField establishes an error response triggered by an invalid
// input field from the user.
func (base *Base) SetInvalidField(name string, reason error) {
base.Err = problem.MakeInvalidFieldProblem(name, reason)
}
// Path returns the current action's path, as determined by the http.Request of
// this action
func (base *Base) Path() string {
return base.R.URL.Path
}
// ValidateBodyType sets an error on the action if the requests Content-Type
// is not `application/x-www-form-urlencoded`
func (base *Base) ValidateBodyType() {
c := base.R.Header.Get("Content-Type")
if c == "" {
return
}
mt, _, err := mime.ParseMediaType(c)
if err != nil {
base.Err = err
return
}
switch {
case mt == "application/x-www-form-urlencoded":
return
case mt == "multipart/form-data":
return
default:
base.Err = &hProblem.UnsupportedMediaType
}
}