forked from stellar/go
/
submitter.go
100 lines (85 loc) · 2.23 KB
/
submitter.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
package txsub
import (
"context"
"encoding/json"
"net/http"
"net/url"
"time"
"github.com/go-errors/errors"
)
const (
StatusError = "ERROR"
StatusPending = "PENDING"
StatusDuplicate = "DUPLICATE"
)
// NewDefaultSubmitter returns a new, simple Submitter implementation
// that submits directly to the stellar-core at `url` using the http client
// `h`.
func NewDefaultSubmitter(h *http.Client, url string) Submitter {
return &submitter{
http: h,
coreURL: url,
}
}
// coreSubmissionResponse is the json response from stellar-core's tx endpoint
type coreSubmissionResponse struct {
Exception string `json:"exception"`
Error string `json:"error"`
Status string `json:"status"`
}
// submitter is the default implementation for the Submitter interface. It
// submits directly to the configured stellar-core instance using the
// configured http client.
type submitter struct {
http *http.Client
coreURL string
}
// Submit sends the provided envelope to stellar-core and parses the response into
// a SubmissionResult
func (sub *submitter) Submit(ctx context.Context, env string) (result SubmissionResult) {
start := time.Now()
defer func() { result.Duration = time.Since(start) }()
// construct the request
u, err := url.Parse(sub.coreURL)
if err != nil {
result.Err = errors.Wrap(err, 1)
return
}
u.Path = "/tx"
q := u.Query()
q.Add("blob", env)
u.RawQuery = q.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
result.Err = errors.Wrap(err, 1)
return
}
// perform the submission
resp, err := sub.http.Do(req)
if err != nil {
result.Err = errors.Wrap(err, 1)
return
}
defer resp.Body.Close()
// parse response
var cresp coreSubmissionResponse
err = json.NewDecoder(resp.Body).Decode(&cresp)
if err != nil {
result.Err = errors.Wrap(err, 1)
return
}
// interpet response
if cresp.Exception != "" {
result.Err = errors.Errorf("stellar-core exception: %s", cresp.Exception)
return
}
switch cresp.Status {
case StatusError:
result.Err = &FailedTransactionError{cresp.Error}
case StatusPending, StatusDuplicate:
//noop. A nil Err indicates success
default:
result.Err = errors.Errorf("Unrecognized stellar-core status response: %s", cresp.Status)
}
return
}