forked from gcash/bchwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
paymentprotocol.go
290 lines (256 loc) · 8.29 KB
/
paymentprotocol.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
package pymtproto
import (
"bytes"
"crypto/x509"
"errors"
"fmt"
"github.com/gcash/bchd/chaincfg"
"github.com/gcash/bchd/txscript"
"github.com/gcash/bchd/wire"
"github.com/gcash/bchutil"
"github.com/gcash/bchwallet/pymtproto/payments"
"github.com/golang/protobuf/proto"
"golang.org/x/net/proxy"
"io/ioutil"
"net"
"net/http"
"net/url"
"time"
)
// PaymentRequest is returned by the DownloadBip0070PaymentRequest method. It
// contains all the relevant information from the downloaded payment request.
type PaymentRequest struct {
PayToName string
Outputs []Output
Expires time.Time
Memo string
PaymentURL string
MerchantData []byte
}
// Output represents an address and amount to be paid.
type Output struct {
Address bchutil.Address
Amount bchutil.Amount
}
// PaymentProtocolClient is used to download payment requests and make payments.
// We use an object for this to make testing a little easier.
type PaymentProtocolClient struct {
httpClient *http.Client
params *chaincfg.Params
proxyDialer proxy.Dialer
skipExpirationChecks bool
}
// NewPaymentProtocolClient returns a PaymentRequestDownloader that can be used to get the payment request.
func NewPaymentProtocolClient(params *chaincfg.Params, proxyDialer proxy.Dialer) *PaymentProtocolClient {
// Use proxy on http connection if one is provided
dial := net.Dial
if proxyDialer != nil {
dial = proxyDialer.Dial
}
tbTransport := &http.Transport{Dial: dial}
client := &http.Client{Transport: tbTransport, Timeout: time.Minute}
return &PaymentProtocolClient{
httpClient: client,
params: params,
proxyDialer: proxyDialer,
}
}
// DownloadBip0070PaymentRequest will download a Bip70 (protobuf) payment request from
// the provided bitcoincash URI. Upon download it will validate the request is formatted
// correctly and signed with a valid X509 certificate. The cert will be checked against
// the OS's certificate store. A PaymentRequest object with the relevant data extracted
// is returned.
func (c *PaymentProtocolClient) DownloadBip0070PaymentRequest(uri string) (*PaymentRequest, error) {
// Extract the `r` parameter from the URI
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
endpoint := u.Query().Get("r")
if endpoint == "" {
return nil, errors.New("invalid bitcoin cash URI")
}
// Build GET request
request, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
request.Header.Add("Accept", "application/bitcoincash-paymentrequest")
// Make the request
resp, err := c.httpClient.Do(request)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http status not OK: %d", resp.StatusCode)
}
// Unmarshal payment request
paymentRequestBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
paymentRequest := new(payments.PaymentRequest)
if err = proto.Unmarshal(paymentRequestBytes, paymentRequest); err != nil {
return nil, err
}
// We're only accepting `x509+sha256` certs. The alternatives are `none` which is insecure
// and `x509+sha1` which is also insecure. So `x509+sha256` it is.
switch paymentRequest.GetPkiType() {
case "x509+sha256":
break
case "x509+sha1":
return nil, errors.New("payment request PkiType x509+sha1 is insecure")
default:
return nil, errors.New("payment request PkiType unknown")
}
// Unmarshal the certificate object
certificateProto := new(payments.X509Certificates)
if err := proto.Unmarshal(paymentRequest.PkiData, certificateProto); err != nil {
return nil, err
}
// Parse the certificates
var certs []*x509.Certificate
for _, certBytes := range certificateProto.Certificate {
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, err
}
certs = append(certs, cert)
}
if len(certs) < 2 {
return nil, errors.New("invalid number of certs")
}
// If the certificate is expired or not valid yet we return and error
if !c.skipExpirationChecks {
if time.Now().After(certs[0].NotAfter) {
return nil, errors.New("certificate is expired")
}
}
if time.Now().Before(certs[0].NotBefore) {
return nil, errors.New("certificate is not valid yet")
}
// Now make sure the cert is signed by a valid certificate authority
roots := x509.NewCertPool()
roots.AddCert(certs[1])
opts := x509.VerifyOptions{
Roots: roots,
}
if _, err := certs[0].Verify(opts); err != nil {
return nil, err
}
// Verify the signature on the PaymentRequest object
signature := paymentRequest.Signature
paymentRequest.Signature = []byte{} // Zero out the signature for verification
serializedPaymentRequest, err := proto.Marshal(paymentRequest)
if err != nil {
return nil, err
}
if err := certs[0].CheckSignature(certs[0].SignatureAlgorithm, serializedPaymentRequest, signature); err != nil {
return nil, err
}
// Parse the payment details and build the response
paymentDetails := new(payments.PaymentDetails)
if err := proto.Unmarshal(paymentRequest.SerializedPaymentDetails, paymentDetails); err != nil {
return nil, err
}
pr := &PaymentRequest{
PayToName: certs[0].Subject.CommonName,
}
for _, out := range paymentDetails.Outputs {
// We're going to return an error here if they ask us to pay an unparsable
// address. This is kind of lame as we should be able to pay any script but
// our gRPC API currently only works with addresses for convenience so we wont
// be able to pay arbitrary scripts right now anyway.
_, addrs, _, err := txscript.ExtractPkScriptAddrs(out.Script, c.params)
if err != nil {
return nil, err
}
if out.Amount == nil {
return nil, errors.New("nil payment amount")
}
output := Output{
Address: addrs[0],
Amount: bchutil.Amount(int64(*out.Amount)),
}
pr.Outputs = append(pr.Outputs, output)
}
pr.Expires = time.Unix(int64(paymentDetails.GetExpires()), 0)
if !c.skipExpirationChecks {
if pr.Expires.Before(time.Now()) {
return nil, errors.New("payment request is expired")
}
}
pr.Memo = paymentDetails.GetMemo()
pr.PaymentURL = paymentDetails.GetPaymentUrl()
pr.MerchantData = paymentDetails.GetMerchantData()
return pr, nil
}
// Payment is an object that holds all information needed to POST a payment back
// to the merchant server. All fields except memo are required.
type Payment struct {
PaymentURL string
MerchantData []byte
Transactions []*wire.MsgTx
RefundOutput Output
Memo string
}
// PostPayment sends a payment response back to the merchant's server. Any errors
// that are encountered in the process are returned along with an optional "memo"
// that the merchant can include in the ACK.
func (c *PaymentProtocolClient) PostPayment(payment *Payment) (memo string, err error) {
// Build the payment protobuf object
var transactions [][]byte
for _, tx := range payment.Transactions {
var buf bytes.Buffer
if err := tx.BchEncode(&buf, 0, wire.BaseEncoding); err != nil {
return "", err
}
transactions = append(transactions, buf.Bytes())
}
refundScript, err := txscript.PayToAddrScript(payment.RefundOutput.Address)
if err != nil {
return "", err
}
refundAmount := uint64(payment.RefundOutput.Amount.ToUnit(bchutil.AmountSatoshi))
paymentProto := &payments.Payment{
MerchantData: payment.MerchantData,
Memo: &payment.Memo,
Transactions: transactions,
}
paymentProto.RefundTo = append(paymentProto.RefundTo, &payments.Output{
Script: refundScript,
Amount: &refundAmount,
})
// Marshal the protobuf
serializedPayment, err := proto.Marshal(paymentProto)
if err != nil {
return "", err
}
// Build the POST request
request, err := http.NewRequest(http.MethodPost, payment.PaymentURL, bytes.NewReader(serializedPayment))
if err != nil {
return "", err
}
request.Header.Add("Content-Type", "application/bitcoincash-payment")
request.Header.Add("Accept", "application/bitcoincash-paymentack")
// Make the request
resp, err := c.httpClient.Do(request)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("http status not OK: %d", resp.StatusCode)
}
serializedPaymentAck, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
paymentAck := new(payments.PaymentACK)
if err := proto.Unmarshal(serializedPaymentAck, paymentAck); err != nil {
return "", err
}
if paymentAck.Memo != nil {
memo = *paymentAck.Memo
}
return memo, nil
}