status-go/server/client.go

109 lines
2.2 KiB
Go
Raw Normal View History

2022-05-03 14:50:40 +00:00
package server
import (
"bytes"
"crypto/ecdsa"
2022-05-03 14:50:40 +00:00
"crypto/tls"
"crypto/x509"
"encoding/pem"
2022-05-03 14:50:40 +00:00
"fmt"
"io/ioutil"
2022-05-03 14:50:40 +00:00
"net/http"
"net/url"
)
type PairingClient struct {
2022-05-03 14:50:40 +00:00
*http.Client
PayloadManager
2022-05-03 14:50:40 +00:00
baseAddress *url.URL
certPEM []byte
serverPK *ecdsa.PublicKey
serverMode Mode
serverCert *x509.Certificate
2022-05-03 14:50:40 +00:00
}
2022-07-01 15:37:53 +00:00
func NewPairingClient(c *ConnectionParams, config *PairingPayloadManagerConfig) (*PairingClient, error) {
u, err := c.URL()
2022-05-03 14:50:40 +00:00
if err != nil {
return nil, err
}
serverCert, err := getServerCert(u)
if err != nil {
return nil, err
}
err = verifyCert(serverCert, c.publicKey)
2022-05-03 14:50:40 +00:00
if err != nil {
return nil, err
}
certPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: serverCert.Raw})
2022-05-03 14:50:40 +00:00
rootCAs, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
2022-05-03 14:50:40 +00:00
if ok := rootCAs.AppendCertsFromPEM(certPem); !ok {
return nil, fmt.Errorf("failed to append certPem to rootCAs")
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: false, // MUST BE FALSE
RootCAs: rootCAs,
},
}
pm, err := NewPairingPayloadManager(c.aesKey, config)
if err != nil {
return nil, err
}
return &PairingClient{
2022-07-01 15:37:53 +00:00
Client: &http.Client{Transport: tr},
baseAddress: u,
certPEM: certPem,
serverCert: serverCert,
serverPK: c.publicKey,
2022-07-01 15:37:53 +00:00
serverMode: c.serverMode,
PayloadManager: pm,
2022-05-03 14:50:40 +00:00
}, nil
}
func (c *PairingClient) PairAccount() error {
switch c.serverMode {
case Receiving:
return c.sendAccountData()
case Sending:
return c.receiveAccountData()
default:
return fmt.Errorf("unrecognised server mode '%d'", c.serverMode)
}
}
func (c *PairingClient) sendAccountData() error {
c.baseAddress.Path = pairingReceive
2022-07-01 15:37:53 +00:00
_, err := c.Post(c.baseAddress.String(), "application/octet-stream", bytes.NewBuffer(c.PayloadManager.ToSend()))
if err != nil {
return err
}
return nil
}
func (c *PairingClient) receiveAccountData() error {
c.baseAddress.Path = pairingSend
resp, err := c.Get(c.baseAddress.String())
if err != nil {
return err
}
payload, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
2022-07-01 15:37:53 +00:00
return c.PayloadManager.Receive(payload)
}