forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
internal.go
198 lines (179 loc) · 4.95 KB
/
internal.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
package horizonclient
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/stellar/go/protocols/horizon"
"github.com/stellar/go/support/clock"
"github.com/stellar/go/support/errors"
)
// decodeResponse decodes the response from a request to a horizon server
func decodeResponse(resp *http.Response, object interface{}, horizonUrl string, clock *clock.Clock) (err error) {
defer resp.Body.Close()
if object == nil {
// Nothing to decode
return nil
}
decoder := json.NewDecoder(resp.Body)
u, err := url.Parse(horizonUrl)
if err != nil {
return errors.Errorf("unable to parse the provided horizon url: %s", horizonUrl)
}
setCurrentServerTime(u.Hostname(), resp.Header["Date"], clock)
if isStatusCodeAnError(resp.StatusCode) {
if isAsyncTxSubRequest(resp) {
return decodeAsyncTxSubResponse(resp, object)
}
horizonError := &Error{
Response: resp,
}
decodeError := decoder.Decode(&horizonError.Problem)
if decodeError != nil {
return errors.Wrap(decodeError, "error decoding horizon.Problem")
}
return horizonError
}
err = decoder.Decode(&object)
if err != nil {
return errors.Wrap(err, "error decoding response")
}
return
}
func isStatusCodeAnError(statusCode int) bool {
return !(statusCode >= 200 && statusCode < 300)
}
func isAsyncTxSubRequest(resp *http.Response) bool {
return resp.Request != nil && resp.Request.URL != nil && resp.Request.URL.Path == "/transactions_async"
}
func decodeAsyncTxSubResponse(resp *http.Response, object interface{}) error {
// We need to read the entire body in order to create 2 decoders later.
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "error reading response body")
}
// The first decoder converts the response to AsyncTransactionSubmissionResponse and checks
// the hash of the transaction. If the response was not a valid AsyncTransactionSubmissionResponse object,
// the hash of the converted object will be empty.
asyncRespDecoder := json.NewDecoder(bytes.NewReader(bodyBytes))
err = asyncRespDecoder.Decode(&object)
if asyncResp, ok := object.(*horizon.AsyncTransactionSubmissionResponse); err == nil && ok && asyncResp.Hash != "" {
return nil
}
// Create a new reader for the second decoding. The second decoder decodes to Horizon.Problem object.
problemDecoder := json.NewDecoder(bytes.NewReader(bodyBytes))
horizonError := Error{
Response: resp,
}
err = problemDecoder.Decode(&horizonError.Problem)
if err != nil {
return errors.Wrap(err, "error decoding horizon error")
}
return horizonError
}
// countParams counts the number of parameters provided
func countParams(params ...interface{}) int {
counter := 0
for _, param := range params {
switch param := param.(type) {
case string:
if param != "" {
counter++
}
case int:
if param > 0 {
counter++
}
case uint:
if param > 0 {
counter++
}
case bool:
counter++
default:
panic("Unknown parameter type")
}
}
return counter
}
// addQueryParams sets query parameters for a url
func addQueryParams(params ...interface{}) string {
query := url.Values{}
for _, param := range params {
switch param := param.(type) {
case cursor:
if param != "" {
query.Add("cursor", string(param))
}
case Order:
if param != "" {
query.Add("order", string(param))
}
case limit:
if param != 0 {
query.Add("limit", strconv.Itoa(int(param)))
}
case assetCode:
if param != "" {
query.Add("asset_code", string(param))
}
case assetIssuer:
if param != "" {
query.Add("asset_issuer", string(param))
}
case includeFailed:
if param {
query.Add("include_failed", "true")
}
case join:
if param != "" {
query.Add("join", string(param))
}
case reserves:
if len(param) > 0 {
query.Add("reserves", strings.Join(param, ","))
}
case map[string]string:
for key, value := range param {
if value != "" {
query.Add(key, value)
}
}
default:
panic("Unknown parameter type")
}
}
return query.Encode()
}
// setCurrentServerTime saves the current time returned by a horizon server
func setCurrentServerTime(host string, serverDate []string, clock *clock.Clock) {
if len(serverDate) == 0 {
return
}
st, err := time.Parse(time.RFC1123, serverDate[0])
if err != nil {
return
}
serverTimeMapMutex.Lock()
ServerTimeMap[host] = ServerTimeRecord{ServerTime: st.UTC().Unix(), LocalTimeRecorded: clock.Now().UTC().Unix()}
serverTimeMapMutex.Unlock()
}
// currentServerTime returns the current server time for a given horizon server
func currentServerTime(host string, currentTimeUTC int64) int64 {
serverTimeMapMutex.Lock()
st, has := ServerTimeMap[host]
serverTimeMapMutex.Unlock()
if !has {
return 0
}
// if it has been more than 5 minutes from the last time, then return 0 because the saved
// server time is behind.
if currentTimeUTC-st.LocalTimeRecorded > 60*5 {
return 0
}
return currentTimeUTC - st.LocalTimeRecorded + st.ServerTime
}