vls_proxy/
client.rs

1use std::os::unix::io::RawFd;
2
3use bitcoin::consensus::Encodable;
4use lightning_signer::bitcoin;
5use nix::sys::socket::{socketpair, AddressFamily, SockFlag, SockType};
6
7use serde_bolt::{io::Read, ReadBigEndian};
8use vls_protocol::serde_bolt;
9use vls_protocol::{msgs, Error, Result};
10use vls_protocol_signer::vls_protocol;
11
12use crate::connection::UnixConnection;
13
14pub trait Client: Send {
15    fn write<M: msgs::DeBolt + Encodable>(&mut self, msg: M) -> Result<()>;
16    fn write_vec(&mut self, v: Vec<u8>) -> Result<()>;
17    fn read(&mut self) -> Result<msgs::Message>;
18    fn read_raw(&mut self) -> Result<Vec<u8>>;
19    fn id(&self) -> u64;
20    #[must_use = "don't leak the client fd"]
21    fn new_client(&mut self) -> Self;
22}
23
24pub struct UnixClient {
25    conn: UnixConnection,
26}
27
28impl UnixClient {
29    pub fn new(conn: UnixConnection) -> Self {
30        Self { conn }
31    }
32
33    pub fn recv_fd(&mut self) -> core::result::Result<RawFd, ()> {
34        self.conn.recv_fd()
35    }
36}
37
38impl Client for UnixClient {
39    fn write<M: msgs::DeBolt + Encodable>(&mut self, msg: M) -> Result<()> {
40        msgs::write(&mut self.conn, msg)?;
41        Ok(())
42    }
43
44    fn write_vec(&mut self, v: Vec<u8>) -> Result<()> {
45        msgs::write_vec(&mut self.conn, v)?;
46        Ok(())
47    }
48
49    fn read(&mut self) -> Result<msgs::Message> {
50        msgs::read(&mut self.conn)
51    }
52
53    fn read_raw(&mut self) -> Result<Vec<u8>> {
54        // map to IO error, otherwise we get a Bitcoin error because of where read_u32_be is defined
55        let len = self.conn.read_u32_be().map_err(|e| Error::Io(e.to_string()))?;
56        let mut data = Vec::new();
57        data.resize(len as usize, 0);
58        let len = self.conn.read(&mut data)?;
59        if len < data.len() {
60            return Err(Error::ShortRead);
61        }
62        Ok(data)
63    }
64
65    fn id(&self) -> u64 {
66        self.conn.id()
67    }
68
69    fn new_client(&mut self) -> UnixClient {
70        let (fd_a, fd_b) =
71            socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()).unwrap();
72        self.conn.send_fd(fd_a);
73        UnixClient::new(UnixConnection::new(fd_b))
74    }
75}