Compare commits
2 Commits
407085c78b
...
5e54d316d7
| Author | SHA1 | Date | |
|---|---|---|---|
| 5e54d316d7 | |||
| edbebe64fe |
@ -1,11 +1,9 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use shared::blockchain_core;
|
||||
use shared::blockchain_core::{self, Address, AddressParser};
|
||||
use cli_renderer::RenderLayoutKind;
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use clap::*;
|
||||
|
||||
#[derive(Parser)]
|
||||
pub struct Cli {
|
||||
#[command(subcommand)]
|
||||
@ -14,6 +12,7 @@ pub struct Cli {
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum CliCommand {
|
||||
/// Ping a node
|
||||
#[command(name = "ping")]
|
||||
Ping {
|
||||
#[command(subcommand)]
|
||||
@ -34,12 +33,12 @@ pub enum CliCommand {
|
||||
block_cmd: CliBlockCommand,
|
||||
},
|
||||
|
||||
/// Award currency to wallet
|
||||
#[command(name = "award")]
|
||||
Award {
|
||||
#[arg(short, long)]
|
||||
#[clap(value_parser = AddressParser {})]
|
||||
address: Address,
|
||||
amount: u64,
|
||||
#[arg(short, long)]
|
||||
address: String,
|
||||
},
|
||||
|
||||
/// Make a Transaction
|
||||
@ -120,14 +119,14 @@ pub enum CliPingCommand {
|
||||
/// Ping Peer by Id
|
||||
#[command(name = "id", aliases = ["i"])]
|
||||
Id {
|
||||
#[arg(short, long)]
|
||||
#[arg()]
|
||||
id: String,
|
||||
},
|
||||
|
||||
/// Ping Peer by Address
|
||||
#[command(name = "addr", aliases = ["a", "ad"])]
|
||||
Addr {
|
||||
#[arg(short, long)]
|
||||
#[arg()]
|
||||
addr: String,
|
||||
},
|
||||
}
|
||||
|
||||
@ -60,15 +60,12 @@ pub fn cli(input: &str) -> WatcherCommand {
|
||||
WatcherCommand::Node(NodeCommand::ProcessChainData(ChainData::NodeTransaction(tx)))
|
||||
}
|
||||
CliCommand::Award { address, amount } => {
|
||||
let mut bytes = [0u8; 20];
|
||||
log(msg!(DEBUG, "Received address: {:?}", address));
|
||||
if address.len() != 20 {
|
||||
log(msg!(ERROR, "Invalid address length"))
|
||||
} else if !address.is_ascii() {
|
||||
log(msg!(ERROR, "Invalid address content"))
|
||||
}
|
||||
|
||||
bytes.copy_from_slice(address.as_bytes());
|
||||
WatcherCommand::Node(NodeCommand::AwardCurrency{ address: bytes, amount }
|
||||
WatcherCommand::Node(NodeCommand::AwardCurrency{ address, amount }
|
||||
)}
|
||||
CliCommand::DebugShowId => WatcherCommand::Node(NodeCommand::ShowId),
|
||||
CliCommand::StartListner { addr } => {
|
||||
|
||||
@ -3,7 +3,7 @@ use crate::network::NodeId;
|
||||
use crate::node::node;
|
||||
use super::ProtocolMessage;
|
||||
use tokio::net;
|
||||
use tokio::sync::mpsc;
|
||||
use futures::stream::Stream;
|
||||
|
||||
use super::Connector;
|
||||
|
||||
@ -14,22 +14,27 @@ use vlogger::*;
|
||||
pub struct Connection {
|
||||
node_id: NodeId,
|
||||
peer_id: NodeId,
|
||||
stream: net::TcpStream,
|
||||
rx: mpsc::Receiver<ProtocolMessage>,
|
||||
r_stream: net::tcp::OwnedReadHalf,
|
||||
}
|
||||
|
||||
impl Stream for Connection {
|
||||
type Item = (NodeId, Option<ProtocolMessage>);
|
||||
|
||||
fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<Self::Item>> {
|
||||
todo!("Impl poll next")
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
pub fn new(
|
||||
node_id: NodeId,
|
||||
peer_id: NodeId,
|
||||
stream: net::TcpStream,
|
||||
rx: mpsc::Receiver<ProtocolMessage>,
|
||||
r_stream: net::tcp::OwnedReadHalf,
|
||||
) -> Self {
|
||||
Self {
|
||||
node_id,
|
||||
peer_id,
|
||||
stream,
|
||||
rx,
|
||||
r_stream,
|
||||
}
|
||||
}
|
||||
|
||||
@ -38,22 +43,7 @@ impl Connection {
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
response_result = self.rx.recv() => {
|
||||
match response_result {
|
||||
Some(response) => {
|
||||
if let Err(e) = Connector::send_message(&mut self.stream, &response).await {
|
||||
log(msg!(ERROR, "Failed to send response to {}: {}", self.peer_id.clone(), e));
|
||||
break;
|
||||
}
|
||||
},
|
||||
None => {
|
||||
log(msg!(DEBUG, "Response channel closed for {}", self.peer_id));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
message_result = Connector::receive_message(&mut self.stream) => {
|
||||
message_result = Connector::receive_message(&mut self.r_stream) => {
|
||||
match message_result {
|
||||
Ok(message) => {
|
||||
todo!("[TODO] Return parsed command to propagate");
|
||||
|
||||
@ -1,19 +1,18 @@
|
||||
use anyhow::Context;
|
||||
use futures::stream::{ StreamExt, SelectAll };
|
||||
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
|
||||
use std::net::SocketAddr;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net;
|
||||
use tokio::sync::mpsc;
|
||||
use vlogger::*;
|
||||
use shared::print_error_chain;
|
||||
use thiserror::*;
|
||||
|
||||
use crate::db::BINCODE_CONFIG;
|
||||
use crate::log;
|
||||
use crate::network::NodeId;
|
||||
use crate::network::{NodeId, ProtocolError};
|
||||
use super::Connection;
|
||||
use crate::bus::*;
|
||||
use crate::node::node;
|
||||
use crate::node::{NetworkError, error};
|
||||
use super::ProtocolMessage;
|
||||
|
||||
pub enum ConnectorCommand {
|
||||
@ -26,6 +25,8 @@ pub struct Connector {
|
||||
node_id: NodeId,
|
||||
addr: SocketAddr,
|
||||
connections: Vec<Connection>,
|
||||
peer_streams: Vec<(NodeId, OwnedWriteHalf)>,
|
||||
streams: SelectAll<Connection>,
|
||||
listener: Option<tokio::net::TcpListener>,
|
||||
exit: bool,
|
||||
}
|
||||
@ -33,7 +34,17 @@ pub struct Connector {
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ConnectorError {
|
||||
#[error("Connection failed")]
|
||||
ConnectionError(#[from] anyhow::Error),
|
||||
IO(#[from] std::io::Error),
|
||||
#[error("Decode Error: {0}")]
|
||||
Decode(#[from] bincode::error::DecodeError),
|
||||
#[error("Encode Error: {0}")]
|
||||
Encode(#[from] bincode::error::EncodeError),
|
||||
#[error("Protocol Error: {0}")]
|
||||
Protocol(#[from] crate::network::message::ProtocolError),
|
||||
#[error("Unkown Peer Id: {0}")]
|
||||
UnknownPeerId(NodeId),
|
||||
#[error("Unkown Peer Address: {0}")]
|
||||
UnknownPeerAddr(SocketAddr),
|
||||
}
|
||||
|
||||
const MAX_LISTNER_TRIES: usize = 5;
|
||||
@ -47,6 +58,8 @@ impl Connector {
|
||||
node_id,
|
||||
addr,
|
||||
connections: Vec::new(),
|
||||
peer_streams: Vec::new(),
|
||||
streams: SelectAll::new(),
|
||||
listener: None,
|
||||
exit: false,
|
||||
}
|
||||
@ -71,8 +84,11 @@ impl Connector {
|
||||
|
||||
pub async fn poll(&mut self) -> Result<Option<node::NodeCommand>, ConnectorError> {
|
||||
if let Some(listener) = &mut self.listener {
|
||||
todo!("Implement Vec Poll for connections");
|
||||
tokio::select! {
|
||||
protocol_message = self.streams.next() => {
|
||||
todo!("Implement protocol message");
|
||||
}
|
||||
|
||||
// cmd_result = self.rx.recv() => {
|
||||
// todo!("Implement Vec Poll for connections");
|
||||
// match cmd_result {
|
||||
@ -108,7 +124,7 @@ impl Connector {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn execute_cmd(&mut self, cmd: ConnectorCommand) -> Result<Option<node::NodeCommand>, ConnectorError> {
|
||||
pub async fn command(&mut self, cmd: ConnectorCommand) -> Result<Option<node::NodeCommand>, ConnectorError> {
|
||||
match cmd {
|
||||
ConnectorCommand::ConnectToTcpPeer(addr) => {
|
||||
let peer = self.connect_to_peer(addr).await?;
|
||||
@ -128,7 +144,6 @@ impl Connector {
|
||||
pub async fn connect_to_seed(&mut self, addr: SocketAddr) -> Result<node::TcpPeer, ConnectorError> {
|
||||
match net::TcpStream::connect(addr)
|
||||
.await
|
||||
.with_context(|| format!("Connecting to {}", addr))
|
||||
{
|
||||
Ok(stream) => {
|
||||
let peer = self.establish_connection_outbound(stream, addr).await;
|
||||
@ -136,9 +151,8 @@ impl Connector {
|
||||
peer
|
||||
},
|
||||
Err(e) => {
|
||||
// let err = ConnectorError::ConnectionError(e.into());
|
||||
print_error_chain(&e.into());
|
||||
todo!("Handle connector error propagation");
|
||||
let err = ConnectorError::IO(e);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -147,9 +161,8 @@ impl Connector {
|
||||
match net::TcpStream::connect(addr).await {
|
||||
Ok(stream) => self.establish_connection_inbound(stream, addr).await,
|
||||
Err(e) => {
|
||||
let err = ConnectorError::ConnectionError(e.into());
|
||||
print_error_chain(&err.into());
|
||||
todo!("Handle connector error propagation");
|
||||
let err = ConnectorError::IO(e);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -158,29 +171,28 @@ impl Connector {
|
||||
match net::TcpStream::connect(addr).await {
|
||||
Ok(stream) => self.establish_connection_outbound(stream, addr).await,
|
||||
Err(e) => {
|
||||
let err = ConnectorError::ConnectionError(e.into());
|
||||
print_error_chain(&err.into());
|
||||
todo!("Handle connector error propagation");
|
||||
let err = ConnectorError::IO(e);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn establish_connection_outbound(
|
||||
&mut self,
|
||||
mut stream: tokio::net::TcpStream,
|
||||
stream: tokio::net::TcpStream,
|
||||
addr: SocketAddr,
|
||||
) -> Result<node::TcpPeer, ConnectorError> {
|
||||
let (mut r_stream, mut w_stream) = stream.into_split();
|
||||
let handshake = ProtocolMessage::Handshake {
|
||||
peer_id: self.node_id.clone(),
|
||||
version: "".to_string(),
|
||||
};
|
||||
match Connector::send_message(&mut stream, &handshake).await {
|
||||
match Connector::send_message(&mut w_stream, &handshake).await {
|
||||
Ok(()) => {
|
||||
if let Ok(mes) = Connector::receive_message(&mut stream).await {
|
||||
let (ch_tx, ch_rx) = mpsc::channel::<ProtocolMessage>(100);
|
||||
if let Ok(mes) = Connector::receive_message(&mut r_stream).await {
|
||||
let peer = match mes {
|
||||
ProtocolMessage::HandshakeAck { peer_id, .. } => {
|
||||
node::TcpPeer::new(peer_id, addr, ch_tx)
|
||||
node::TcpPeer::new(peer_id, addr)
|
||||
}
|
||||
_ => {
|
||||
log(msg!(
|
||||
@ -190,7 +202,7 @@ impl Connector {
|
||||
todo!("Handle connector receive message fail");
|
||||
}
|
||||
};
|
||||
let connection = Connection::new(self.node_id.clone(), peer.id.clone(), stream, ch_rx);
|
||||
let connection = Connection::new(self.node_id.clone(), peer.id.clone(), r_stream);
|
||||
self.connections.push(connection);
|
||||
Ok(peer)
|
||||
} else {
|
||||
@ -206,82 +218,78 @@ impl Connector {
|
||||
|
||||
async fn establish_connection_inbound(
|
||||
&mut self,
|
||||
mut stream: tokio::net::TcpStream,
|
||||
stream: tokio::net::TcpStream,
|
||||
addr: SocketAddr,
|
||||
) -> Result<node::TcpPeer, ConnectorError> {
|
||||
if let Ok(mes) = Connector::receive_message(&mut stream).await {
|
||||
let (ch_tx, ch_rx) = mpsc::channel::<ProtocolMessage>(100);
|
||||
let peer = match mes {
|
||||
ProtocolMessage::Handshake { peer_id, .. } => {
|
||||
let ack = ProtocolMessage::HandshakeAck {
|
||||
peer_id: self.node_id.clone(),
|
||||
version: "".to_string(),
|
||||
};
|
||||
match Connector::send_message(&mut stream, &ack).await {
|
||||
Ok(()) => node::TcpPeer::new(peer_id, addr, ch_tx),
|
||||
Err(e) => {
|
||||
print_error_chain(&e.into());
|
||||
todo!("Implement inbound conneciton message send fail")
|
||||
let (mut r_stream, mut w_stream) = stream.into_split();
|
||||
let mes = Connector::receive_message(&mut r_stream).await?;
|
||||
let peer = match mes {
|
||||
ProtocolMessage::Handshake { peer_id, .. } => {
|
||||
let ack = ProtocolMessage::HandshakeAck {
|
||||
peer_id: self.node_id.clone(),
|
||||
version: "".to_string(),
|
||||
};
|
||||
Connector::send_message(&mut w_stream, &ack).await?;
|
||||
node::TcpPeer::new(peer_id, addr)
|
||||
}
|
||||
e => {
|
||||
return Err(ConnectorError::Protocol(ProtocolError::Unexpected(e)));
|
||||
}
|
||||
};
|
||||
let connection = Connection::new(self.node_id.clone(), peer.id.clone(), r_stream);
|
||||
self.connections.push(connection);
|
||||
Ok(peer)
|
||||
}
|
||||
|
||||
},
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
log(msg!(
|
||||
ERROR,
|
||||
"Invalid Message On Connetion Establishment: {mes}"
|
||||
));
|
||||
todo!("Implement inbound conneciton message invalid");
|
||||
}
|
||||
};
|
||||
let connection = Connection::new(self.node_id.clone(), peer.id.clone(), stream, ch_rx);
|
||||
self.connections.push(connection);
|
||||
Ok(peer)
|
||||
pub async fn send_message_to_peer(&mut self, peer_id: NodeId, message: &ProtocolMessage) -> Result<(), ConnectorError> {
|
||||
if let Some((_, w_stream)) = &mut self.peer_streams.iter_mut().find(|p| p.0 == peer_id) {
|
||||
Connector::send_message(w_stream, message).await
|
||||
} else {
|
||||
todo!("Implement inbount connection message read fail");
|
||||
Err(ConnectorError::UnknownPeerId(peer_id))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send_message(
|
||||
stream: &mut net::TcpStream,
|
||||
stream: &mut net::tcp::OwnedWriteHalf,
|
||||
message: &ProtocolMessage,
|
||||
) -> Result<(), NetworkError> {
|
||||
) -> Result<(), ConnectorError> {
|
||||
let data = bincode::encode_to_vec(message, BINCODE_CONFIG)?;
|
||||
|
||||
let len = data.len() as u32;
|
||||
|
||||
stream
|
||||
.write_all(&len.to_be_bytes())
|
||||
.await
|
||||
.map_err(|_e| NetworkError::TODO)?;
|
||||
.map_err(|e| ConnectorError::IO(e))?;
|
||||
|
||||
stream
|
||||
.write_all(&data)
|
||||
.await
|
||||
.map_err(|_e| NetworkError::TODO)?;
|
||||
stream.flush().await.map_err(|_e| NetworkError::TODO)?;
|
||||
.map_err(|e| ConnectorError::IO(e))?;
|
||||
stream.flush().await.map_err(|e| ConnectorError::IO(e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn receive_message(
|
||||
stream: &mut tokio::net::TcpStream,
|
||||
) -> Result<ProtocolMessage, error::NetworkError> {
|
||||
stream: &mut OwnedReadHalf,
|
||||
) -> Result<ProtocolMessage, ConnectorError> {
|
||||
let mut len_bytes = [0u8; 4];
|
||||
stream
|
||||
.read_exact(&mut len_bytes)
|
||||
.await
|
||||
.map_err(|_e| NetworkError::TODO)?;
|
||||
.map_err(|e| ConnectorError::IO(e))?;
|
||||
|
||||
let len = u32::from_be_bytes(len_bytes) as usize;
|
||||
|
||||
if len >= super::message::MAX_MESSAGE_SIZE {
|
||||
return Err(NetworkError::TODO);
|
||||
return Err(ConnectorError::Protocol(ProtocolError::MessageTooLong(len)));
|
||||
}
|
||||
|
||||
let mut data = vec![0u8; len];
|
||||
stream
|
||||
.read_exact(&mut data)
|
||||
.await
|
||||
.map_err(|_e| NetworkError::TODO)?;
|
||||
.map_err(|e| ConnectorError::IO(e))?;
|
||||
|
||||
let (message, _): (ProtocolMessage, usize) = bincode::decode_from_slice(&data, BINCODE_CONFIG)?;
|
||||
|
||||
|
||||
@ -4,9 +4,17 @@ use std::net::SocketAddr;
|
||||
|
||||
pub const MAX_MESSAGE_SIZE: usize = 1_000_000;
|
||||
|
||||
#[derive(Debug, Clone, bincode::Encode, bincode::Decode, Hash, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Copy, bincode::Encode, bincode::Decode, Hash, PartialEq, Eq)]
|
||||
pub struct NodeId(pub [u8; 16]);
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum ProtocolError {
|
||||
#[error("Invalid message len: {0}")]
|
||||
MessageTooLong(usize),
|
||||
#[error("Unexpected message: {0}")]
|
||||
Unexpected(ProtocolMessage)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, bincode::Encode, bincode::Decode)]
|
||||
pub enum ProtocolMessage {
|
||||
BootstrapRequest {
|
||||
@ -51,10 +59,9 @@ pub enum ProtocolMessage {
|
||||
}
|
||||
|
||||
impl fmt::Display for NodeId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let msg = self.to_string();
|
||||
write!(f, "{}", msg)
|
||||
}
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", hex::encode(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ProtocolMessage {
|
||||
|
||||
@ -33,9 +33,9 @@ pub struct ChainBootStrap {
|
||||
#[allow(dead_code)]
|
||||
#[derive(Error, Debug)]
|
||||
pub enum BlockchainError {
|
||||
#[error("Failed to serialize data: {0}")]
|
||||
#[error("Failed to serialize data")]
|
||||
Encode(#[from] bincode::error::EncodeError),
|
||||
#[error("Failed to deserialize data: {0}")]
|
||||
#[error("Failed to deserialize data")]
|
||||
Decode(#[from] bincode::error::DecodeError),
|
||||
#[error("Database operation failed")]
|
||||
Database(#[from] DatabaseError),
|
||||
|
||||
@ -4,8 +4,4 @@ use thiserror::Error;
|
||||
pub enum NetworkError {
|
||||
#[error("Implement NetworkError Enum: ({})", file!())]
|
||||
TODO,
|
||||
#[error("Decode Error: {0}")]
|
||||
Decode(#[from] bincode::error::DecodeError),
|
||||
#[error("Encode Error: {0}")]
|
||||
Encode(#[from] bincode::error::EncodeError),
|
||||
}
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
use crate::bus::{publish_system_event, publish_watcher_event, subscribe_system_event, SystemEvent};
|
||||
use shared::blockchain_core::{self, ChainData, SignedTransaction, validator::ValidationError};
|
||||
use crate::print_error_chain;
|
||||
use crate::network::ConnectorError;
|
||||
use shared::blockchain_core::{self, ChainData, SignedTransaction};
|
||||
use crate::log;
|
||||
use crate::network::{NodeId, ProtocolMessage};
|
||||
use crate::network::{Connector, ConnectorCommand};
|
||||
@ -20,24 +19,22 @@ use vlogger::*;
|
||||
pub struct TcpPeer {
|
||||
pub id: NodeId,
|
||||
pub addr: SocketAddr,
|
||||
pub sender: tokio::sync::mpsc::Sender<ProtocolMessage>,
|
||||
}
|
||||
|
||||
impl TcpPeer {
|
||||
pub fn new(
|
||||
id: NodeId,
|
||||
addr: SocketAddr,
|
||||
sender: tokio::sync::mpsc::Sender<ProtocolMessage>,
|
||||
) -> Self {
|
||||
Self { id, addr, sender }
|
||||
Self { id, addr }
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct Node {
|
||||
pub tcp_connector: Option<Connector>,
|
||||
pub tcp_connector: Connector,
|
||||
pub id: NodeId,
|
||||
pub addr: Option<SocketAddr>,
|
||||
pub addr: SocketAddr,
|
||||
pub tcp_peers: HashMap<NodeId, TcpPeer>,
|
||||
chain: Blockchain,
|
||||
listner_handle: Option<tokio::task::JoinHandle<()>>,
|
||||
@ -46,7 +43,15 @@ pub struct Node {
|
||||
#[derive(Debug, Error)]
|
||||
pub enum NodeError {
|
||||
#[error("Block chain error")]
|
||||
ChainError(#[from] BlockchainError),
|
||||
Blockchain(#[from] BlockchainError),
|
||||
#[error("Connector Error")]
|
||||
Connector(#[from] ConnectorError),
|
||||
#[error("Unknown peer address")]
|
||||
UnknownPeerAddr(SocketAddr),
|
||||
#[error("Invalid Address:\npeer: {0}\naddr: {1}")]
|
||||
InvalidAddress(String, SocketAddr),
|
||||
#[error("Hex Error")]
|
||||
Hex(#[from] hex::FromHexError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@ -86,9 +91,7 @@ impl Node {
|
||||
.iter()
|
||||
.map(|p| p.1.addr.to_string().parse::<SocketAddr>().unwrap())
|
||||
.collect();
|
||||
if let Some(a) = self.addr {
|
||||
addr.push(a.clone());
|
||||
}
|
||||
addr.push(self.addr.clone());
|
||||
addr
|
||||
}
|
||||
|
||||
@ -109,43 +112,42 @@ impl Node {
|
||||
self.tcp_peers.remove_entry(&peer_id);
|
||||
}
|
||||
|
||||
async fn add_tcp_peer(&mut self, peer: TcpPeer) {
|
||||
fn add_tcp_peer(&mut self, peer: TcpPeer) {
|
||||
log(msg!(DEBUG, "Added Peer from address: {}", peer.addr));
|
||||
self.tcp_peers.insert(peer.id.clone(), peer);
|
||||
}
|
||||
|
||||
pub async fn new_with_id(
|
||||
id: NodeId,
|
||||
addr: Option<SocketAddr>,
|
||||
addr: SocketAddr,
|
||||
chain: Blockchain,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
id: id.clone(),
|
||||
tcp_peers: HashMap::new(),
|
||||
addr,
|
||||
chain,
|
||||
listner_handle: None,
|
||||
tcp_connector: None,
|
||||
tcp_connector: Connector::new(id, addr),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
addr: Option<SocketAddr>,
|
||||
addr: SocketAddr,
|
||||
chain: Blockchain,
|
||||
) -> Self {
|
||||
let id = NodeId(*Uuid::new_v4().as_bytes());
|
||||
Self {
|
||||
id: NodeId(*Uuid::new_v4().as_bytes()),
|
||||
id: id.clone(),
|
||||
tcp_peers: HashMap::new(),
|
||||
addr,
|
||||
listner_handle: None,
|
||||
tcp_connector: None,
|
||||
tcp_connector: Connector::new(id, addr),
|
||||
chain,
|
||||
}
|
||||
}
|
||||
|
||||
async fn shutdown(&mut self) {
|
||||
if let Some(conn) = &self.tcp_connector {
|
||||
}
|
||||
let _ = self.chain.shutdown().await;
|
||||
}
|
||||
|
||||
@ -153,6 +155,25 @@ impl Node {
|
||||
Ok(self.chain.blocks()?)
|
||||
}
|
||||
|
||||
async fn send_message(&mut self, peer_id: NodeId, message: &ProtocolMessage) -> Result<(), NodeError> {
|
||||
self.tcp_connector.send_message_to_peer(peer_id, &message).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn broadcast_message(&mut self, msg: &ProtocolMessage) -> Result<(), NodeError> {
|
||||
let keys: Vec<_> = self.tcp_peers.keys().cloned().collect();
|
||||
let mut results = Vec::new();
|
||||
for id in keys {
|
||||
let res = self.send_message(id, msg).await;
|
||||
results.push(res);
|
||||
}
|
||||
if let Some(error) = results.into_iter().find(|r| r.is_err()) {
|
||||
error
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn process_message(&mut self, peer_id: NodeId, message: ProtocolMessage) -> Result<(), NodeError> {
|
||||
match message {
|
||||
ProtocolMessage::BootstrapRequest { .. } => {
|
||||
@ -160,7 +181,7 @@ impl Node {
|
||||
let peer = &self.tcp_peers[&peer_id];
|
||||
let blocks = self.chain.bootstrap()?;
|
||||
let resp = ProtocolMessage::BootstrapResponse { blocks };
|
||||
peer.sender.send(resp).await.unwrap();
|
||||
self.send_message(peer.id.clone(), &resp).await?;
|
||||
log(msg!(DEBUG, "Send BootstrapResponse to {peer_id}"));
|
||||
}
|
||||
ProtocolMessage::BootstrapResponse { blocks } => {
|
||||
@ -172,11 +193,11 @@ impl Node {
|
||||
}
|
||||
ProtocolMessage::Ping { peer_id } => {
|
||||
log(msg!(DEBUG, "Received Ping from {peer_id}"));
|
||||
let peer = &self.tcp_peers[&peer_id];
|
||||
let resp = ProtocolMessage::Pong {
|
||||
peer_id: self.id.clone(),
|
||||
};
|
||||
let peer = &self.tcp_peers[&peer_id];
|
||||
peer.sender.send(resp).await.unwrap();
|
||||
self.send_message(peer.id.clone(), &resp).await?;
|
||||
}
|
||||
ProtocolMessage::GetPeersRequest { peer_id } => {
|
||||
log(msg!(DEBUG, "Received GetPeersRequest from {peer_id}"));
|
||||
@ -185,7 +206,7 @@ impl Node {
|
||||
peer_addresses: peers,
|
||||
};
|
||||
let peer = &self.tcp_peers[&peer_id];
|
||||
peer.sender.send(resp).await.unwrap();
|
||||
self.send_message(peer.id.clone(), &resp).await?;
|
||||
}
|
||||
ProtocolMessage::Block { block, .. } => {
|
||||
log(msg!(DEBUG, "Received Block from {peer_id}"));
|
||||
@ -209,223 +230,163 @@ impl Node {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_message_to_peer_addr(&self, addr: SocketAddr, msg: ProtocolMessage) {
|
||||
pub async fn send_message_to_peer_addr(&mut self, addr: SocketAddr, msg: &ProtocolMessage) -> Result<(), NodeError> {
|
||||
if let Some((_, peer)) = self.tcp_peers.iter().find(|(_, v)| v.addr == addr) {
|
||||
if let Err(e) = peer.sender.send(msg).await {
|
||||
log(msg!(ERROR, "Error Sending message to peer: {e}"));
|
||||
}
|
||||
log(msg!(DEBUG, "Sent BootstrapRequest to seed"));
|
||||
self.send_message(peer.id.clone(), &msg).await?;
|
||||
Ok(())
|
||||
} else {
|
||||
log(msg!(
|
||||
ERROR,
|
||||
"Error Sending message to peer: peer not in list"
|
||||
));
|
||||
Err(NodeError::UnknownPeerAddr(addr))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send_message_to_peer_id(&self, id: NodeId, msg: ProtocolMessage) {
|
||||
if let Some(peer) = self.tcp_peers.get(&id) {
|
||||
if let Err(e) = peer.sender.send(msg).await {
|
||||
log(msg!(ERROR, "Error Sending message to peer: {e}"));
|
||||
}
|
||||
}
|
||||
pub async fn send_message_to_peer_id(&mut self, id: NodeId, msg: &ProtocolMessage) -> Result<(), NodeError> {
|
||||
self.send_message(id.clone(), &msg).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_message_to_seed(&self, msg: ProtocolMessage) {
|
||||
async fn send_message_to_seed(&mut self, msg: &ProtocolMessage) -> Result<(), NodeError> {
|
||||
for seed in SEED_NODES.iter() {
|
||||
if let Some(_) = self.tcp_peers.iter().find(|(_, v)| v.addr == *seed) {
|
||||
self.send_message_to_peer_addr(*seed, msg).await;
|
||||
return;
|
||||
} else {
|
||||
self.send_message_to_peer_addr(*seed, msg).await;
|
||||
return;
|
||||
if let Some(s) = self.tcp_peers.iter().find(|(_, v)| v.addr == *seed) {
|
||||
self.send_message_to_peer_addr(s.1.addr, &msg).await?;
|
||||
}
|
||||
}
|
||||
log(msg!(ERROR, "No Seed Nodes Avaliable"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn bootstrap(&mut self) -> Result<(), ValidationError> {
|
||||
log(msg!(DEBUG, "Bootstrapping"));
|
||||
|
||||
async fn bootstrap(&mut self) -> Result<(), NodeError> {
|
||||
let message = ProtocolMessage::BootstrapRequest {
|
||||
peer_id: self.id.clone(),
|
||||
version: "".to_string(),
|
||||
};
|
||||
self.send_message_to_seed(message).await;
|
||||
|
||||
self.send_message_to_seed(&message).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn broadcast_network_data(&self, data: ChainData) {
|
||||
for (id, peer) in &self.tcp_peers {
|
||||
let message = ProtocolMessage::ChainData {
|
||||
peer_id: self.id.clone(),
|
||||
data: data.clone(),
|
||||
};
|
||||
peer.sender.send(message).await.unwrap();
|
||||
log(msg!(DEBUG, "Send Transaction message to {id}"));
|
||||
}
|
||||
async fn broadcast_network_data(&mut self, data: ChainData) -> Result<(), NodeError> {
|
||||
let message = ProtocolMessage::ChainData {
|
||||
peer_id: self.id.clone(),
|
||||
data,
|
||||
};
|
||||
self.broadcast_message(&message).await
|
||||
}
|
||||
|
||||
async fn broadcast_block(&self, block: &blockchain_core::Block) {
|
||||
for (id, peer) in &self.tcp_peers {
|
||||
let message = ProtocolMessage::Block {
|
||||
peer_id: self.id.clone(),
|
||||
height: block.head().height as u64,
|
||||
block: block.clone(),
|
||||
};
|
||||
peer.sender.send(message).await.unwrap();
|
||||
log(msg!(DEBUG, "Send Block message to {id}"));
|
||||
}
|
||||
async fn broadcast_block(&mut self, block: &blockchain_core::Block) -> Result<(), NodeError> {
|
||||
let message = ProtocolMessage::Block {
|
||||
peer_id: self.id.clone(),
|
||||
height: block.head().height as u64,
|
||||
block: block.clone(),
|
||||
};
|
||||
self.broadcast_message(&message).await
|
||||
}
|
||||
|
||||
async fn connector_cmd(&mut self, cmd: ConnectorCommand) -> Result<Option<NodeCommand>, crate::network::ConnectorError> {
|
||||
match &mut self.tcp_connector {
|
||||
Some(t) => { t.execute_cmd(cmd).await },
|
||||
None => {
|
||||
log(msg!(ERROR, "No Connector Availiable"));
|
||||
todo!("Implement node level connection cmd fail");
|
||||
},
|
||||
}
|
||||
async fn connector_cmd(&mut self, cmd: ConnectorCommand) -> Result<Option<NodeCommand>, NodeError> {
|
||||
let res = self.tcp_connector.command(cmd).await?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
async fn start_connection_listner(&mut self, addr: SocketAddr) {
|
||||
fn start_connection_listner(&mut self, addr: SocketAddr) {
|
||||
log(msg!(DEBUG, "Starting Connection Listener"));
|
||||
|
||||
let connector = Connector::new(self.id.clone(), addr);
|
||||
log(msg!(DEBUG, "Connector Build"));
|
||||
self.tcp_connector = Some(connector);
|
||||
let connector = Connector::new(self.id.clone(), addr);
|
||||
log(msg!(DEBUG, "Connector Build"));
|
||||
self.tcp_connector = connector;
|
||||
}
|
||||
|
||||
async fn connect_to_seed(&mut self) {
|
||||
self
|
||||
.connector_cmd(ConnectorCommand::ConnectToTcpSeed(SEED_NODES[0]))
|
||||
.await;
|
||||
async fn connect_to_seed(&mut self) -> Result<Option<NodeCommand>, NodeError> {
|
||||
let res = self.tcp_connector.command(ConnectorCommand::ConnectToTcpSeed(SEED_NODES[0])).await?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub async fn command(&mut self, command: NodeCommand) {
|
||||
match command {
|
||||
NodeCommand::BootStrap => {
|
||||
log(msg!(DEBUG, "Received NodeCommand::BootStrap"));
|
||||
let _ = self.bootstrap().await;
|
||||
pub async fn command(&mut self, command: NodeCommand) -> Result<Option<WatcherCommand>, NodeError> {
|
||||
match command {
|
||||
NodeCommand::BootStrap => {
|
||||
self.bootstrap().await?;
|
||||
}
|
||||
NodeCommand::BroadcastTransaction(sign_tx) => {
|
||||
self.broadcast_network_data(ChainData::Transaction(sign_tx)).await?;
|
||||
}
|
||||
NodeCommand::StartListner(addr) => {
|
||||
self.start_connection_listner(addr);
|
||||
}
|
||||
NodeCommand::ConnectToSeeds => {
|
||||
self.connect_to_seed().await?;
|
||||
}
|
||||
NodeCommand::ConnectTcpPeer(addr) => {
|
||||
let addr_sock = addr.parse::<SocketAddr>()
|
||||
.map_err(|_| NodeError::InvalidAddress("Self".to_string(), self.addr))?;
|
||||
let res = self.connector_cmd(ConnectorCommand::ConnectToTcpPeer(addr_sock)).await?;
|
||||
if let Some(node_cmd) = res {
|
||||
return Ok(Some(WatcherCommand::Node(node_cmd)))
|
||||
}
|
||||
NodeCommand::BroadcastTransaction(sign_tx) => {
|
||||
self.broadcast_network_data(ChainData::Transaction(sign_tx)).await;
|
||||
}
|
||||
NodeCommand::StartListner(addr) => {
|
||||
self.start_connection_listner(addr).await;
|
||||
}
|
||||
NodeCommand::ConnectToSeeds => {
|
||||
self.connect_to_seed().await;
|
||||
}
|
||||
NodeCommand::ConnectTcpPeer(addr) => {
|
||||
log(msg!(DEBUG, "Received ConnectToPeer: {addr}"));
|
||||
if let Ok(addr_sock) = addr.parse::<SocketAddr>() {
|
||||
let mes = ConnectorCommand::ConnectToTcpPeer(addr_sock);
|
||||
self.connector_cmd(mes).await;
|
||||
} else {
|
||||
log(msg!(ERROR, "Failed to Parse to sock_addr: {addr}"));
|
||||
}
|
||||
}
|
||||
NodeCommand::PingAddr(addr) => {
|
||||
if let Ok(addr_sock) = addr.parse::<SocketAddr>() {
|
||||
let mes = ProtocolMessage::Ping { peer_id: self.id.clone() };
|
||||
self.send_message_to_peer_addr(addr_sock, mes).await;
|
||||
} else {
|
||||
log(msg!(ERROR, "Failed to Parse to sock_addr: {addr}"));
|
||||
}
|
||||
}
|
||||
NodeCommand::PingId(id) => {
|
||||
let mes = ProtocolMessage::Ping { peer_id: self.id.clone() };
|
||||
self.send_message_to_peer_id(id, mes).await;
|
||||
}
|
||||
NodeCommand::AddPeer(peer) => {
|
||||
self.add_tcp_peer(peer).await;
|
||||
}
|
||||
NodeCommand::RemovePeer { peer_id } => {
|
||||
self.remove_tcp_peer(peer_id).await;
|
||||
}
|
||||
|
||||
NodeCommand::ProcessMessage { peer_id, message } => {
|
||||
self.process_message(peer_id, message).await.unwrap();
|
||||
}
|
||||
NodeCommand::AwardCurrency { address, amount } => {
|
||||
if let Err(e) = self.chain.award_currency(address, amount) {
|
||||
print_error_chain(&e.into());
|
||||
}
|
||||
}
|
||||
NodeCommand::ProcessChainData(data) => {
|
||||
if let Err(e) = self.chain.apply_chain_data(data.clone()) {
|
||||
print_error_chain(&e.into());
|
||||
}
|
||||
self.broadcast_network_data(data).await;
|
||||
}
|
||||
NodeCommand::CreateBlock => {
|
||||
log(msg!(DEBUG, "Received CreateBlock Command"));
|
||||
match self.chain.create_block() {
|
||||
Ok(block) => {
|
||||
log(msg!(
|
||||
INFO,
|
||||
"Created Block with hash {}",
|
||||
hex::encode(block.head().block_hash())
|
||||
));
|
||||
self.broadcast_block(&block).await;
|
||||
}
|
||||
Err(e) => print_error_chain(&e.into()),
|
||||
}
|
||||
}
|
||||
NodeCommand::DisplayBlockInteractive => {
|
||||
let blocks = match self.chain.list_blocks() {
|
||||
Ok(b) => b,
|
||||
Err(e) => return print_error_chain(&e.into()),
|
||||
};
|
||||
let wat_cmd = WatcherCommand::SetMode(WatcherMode::Select {
|
||||
}
|
||||
NodeCommand::PingAddr(addr) => {
|
||||
let addr_sock = addr.parse::<SocketAddr>()
|
||||
.map_err(|_| NodeError::InvalidAddress("Self".to_string(), self.addr))?;
|
||||
let mes = ProtocolMessage::Ping { peer_id: self.id.clone() };
|
||||
self.send_message_to_peer_addr(addr_sock, &mes).await?;
|
||||
}
|
||||
NodeCommand::PingId(id) => {
|
||||
let mes = ProtocolMessage::Ping { peer_id: self.id.clone() };
|
||||
self.send_message_to_peer_id(id, &mes).await?;
|
||||
}
|
||||
NodeCommand::AddPeer(peer) => {
|
||||
self.add_tcp_peer(peer);
|
||||
}
|
||||
NodeCommand::RemovePeer { peer_id } => {
|
||||
self.remove_tcp_peer(peer_id).await;
|
||||
}
|
||||
NodeCommand::ProcessMessage { peer_id, message } => {
|
||||
self.process_message(peer_id, message).await?;
|
||||
}
|
||||
NodeCommand::AwardCurrency { address, amount } => {
|
||||
self.chain.award_currency(address, amount)?;
|
||||
}
|
||||
NodeCommand::ProcessChainData(data) => {
|
||||
self.chain.apply_chain_data(data.clone())?;
|
||||
self.broadcast_network_data(data).await?;
|
||||
}
|
||||
NodeCommand::CreateBlock => {
|
||||
let block = self.chain.create_block()?;
|
||||
self.broadcast_block(&block).await?;
|
||||
}
|
||||
NodeCommand::DisplayBlockInteractive => {
|
||||
let blocks = self.chain.list_blocks()?;
|
||||
return Ok(Some(
|
||||
WatcherCommand::SetMode(WatcherMode::Select {
|
||||
content: blocks.iter().map(|h| hex::encode(h)).collect::<Vec<String>>().into(),
|
||||
title: "Select Block to display".to_string(),
|
||||
callback: Box::new(WatcherCommand::Node(NodeCommand::DisplayBlockByKey("".to_string()))),
|
||||
index: 0
|
||||
});
|
||||
publish_watcher_event(wat_cmd);
|
||||
}
|
||||
NodeCommand::DisplayBlockByKey(key) => {
|
||||
if let Ok(block_hash) = hex::decode(key) {
|
||||
self.chain.display_block_by_key(&block_hash)
|
||||
}
|
||||
},
|
||||
NodeCommand::DisplayBlockByHeight(height) => self.chain.display_block_by_height(height),
|
||||
NodeCommand::ListBlocks => {
|
||||
log(msg!(DEBUG, "Received DebugListBlocks command"));
|
||||
match self.chain.list_blocks() {
|
||||
Ok(s) => log(s.iter().map(|h| format!("{}\n", hex::encode(h))).collect::<Vec<String>>().join("\n")),
|
||||
Err(e) => print_error_chain(&e.into()),
|
||||
}
|
||||
}
|
||||
NodeCommand::ListPeers => {
|
||||
log(msg!(DEBUG, "Received DebugListPeers command"));
|
||||
log(self.list_peers());
|
||||
}
|
||||
NodeCommand::ShowId => {
|
||||
log(msg!(DEBUG, "Received DebugListBlocks command"));
|
||||
self.show_id().await;
|
||||
}
|
||||
NodeCommand::Exit => {
|
||||
log(msg!(DEBUG, "Node Exit"));
|
||||
index: 0,
|
||||
})
|
||||
));
|
||||
}
|
||||
NodeCommand::DisplayBlockByKey(key) => {
|
||||
self.chain.display_block_by_key(&hex::decode(key)?);
|
||||
}
|
||||
NodeCommand::DisplayBlockByHeight(height) => {
|
||||
self.chain.display_block_by_height(height);
|
||||
}
|
||||
NodeCommand::ListBlocks => {
|
||||
let s = self.chain.list_blocks()?;
|
||||
let block_list = s.iter().map(|h| format!("{}\n", hex::encode(h))).collect::<Vec<String>>().join("\n");
|
||||
return Ok(Some(WatcherCommand::Print(block_list)));
|
||||
}
|
||||
NodeCommand::ListPeers => {
|
||||
return Ok(Some(WatcherCommand::Print(self.list_peers())));
|
||||
}
|
||||
NodeCommand::ShowId => {
|
||||
self.show_id().await;
|
||||
}
|
||||
NodeCommand::Exit => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn handle_error(&self, error: NodeError) {
|
||||
log(msg!(ERROR, "{error}"));
|
||||
}
|
||||
|
||||
pub async fn init(&mut self) {
|
||||
if let Some(addr) = self.addr {
|
||||
self.start_connection_listner(addr).await;
|
||||
} else {
|
||||
self
|
||||
.start_connection_listner(SocketAddr::new(
|
||||
std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
|
||||
8080,
|
||||
))
|
||||
.await;
|
||||
};
|
||||
|
||||
let _http_handle = tokio::spawn(async move {
|
||||
let _ = crate::api::server::start_server().await;
|
||||
});
|
||||
@ -440,15 +401,12 @@ impl Node {
|
||||
// }
|
||||
// });
|
||||
|
||||
let mut _system_rx = subscribe_system_event();
|
||||
publish_system_event(SystemEvent::NodeStarted);
|
||||
|
||||
self.chain.recover_mempool();
|
||||
}
|
||||
|
||||
pub async fn poll(&mut self) -> Option<()> {
|
||||
tokio::select! {
|
||||
_con_cmd = self.tcp_connector.as_mut()?.poll() => {
|
||||
_con_cmd = self.tcp_connector.poll() => {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@ -71,14 +71,21 @@ impl WatcherBuilder {
|
||||
self.addr = Some(crate::seeds_constants::SEED_NODES[0]);
|
||||
}
|
||||
|
||||
if self.addr.is_none() {
|
||||
self.addr = Some(SocketAddr::new(
|
||||
std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
|
||||
8080,
|
||||
))
|
||||
}
|
||||
|
||||
let chain = node::Blockchain::new(self.database, self.temporary).unwrap();
|
||||
let mut node = Node::new(self.addr.clone(), chain);
|
||||
let mut node = Node::new(self.addr.unwrap(), chain);
|
||||
node.init().await;
|
||||
|
||||
log(msg!(INFO, "Built Node"));
|
||||
|
||||
if self.bootstrap {
|
||||
node.command(NodeCommand::BootStrap).await;
|
||||
node.command(NodeCommand::BootStrap).await.unwrap();
|
||||
}
|
||||
|
||||
let cmd_history = Vec::new();
|
||||
|
||||
@ -1,12 +1,13 @@
|
||||
use crate::{
|
||||
bus::{SystemEvent, publish_system_event, subscribe_system_event}, cli::cli, node::{Node, node::NodeCommand}, watcher::WatcherMode
|
||||
bus::{SystemEvent, publish_system_event, subscribe_system_event}, cli::cli, node::{Node, NodeError, node::NodeCommand}, watcher::WatcherMode
|
||||
};
|
||||
|
||||
use shared::print_error_chain;
|
||||
use ratatui::prelude::CrosstermBackend;
|
||||
use crate::print_error_chain;
|
||||
use crossterm::event::{Event, EventStream, KeyCode, KeyEventKind, MouseButton, MouseEventKind};
|
||||
use futures::StreamExt;
|
||||
use memory_stats::memory_stats;
|
||||
use std::io::{self, Write};
|
||||
use std::io::{self, Stdout, Write};
|
||||
use tokio::{
|
||||
select,
|
||||
time::{Duration, interval},
|
||||
@ -24,6 +25,12 @@ use cli_renderer::{
|
||||
RenderCommand
|
||||
};
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum WatcherError {
|
||||
#[error("Node Error")]
|
||||
Node(#[from] NodeError),
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct Watcher {
|
||||
cmd_buffer: String,
|
||||
@ -86,10 +93,9 @@ impl Watcher {
|
||||
poll_res = self.poll() => {
|
||||
match poll_res {
|
||||
Ok(event) => {
|
||||
self.renderer.set_area(terminal.get_frame().area());
|
||||
match self.handle_event(event).await {
|
||||
Ok(ret) => if !ret { self.exit(); break }
|
||||
Err(e) => log(msg!(ERROR, "{}", e)),
|
||||
match self.handle_event(event, &mut terminal).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => print_error_chain(&e.into()),
|
||||
}
|
||||
}
|
||||
Err(()) => { log(msg!(ERROR, "Failed to read from Stream")) }
|
||||
@ -99,10 +105,13 @@ impl Watcher {
|
||||
match ui_event {
|
||||
Ok(cmd) => {
|
||||
self.renderer.set_area(terminal.get_frame().area());
|
||||
self.command(cmd);
|
||||
match self.command(cmd).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => print_error_chain(&e.into()),
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
log(msg!(ERROR, "{}", e))
|
||||
print_error_chain(&e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -160,28 +169,32 @@ impl Watcher {
|
||||
self.mode = mode;
|
||||
}
|
||||
|
||||
pub async fn command(&mut self, cmd: WatcherCommand) {
|
||||
pub async fn command(&mut self, cmd: WatcherCommand) -> Result<Option<WatcherCommand>, WatcherError> {
|
||||
match cmd {
|
||||
WatcherCommand::NodeResponse(resp) => log(resp),
|
||||
WatcherCommand::Node(n) => self.node.command(n).await,
|
||||
WatcherCommand::Node(n) => return Ok(self.node.command(n).await?),
|
||||
WatcherCommand::Render(p) => self.renderer.apply(p),
|
||||
WatcherCommand::Echo(s) => self.echo(s),
|
||||
WatcherCommand::Print(s) => log(s),
|
||||
WatcherCommand::InvalidCommand(str) => self.invalid_command(str).await,
|
||||
WatcherCommand::Exit => self.exit(),
|
||||
WatcherCommand::SetMode(mode) => self.set_mode(mode),
|
||||
}
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn handle_enter(&mut self) {
|
||||
async fn handle_enter(&mut self) -> Result<(), WatcherError> {
|
||||
match &self.mode {
|
||||
WatcherMode::Input => {
|
||||
if !self.cmd_buffer.is_empty() {
|
||||
let exec_event = cli(&self.cmd_buffer);
|
||||
self.command(exec_event).await;
|
||||
let mut cmd = cli(&self.cmd_buffer);
|
||||
self.cmd_buffer.clear();
|
||||
self.renderer.handle_enter()
|
||||
self.renderer.handle_enter();
|
||||
while let Some(new_cmd) = self.command(cmd).await? {
|
||||
cmd = new_cmd;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
WatcherMode::Select { content, callback, index, .. } => {
|
||||
match &&**callback {
|
||||
@ -190,7 +203,7 @@ impl Watcher {
|
||||
NodeCommand::DisplayBlockByKey(_) => {
|
||||
let key = (*content)[*index].clone().to_string();
|
||||
log(msg!(DEBUG, "KEY IN ENTER: {key}"));
|
||||
self.node.command(NodeCommand::DisplayBlockByKey(key));
|
||||
self.node.command(NodeCommand::DisplayBlockByKey(key)).await?;
|
||||
}
|
||||
_ => {log(msg!(DEBUG, "TODO: Implement callback for {:?}", nd_cmd))}
|
||||
}
|
||||
@ -200,6 +213,7 @@ impl Watcher {
|
||||
self.mode = WatcherMode::Input;
|
||||
let rd_cmd = RenderCommand::SetMode(InputMode::Input);
|
||||
self.renderer.apply(rd_cmd);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -268,7 +282,7 @@ impl Watcher {
|
||||
});
|
||||
}
|
||||
|
||||
pub async fn handle_event(&mut self, event: Event) -> io::Result<bool> {
|
||||
pub async fn handle_event(&mut self, event: Event, terminal: &mut ratatui::Terminal<CrosstermBackend<Stdout>>) -> Result<(), WatcherError> {
|
||||
match event {
|
||||
Event::Mouse(event) => match event.kind {
|
||||
MouseEventKind::ScrollUp => {
|
||||
@ -288,6 +302,9 @@ impl Watcher {
|
||||
},
|
||||
_ => {}
|
||||
},
|
||||
Event::Resize(_, _) => {
|
||||
self.renderer.set_area(terminal.get_frame().area());
|
||||
}
|
||||
Event::Key(k) if k.kind == KeyEventKind::Press => match k.code {
|
||||
KeyCode::Esc => publish_system_event(SystemEvent::Shutdown),
|
||||
KeyCode::Char(c) => {
|
||||
@ -299,7 +316,7 @@ impl Watcher {
|
||||
self.renderer.handle_backspace()
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
self.handle_enter().await;
|
||||
self.handle_enter().await?;
|
||||
}
|
||||
KeyCode::Up | KeyCode::Down | KeyCode::Left | KeyCode::Right => {
|
||||
self.handle_arrow_key(k.code);
|
||||
@ -313,7 +330,7 @@ impl Watcher {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(true)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn poll(&mut self) -> Result<Event, ()> {
|
||||
|
||||
@ -8,7 +8,7 @@ use thiserror::Error;
|
||||
pub struct AddressParser {}
|
||||
|
||||
impl clap::builder::TypedValueParser for AddressParser {
|
||||
type Value = [u8; 20];
|
||||
type Value = Address;
|
||||
|
||||
fn parse_ref(
|
||||
&self,
|
||||
@ -21,14 +21,20 @@ impl clap::builder::TypedValueParser for AddressParser {
|
||||
})?;
|
||||
|
||||
let stripped_value = str.strip_prefix("0x").unwrap_or(str);
|
||||
let bytes = hex::decode(stripped_value).map_err(|_| {
|
||||
let mut bytes: [u8; 20] = [0; 20];
|
||||
|
||||
let decoded_hex = hex::decode(stripped_value).map_err(|_| {
|
||||
clap::Error::new(clap::error::ErrorKind::InvalidValue)
|
||||
})?;
|
||||
let bytes_len = bytes.len() - 1;
|
||||
for (i, b) in decoded_hex.into_iter().enumerate() {
|
||||
if i == bytes.len() {
|
||||
break;
|
||||
}
|
||||
bytes[bytes_len - i] = b;
|
||||
}
|
||||
|
||||
let mut addr = [0u8; 20];
|
||||
|
||||
addr.copy_from_slice(&bytes[..12]);
|
||||
Ok(addr)
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
10
testing/tauri/test/.gitignore
vendored
@ -1,10 +0,0 @@
|
||||
.DS_Store
|
||||
node_modules
|
||||
/build
|
||||
/.svelte-kit
|
||||
/package
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
7
testing/tauri/test/.vscode/extensions.json
vendored
@ -1,7 +0,0 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"svelte.svelte-vscode",
|
||||
"tauri-apps.tauri-vscode",
|
||||
"rust-lang.rust-analyzer"
|
||||
]
|
||||
}
|
||||
3
testing/tauri/test/.vscode/settings.json
vendored
@ -1,3 +0,0 @@
|
||||
{
|
||||
"svelte.enable-ts-plugin": true
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
# Tauri + SvelteKit + TypeScript
|
||||
|
||||
This template should help get you started developing with Tauri, SvelteKit and TypeScript in Vite.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).
|
||||
@ -1,16 +0,0 @@
|
||||
{
|
||||
"$schema": "https://shadcn-svelte.com/schema.json",
|
||||
"tailwind": {
|
||||
"css": "src/app.css",
|
||||
"baseColor": "zinc"
|
||||
},
|
||||
"aliases": {
|
||||
"components": "$lib/components",
|
||||
"utils": "$lib/utils",
|
||||
"ui": "$lib/components/ui",
|
||||
"hooks": "$lib/hooks",
|
||||
"lib": "$lib"
|
||||
},
|
||||
"typescript": true,
|
||||
"registry": "https://shadcn-svelte.com/registry"
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
{
|
||||
"name": "test",
|
||||
"version": "0.1.0",
|
||||
"description": "",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||
"tauri": "export WEBKIT_DISABLE_COMPOSITING_MODE=1; tauri"
|
||||
},
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.1.13",
|
||||
"@tauri-apps/api": "^2",
|
||||
"@tauri-apps/plugin-opener": "^2",
|
||||
"tailwindcss": "^4.1.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@lucide/svelte": "^0.544.0",
|
||||
"@sveltejs/adapter-static": "^3.0.6",
|
||||
"@sveltejs/kit": "^2.9.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.0",
|
||||
"@tauri-apps/cli": "^2",
|
||||
"clsx": "^2.1.1",
|
||||
"svelte": "^5.0.0",
|
||||
"svelte-check": "^4.0.0",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwind-variants": "^3.1.1",
|
||||
"tw-animate-css": "^1.3.8",
|
||||
"typescript": "~5.6.2",
|
||||
"vite": "^6.0.3"
|
||||
}
|
||||
}
|
||||
1545
testing/tauri/test/pnpm-lock.yaml
generated
7
testing/tauri/test/src-tauri/.gitignore
vendored
@ -1,7 +0,0 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Generated by Tauri
|
||||
# will have schema files for capabilities auto-completion
|
||||
/gen/schemas
|
||||
5286
testing/tauri/test/src-tauri/Cargo.lock
generated
@ -1,25 +0,0 @@
|
||||
[package]
|
||||
name = "test"
|
||||
version = "0.1.0"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[lib]
|
||||
# The `_lib` suffix may seem redundant but it is necessary
|
||||
# to make the lib name unique and wouldn't conflict with the bin name.
|
||||
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
|
||||
name = "test_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-opener = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
@ -1,3 +0,0 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@ -1,10 +0,0 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"opener:default"
|
||||
]
|
||||
}
|
||||
|
Before Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 974 B |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 903 B |
|
Before Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 14 KiB |
@ -1,14 +0,0 @@
|
||||
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
|
||||
#[tauri::command]
|
||||
fn greet(name: &str) -> String {
|
||||
format!("Hello, {}! You've been greeted from Rust!", name)
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.invoke_handler(tauri::generate_handler![greet])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
test_lib::run()
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "test",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.test.app",
|
||||
"build": {
|
||||
"beforeDevCommand": " pnpm dev",
|
||||
"devUrl": "http://localhost:1420",
|
||||
"beforeBuildCommand": "pnpm build",
|
||||
"frontendDist": "../build"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "test",
|
||||
"width": 800,
|
||||
"height": 600
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
}
|
||||
}
|
||||
@ -1,121 +0,0 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.141 0.005 285.823);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.141 0.005 285.823);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.141 0.005 285.823);
|
||||
--primary: oklch(0.21 0.006 285.885);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.967 0.001 286.375);
|
||||
--secondary-foreground: oklch(0.21 0.006 285.885);
|
||||
--muted: oklch(0.967 0.001 286.375);
|
||||
--muted-foreground: oklch(0.552 0.016 285.938);
|
||||
--accent: oklch(0.967 0.001 286.375);
|
||||
--accent-foreground: oklch(0.21 0.006 285.885);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.92 0.004 286.32);
|
||||
--input: oklch(0.92 0.004 286.32);
|
||||
--ring: oklch(0.705 0.015 286.067);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.141 0.005 285.823);
|
||||
--sidebar-primary: oklch(0.21 0.006 285.885);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.967 0.001 286.375);
|
||||
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
|
||||
--sidebar-border: oklch(0.92 0.004 286.32);
|
||||
--sidebar-ring: oklch(0.705 0.015 286.067);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.141 0.005 285.823);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.21 0.006 285.885);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.21 0.006 285.885);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.92 0.004 286.32);
|
||||
--primary-foreground: oklch(0.21 0.006 285.885);
|
||||
--secondary: oklch(0.274 0.006 286.033);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.274 0.006 286.033);
|
||||
--muted-foreground: oklch(0.705 0.015 286.067);
|
||||
--accent: oklch(0.274 0.006 286.033);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.552 0.016 285.938);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.21 0.006 285.885);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.274 0.006 286.033);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.552 0.016 285.938);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Tauri + SvelteKit + Typescript App</title>
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
@ -1,13 +0,0 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export type WithoutChild<T> = T extends { child?: any } ? Omit<T, "child"> : T;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export type WithoutChildren<T> = T extends { children?: any } ? Omit<T, "children"> : T;
|
||||
export type WithoutChildrenOrChild<T> = WithoutChildren<WithoutChild<T>>;
|
||||
export type WithElementRef<T, U extends HTMLElement = HTMLElement> = T & { ref?: U | null };
|
||||
@ -1,7 +0,0 @@
|
||||
<script lang="ts">
|
||||
import "../app.css";
|
||||
|
||||
let { children } = $props();
|
||||
</script>
|
||||
|
||||
{@render children()}
|
||||
@ -1,5 +0,0 @@
|
||||
// Tauri doesn't have a Node.js server to do proper SSR
|
||||
// so we will use adapter-static to prerender the app (SSG)
|
||||
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
|
||||
export const prerender = true;
|
||||
export const ssr = false;
|
||||
@ -1,105 +0,0 @@
|
||||
<!-- Telegram-like UI in Svelte with Tailwind -->
|
||||
<script lang="ts">
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
|
||||
let currentChat = 'John Doe';
|
||||
let message = '';
|
||||
let messages = [
|
||||
{ id: 1, text: 'Hey there!', own: false },
|
||||
{ id: 2, text: 'Hi! How are you?', own: true },
|
||||
{ id: 3, text: "I'm doing great, thanks for asking!", own: false }
|
||||
];
|
||||
|
||||
let chats = [
|
||||
{ name: 'John Doe', preview: 'Hey, how are you?', active: true },
|
||||
{ name: 'Alice Smith', preview: 'See you tomorrow!', active: false },
|
||||
{ name: 'Bob Wilson', preview: 'Thanks for the help!', active: false }
|
||||
];
|
||||
|
||||
async function sendMessage() {
|
||||
if (!message.trim()) return;
|
||||
|
||||
messages = [...messages, {
|
||||
id: Date.now(),
|
||||
text: message,
|
||||
own: true
|
||||
}];
|
||||
|
||||
// Call Tauri backend
|
||||
try {
|
||||
await invoke('send_message', { content: message });
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
}
|
||||
|
||||
message = '';
|
||||
}
|
||||
|
||||
function selectChat(chatName: string) {
|
||||
chats = chats.map(chat => ({
|
||||
...chat,
|
||||
active: chat.name === chatName
|
||||
}));
|
||||
currentChat = chatName;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex h-screen bg-slate-900">
|
||||
<!-- Sidebar -->
|
||||
<div class="w-80 bg-slate-800 text-white border-r border-slate-700">
|
||||
<!-- Sidebar Header -->
|
||||
<div class="p-5 border-b border-slate-700">
|
||||
<h3 class="text-lg font-semibold">Chats</h3>
|
||||
</div>
|
||||
|
||||
<!-- Chat List -->
|
||||
<div class="overflow-y-auto h-[calc(100vh-80px)]">
|
||||
{#each chats as chat}
|
||||
<button
|
||||
class="px-5 w-full text-start py-3 border-b border-slate-700 cursor-pointer hover:bg-slate-700 transition-colors {chat.active ? 'bg-slate-700' : ''}"
|
||||
on:click={() => selectChat(chat.name)}
|
||||
tabindex="0"
|
||||
>
|
||||
<div class="font-medium mb-1">{chat.name}</div>
|
||||
<div class="text-gray-400 text-sm">{chat.preview}</div>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Chat Area -->
|
||||
<div class="flex-1 flex flex-col bg-slate-900">
|
||||
<!-- Chat Header -->
|
||||
<div class="p-4 bg-slate-800 border-b border-slate-700 text-white">
|
||||
<h3 class="text-lg font-semibold">{currentChat}</h3>
|
||||
</div>
|
||||
|
||||
<!-- Messages -->
|
||||
<div class="flex-1 p-5 overflow-y-auto bg-slate-900">
|
||||
{#each messages as msg}
|
||||
<div class="mb-4 max-w-[70%] {msg.own ? 'ml-auto text-right' : ''}">
|
||||
<div class="inline-block px-3 py-2 rounded-xl text-white {msg.own ? 'bg-blue-600' : 'bg-slate-700'}">
|
||||
{msg.text}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- Input Area -->
|
||||
<div class="p-4 bg-slate-800 border-t border-slate-700 flex gap-3">
|
||||
<input
|
||||
type="text"
|
||||
bind:value={message}
|
||||
on:keydown={(e) => e.key === 'Enter' && sendMessage()}
|
||||
placeholder="Type a message..."
|
||||
class="flex-1 px-4 py-2 bg-slate-900 border border-slate-600 rounded-full text-white placeholder-gray-400 outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<button
|
||||
on:click={sendMessage}
|
||||
class="w-10 h-10 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors flex items-center justify-center"
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.9 KiB |
@ -1,6 +0,0 @@
|
||||
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
@ -1,15 +0,0 @@
|
||||
// Tauri doesn't have a Node.js server to do proper SSR
|
||||
// so we will use adapter-static to prerender the app (SSG)
|
||||
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
|
||||
import adapter from "@sveltejs/adapter-static";
|
||||
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
|
||||
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
preprocess: vitePreprocess(),
|
||||
kit: {
|
||||
adapter: adapter(),
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@ -1,23 +0,0 @@
|
||||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"moduleResolution": "bundler",
|
||||
"paths": {
|
||||
"$lib": ["./src/lib"],
|
||||
"$lib/*": ["./src/lib/*"]
|
||||
}
|
||||
}
|
||||
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
|
||||
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
|
||||
//
|
||||
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
|
||||
// from the referenced tsconfig.json - TypeScript does not merge them in
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
import { defineConfig } from "vite";
|
||||
import { sveltekit } from "@sveltejs/kit/vite";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
|
||||
// @ts-expect-error process is a nodejs global
|
||||
const host = process.env.TAURI_DEV_HOST;
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig(async () => ({
|
||||
plugins: [tailwindcss(), sveltekit()],
|
||||
|
||||
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
|
||||
//
|
||||
// 1. prevent vite from obscuring rust errors
|
||||
clearScreen: false,
|
||||
// 2. tauri expects a fixed port, fail if that port is not available
|
||||
server: {
|
||||
port: 1420,
|
||||
strictPort: true,
|
||||
host: host || false,
|
||||
hmr: host
|
||||
? {
|
||||
protocol: "ws",
|
||||
host,
|
||||
port: 1421,
|
||||
}
|
||||
: undefined,
|
||||
watch: {
|
||||
// 3. tell vite to ignore watching `src-tauri`
|
||||
ignored: ["**/src-tauri/**"],
|
||||
},
|
||||
},
|
||||
}));
|
||||