Skip to content

Commit 8a0153a

Browse files
JuArceOppen
authored andcommitted
feat: support tls in batcher connections [wip]
1 parent 58ab842 commit 8a0153a

File tree

7 files changed

+106
-12
lines changed

7 files changed

+106
-12
lines changed

Makefile

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,10 +304,15 @@ batcher_start: ./batcher/aligned-batcher/.env user_fund_payment_service
304304
@echo "Starting Batcher..."
305305
@cargo run --manifest-path ./batcher/aligned-batcher/Cargo.toml --release -- --config ./config-files/config-batcher.yaml --env-file ./batcher/aligned-batcher/.env
306306

307-
batcher_start_local: user_fund_payment_service
307+
batcher_create_self_signed_cert:
308+
@echo "Creating TLS certificate for localhost"
309+
@openssl req -x509 -days 1825 -newkey rsa:2048 -keyout rootCA.key -out rootCA.crt -nodes -subj '/CN=localhost'
310+
@echo "TLS certificate created"
311+
312+
batcher_start_local: user_fund_payment_service batcher_create_self_signed_cert
308313
@echo "Starting Batcher..."
309314
@$(MAKE) run_storage &
310-
@cargo run --manifest-path ./batcher/aligned-batcher/Cargo.toml --release -- --config ./config-files/config-batcher.yaml --env-file ./batcher/aligned-batcher/.env.dev
315+
@cargo run --manifest-path ./batcher/aligned-batcher/Cargo.toml --release -- --config ./config-files/config-batcher.yaml --env-file ./batcher/aligned-batcher/.env.dev --cert ./rootCA.crt --key ./rootCA.key
311316

312317
batcher_start_local_no_fund:
313318
@echo "Starting Batcher..."

batcher/Cargo.lock

Lines changed: 66 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

batcher/aligned-batcher/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,5 @@ once_cell = "1.20.2"
3434
warp = "0.3.7"
3535
prometheus = { version = "0.13.4", features = ["process"] }
3636
backon = "1.2.0"
37+
tokio-boring = "4.13.0"
38+
boring = "4.13.0"

batcher/aligned-batcher/src/connection.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::sync::Arc;
2+
use boring::ssl::{SslStream};
23

34
use crate::types::{batch_queue::BatchQueueEntry, errors::BatcherError};
45
use aligned_sdk::{
@@ -15,7 +16,7 @@ use tokio_tungstenite::{
1516
WebSocketStream,
1617
};
1718

18-
pub(crate) type WsMessageSink = Arc<RwLock<SplitSink<WebSocketStream<TcpStream>, Message>>>;
19+
pub(crate) type WsMessageSink = Arc<RwLock<SplitSink<WebSocketStream<SslStream<TcpStream>>, Message>>>;
1920

2021
pub(crate) async fn send_batch_inclusion_data_responses(
2122
finalized_batch: Vec<BatchQueueEntry>,

batcher/aligned-batcher/src/lib.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@ use retry::{retry_function, RetryError};
1414
use tokio::time::timeout;
1515
use types::batch_state::BatchState;
1616
use types::user_state::UserState;
17-
17+
use boring::ssl::{SslMethod, SslAcceptor, SslStream, SslFiletype};
1818
use std::collections::HashMap;
1919
use std::env;
2020
use std::net::SocketAddr;
21+
use std::path::PathBuf;
2122
use std::sync::Arc;
2223
use std::time::Duration;
2324

@@ -260,7 +261,14 @@ impl Batcher {
260261
}
261262
}
262263

263-
pub async fn listen_connections(self: Arc<Self>, address: &str) -> Result<(), BatcherError> {
264+
pub async fn listen_connections(self: Arc<Self>, address: &str, cert: PathBuf, key: PathBuf) -> Result<(), BatcherError> {
265+
let mut acceptor;
266+
let mut acceptor_builder = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
267+
acceptor_builder.set_private_key_file(key, SslFiletype::PEM).unwrap();
268+
acceptor_builder.set_certificate_chain_file(cert).unwrap();
269+
acceptor_builder.check_private_key().unwrap();
270+
acceptor = Arc::new(acceptor_builder.build());
271+
264272
// Create the event loop and TCP listener we'll accept connections on.
265273
let listener = TcpListener::bind(address)
266274
.await
@@ -272,7 +280,7 @@ impl Batcher {
272280
Ok((stream, addr)) => {
273281
let batcher = self.clone();
274282
// Let's spawn the handling of each connection in a separate task.
275-
tokio::spawn(batcher.handle_connection(stream, addr));
283+
tokio::spawn(batcher.handle_connection(stream, addr, acceptor.clone()));
276284
}
277285
Err(e) => {
278286
self.metrics.user_error(&["connection_accept_error", ""]);
@@ -366,11 +374,14 @@ impl Batcher {
366374
self: Arc<Self>,
367375
raw_stream: TcpStream,
368376
addr: SocketAddr,
377+
acceptor: Arc<SslAcceptor>,
369378
) -> Result<(), BatcherError> {
370379
info!("Incoming TCP connection from: {}", addr);
371380
self.metrics.open_connections.inc();
372-
373-
let ws_stream_future = tokio_tungstenite::accept_async(raw_stream);
381+
let tls_stream = tokio_boring::accept(&acceptor, raw_stream)
382+
.await
383+
.map_err(|e | BatcherError::TlsError(e.to_string()))?;
384+
let ws_stream_future = tokio_tungstenite::accept_async(tls_stream);
374385
let ws_stream =
375386
match timeout(Duration::from_secs(CONNECTION_TIMEOUT), ws_stream_future).await {
376387
Ok(Ok(stream)) => stream,

batcher/aligned-batcher/src/main.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
extern crate dotenvy;
22

3+
use std::path::PathBuf;
34
use std::sync::Arc;
4-
55
use clap::Parser;
66
use env_logger::Env;
77

@@ -24,6 +24,12 @@ struct Cli {
2424
env_file: Option<String>,
2525
#[arg(short, long)]
2626
port: Option<u16>,
27+
/// cert file
28+
#[argh(option, short = 'c')]
29+
cert: PathBuf,
30+
/// key file
31+
#[argh(option, short = 'k')]
32+
key: PathBuf,
2733
}
2834

2935
#[tokio::main]
@@ -40,8 +46,6 @@ async fn main() -> Result<(), BatcherError> {
4046
let batcher = Batcher::new(cli.config).await;
4147
let batcher = Arc::new(batcher);
4248

43-
let addr = format!("localhost:{}", port);
44-
4549
// spawn task to listening for incoming blocks
4650
tokio::spawn({
4751
let app = batcher.clone();
@@ -54,7 +58,8 @@ async fn main() -> Result<(), BatcherError> {
5458

5559
batcher.metrics.inc_batcher_restart();
5660

57-
batcher.listen_connections(&addr).await?;
61+
let addr = format!("localhost:{}", port);
62+
batcher.listen_connections(&addr, cli.cert, cli.key).await?;
5863

5964
Ok(())
6065
}

batcher/aligned-batcher/src/types/errors.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use ethers::types::{Address, SignatureError};
44
use tokio_tungstenite::tungstenite;
55

66
pub enum BatcherError {
7+
TlsError(String),
78
TcpListenerError(String),
89
ConnectionError(tungstenite::Error),
910
BatchVerifiedEventStreamError(String),
@@ -37,6 +38,9 @@ impl From<SignatureError> for BatcherError {
3738
impl fmt::Debug for BatcherError {
3839
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3940
match self {
41+
BatcherError::TlsError(e) => {
42+
write!(f, "TLS Handshake error: {}", e)
43+
}
4044
BatcherError::TcpListenerError(e) => {
4145
write!(f, "TCP Listener error: {}", e)
4246
}

0 commit comments

Comments
 (0)