reflector.go/wallet/transport.go

138 lines
2.5 KiB
Go
Raw Permalink Normal View History

2018-09-20 17:24:36 +02:00
package wallet
// copied from https://github.com/d4l3k/go-electrum
import (
"bufio"
"crypto/tls"
2020-07-01 19:23:44 +02:00
"encoding/json"
"fmt"
2018-09-20 17:24:36 +02:00
"net"
"time"
2020-09-01 20:15:34 +02:00
"github.com/lbryio/lbry.go/v2/extras/errors"
2019-11-14 01:11:35 +01:00
"github.com/lbryio/lbry.go/v2/extras/stop"
2020-03-30 21:57:53 +02:00
2018-09-20 17:24:36 +02:00
log "github.com/sirupsen/logrus"
)
type TCPTransport struct {
conn net.Conn
responses chan []byte
errors chan error
grp *stop.Group
}
func NewTransport(addr string, config *tls.Config) (*TCPTransport, error) {
var conn net.Conn
var err error
timeout := 5 * time.Second
if config != nil {
conn, err = tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", addr, config)
} else {
conn, err = net.DialTimeout("tcp", addr, timeout)
}
if err != nil {
return nil, err
}
t := &TCPTransport{
conn: conn,
responses: make(chan []byte),
errors: make(chan error),
grp: stop.New(),
}
t.grp.Add(1)
go func() {
defer t.grp.Done()
<-t.grp.Ch()
t.close()
}()
t.grp.Add(1)
go func() {
2020-07-01 19:23:44 +02:00
defer t.grp.Done()
2018-09-20 17:24:36 +02:00
t.listen()
}()
2020-07-01 19:23:44 +02:00
err = t.test()
if err != nil {
t.grp.StopAndWait()
return nil, errors.Prefix(addr, err)
}
2018-09-20 17:24:36 +02:00
return t, nil
}
const delimiter = byte('\n')
2020-07-01 19:23:44 +02:00
func (t *TCPTransport) Send(body []byte) error {
log.Debugf("%s <- %s", t.conn.RemoteAddr(), body)
_, err := t.conn.Write(body)
return err
}
func (t *TCPTransport) Responses() <-chan []byte { return t.responses }
func (t *TCPTransport) Errors() <-chan error { return t.errors }
func (t *TCPTransport) Shutdown() { t.grp.StopAndWait() }
2018-09-20 17:24:36 +02:00
func (t *TCPTransport) listen() {
reader := bufio.NewReader(t.conn)
for {
line, err := reader.ReadBytes(delimiter)
if err != nil {
t.error(err)
return
}
log.Debugf("%s -> %s", t.conn.RemoteAddr(), line)
t.responses <- line
}
}
func (t *TCPTransport) error(err error) {
select {
case t.errors <- err:
default:
}
}
2020-07-01 19:23:44 +02:00
func (t *TCPTransport) test() error {
err := t.Send([]byte(`{"id":1,"method":"server.version"}` + "\n"))
if err != nil {
return errors.Err(err)
}
2018-09-20 17:24:36 +02:00
2020-07-01 19:23:44 +02:00
var data []byte
select {
case data = <-t.Responses():
case <-time.Tick(1 * time.Second):
return errors.Err(ErrTimeout)
}
var response struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
err = json.Unmarshal(data, &response)
if err != nil {
return errors.Err(err)
}
if response.Error.Message != "" {
return fmt.Errorf(response.Error.Message)
}
return nil
2018-09-20 17:24:36 +02:00
}
func (t *TCPTransport) close() {
err := t.conn.Close()
if err != nil {
t.error(err)
}
}