Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
eb6a371
build scaffold for handshake module substitution support
arik-so Feb 12, 2020
b71b7ea
change peer_handler.rs to use modular handshake and encryption handle…
arik-so Feb 12, 2020
92eac9b
make ephemeral private key explicit for handshake (todo: remove it fr…
arik-so Feb 12, 2020
986f25f
remove import of rand
arik-so Feb 12, 2020
ffbf5ec
make linter complain less about docs
arik-so Feb 12, 2020
19b7700
allocate act messages without vector prevarication
arik-so Feb 13, 2020
17fda75
reduce vector allocations for message encryption
arik-so Feb 13, 2020
8169b31
address some of Jeff's comments pertaining to message decryption, con…
arik-so Feb 19, 2020
f1002c5
Use type standin for remaining act lengths when parsing. Use the same…
arik-so Feb 19, 2020
f0fc10b
Improve comments and type aliasing for handshake module.
arik-so Feb 20, 2020
eb297f9
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
5492717
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
256b6f5
Reflect new modular encryption mechanism in tock ping message creation.
arik-so Feb 20, 2020
b4921e9
Elaborate on lightning codec in conduit's decrypt method.
arik-so Feb 21, 2020
299b6f7
Split up conduit unit tests by tested functionality.
arik-so Feb 21, 2020
944177a
Make handshake store the remote public key instead of passing an opti…
arik-so Feb 21, 2020
0fbd895
Panic when attempting invalid state transitions.
arik-so Feb 27, 2020
6cf5a07
Merge branch 'master' into modular_handshake
arik-so Mar 12, 2020
6f4e76a
Group peer handler's connected state checks instead of repeating them…
arik-so Mar 12, 2020
c2227b6
Fix missing init message send upon connection initiation.
arik-so Mar 13, 2020
6bae489
Merge branch 'master' into modular_handshake
arik-so Apr 9, 2020
2df93ca
fix some unit tests
arik-so Apr 9, 2020
eda13bf
Disconnect peer if act message is too short.
arik-so Apr 9, 2020
4e6b25a
Replace unwrapping public keys with handleable errors in handshake mo…
arik-so Apr 9, 2020
f1940e9
Merge branch 'master' into modular_handshake
arik-so Apr 11, 2020
4deb290
Split conduit into encryptor and decryptor components (to allow for b…
arik-so Apr 30, 2020
5e9c350
Fix conduit constructor bugs and revert indentation for message proce…
arik-so Apr 30, 2020
4b4cb98
Merge remote-tracking branch 'upstream/master' into modular_handshake
arik-so Apr 30, 2020
029bb66
Replace hashing and secp256k1 dependencies with components of the bit…
arik-so Apr 30, 2020
54b7464
Restrict conduit borrow scope for compatibility with Rust 1.22.0.
arik-so Apr 30, 2020
fe705a9
Fix lightning-net-tokio peer handler import.
arik-so Apr 30, 2020
be5e2a5
Apply message handling extraction to relocated peer handler.
arik-so Jun 12, 2020
2e4e659
Merge branch 'master' into modular_handshake
arik-so Jun 12, 2020
a4fff76
Fix unit tests
arik-so Jun 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions lightning-net-tokio/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//! type PeerManager = lightning::ln::peers::handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//!
//! // Connect to node with pubkey their_node_id at addr:
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
Expand DownExpand Up@@ -68,8 +68,8 @@ use tokio::{io, time};
use tokio::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

use lightning::ln::peer_handler;
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::peers::handler;
use lightning::ln::peers::handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use lightning::util::logger::Logger;

Expand DownExpand Up@@ -124,7 +124,7 @@ impl Connection {
_ => panic!()
}
}
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -237,7 +237,7 @@ impl Connection {
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -279,7 +279,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -351,7 +351,7 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
/// make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -402,7 +402,7 @@ impl SocketDescriptor {
Self { conn, id }
}
}
impl peer_handler::SocketDescriptor for SocketDescriptor {
impl handler::SocketDescriptor for SocketDescriptor {
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
// To send data, we take a lock on our Connection to access the WriteHalf of the TcpStream,
// writing to it if there's room in the kernel buffer, or otherwise create a new Waker with
Expand DownExpand Up@@ -494,7 +494,7 @@ impl Hash for SocketDescriptor {
mod tests {
use lightning::ln::features::*;
use lightning::ln::msgs::*;
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
use lightning::ln::peers::handler::{MessageHandler, PeerManager};
use lightning::util::events::*;
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@
pub mod channelmanager;
pub mod channelmonitor;
pub mod msgs;
pub mod peer_handler;
pub mod peers;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this up one so its not in ln? If we're gonna put almost everything in one top-level module, it seems like we should just not have that module :).

pub mod chan_utils;
pub mod features;
pub(crate) mod onchaintx;
Expand Down
40 changes: 40 additions & 0 deletions lightning/src/ln/peers/chacha.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
use util::byte_utils;
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in ln::peers? It seems to be pure crypto functions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the AEAD-based encryption methods are only used for handshakes and peer message encryption IIRC, and not for the onion construction.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but its also a pure-crypto primitive. I guess my preference is for such things (even if it implements a lightning protocol crypto primitive) to be in some kind of crypto module.

pub const TAG_SIZE: usize = 16;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like there's a few places where this can be used throughout the file.


pub fn encrypt(key: &[u8], nonce: u64, associated_data: &[u8], plaintext: &[u8]) -> Vec<u8> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut ciphertext = vec![0u8; plaintext.len()];
let mut authentication_tag = [0u8; 16];
chacha.encrypt(plaintext, &mut ciphertext, &mut authentication_tag);

let mut tagged_ciphertext = ciphertext;
tagged_ciphertext.extend_from_slice(&authentication_tag);
tagged_ciphertext
}

pub fn decrypt(key: &[u8], nonce: u64, associated_data: &[u8], tagged_ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let length = tagged_ciphertext.len();
if length < 16 {
return Err("ciphertext cannot be shorter than tag length of 16 bytes".to_string());
}
let end_index = length - 16;
let ciphertext = &tagged_ciphertext[0..end_index];
let authentication_tag = &tagged_ciphertext[end_index..length];

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut plaintext = vec![0u8; length - 16];
let success = chacha.decrypt(ciphertext, &mut plaintext, authentication_tag);
if success {
Ok(plaintext.to_vec())
} else {
Err("invalid hmac".to_string())
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Modular handshake by arik-so · Pull Request #494 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
eb6a371
build scaffold for handshake module substitution support
arik-so Feb 12, 2020
b71b7ea
change peer_handler.rs to use modular handshake and encryption handle…
arik-so Feb 12, 2020
92eac9b
make ephemeral private key explicit for handshake (todo: remove it fr…
arik-so Feb 12, 2020
986f25f
remove import of rand
arik-so Feb 12, 2020
ffbf5ec
make linter complain less about docs
arik-so Feb 12, 2020
19b7700
allocate act messages without vector prevarication
arik-so Feb 13, 2020
17fda75
reduce vector allocations for message encryption
arik-so Feb 13, 2020
8169b31
address some of Jeff's comments pertaining to message decryption, con…
arik-so Feb 19, 2020
f1002c5
Use type standin for remaining act lengths when parsing. Use the same…
arik-so Feb 19, 2020
f0fc10b
Improve comments and type aliasing for handshake module.
arik-so Feb 20, 2020
eb297f9
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
5492717
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
256b6f5
Reflect new modular encryption mechanism in tock ping message creation.
arik-so Feb 20, 2020
b4921e9
Elaborate on lightning codec in conduit's decrypt method.
arik-so Feb 21, 2020
299b6f7
Split up conduit unit tests by tested functionality.
arik-so Feb 21, 2020
944177a
Make handshake store the remote public key instead of passing an opti…
arik-so Feb 21, 2020
0fbd895
Panic when attempting invalid state transitions.
arik-so Feb 27, 2020
6cf5a07
Merge branch 'master' into modular_handshake
arik-so Mar 12, 2020
6f4e76a
Group peer handler's connected state checks instead of repeating them…
arik-so Mar 12, 2020
c2227b6
Fix missing init message send upon connection initiation.
arik-so Mar 13, 2020
6bae489
Merge branch 'master' into modular_handshake
arik-so Apr 9, 2020
2df93ca
fix some unit tests
arik-so Apr 9, 2020
eda13bf
Disconnect peer if act message is too short.
arik-so Apr 9, 2020
4e6b25a
Replace unwrapping public keys with handleable errors in handshake mo…
arik-so Apr 9, 2020
f1940e9
Merge branch 'master' into modular_handshake
arik-so Apr 11, 2020
4deb290
Split conduit into encryptor and decryptor components (to allow for b…
arik-so Apr 30, 2020
5e9c350
Fix conduit constructor bugs and revert indentation for message proce…
arik-so Apr 30, 2020
4b4cb98
Merge remote-tracking branch 'upstream/master' into modular_handshake
arik-so Apr 30, 2020
029bb66
Replace hashing and secp256k1 dependencies with components of the bit…
arik-so Apr 30, 2020
54b7464
Restrict conduit borrow scope for compatibility with Rust 1.22.0.
arik-so Apr 30, 2020
fe705a9
Fix lightning-net-tokio peer handler import.
arik-so Apr 30, 2020
be5e2a5
Apply message handling extraction to relocated peer handler.
arik-so Jun 12, 2020
2e4e659
Merge branch 'master' into modular_handshake
arik-so Jun 12, 2020
a4fff76
Fix unit tests
arik-so Jun 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions lightning-net-tokio/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//! type PeerManager = lightning::ln::peers::handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//!
//! // Connect to node with pubkey their_node_id at addr:
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
Expand DownExpand Up@@ -68,8 +68,8 @@ use tokio::{io, time};
use tokio::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

use lightning::ln::peer_handler;
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::peers::handler;
use lightning::ln::peers::handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use lightning::util::logger::Logger;

Expand DownExpand Up@@ -124,7 +124,7 @@ impl Connection {
_ => panic!()
}
}
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -237,7 +237,7 @@ impl Connection {
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -279,7 +279,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -351,7 +351,7 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
/// make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -402,7 +402,7 @@ impl SocketDescriptor {
Self { conn, id }
}
}
impl peer_handler::SocketDescriptor for SocketDescriptor {
impl handler::SocketDescriptor for SocketDescriptor {
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
// To send data, we take a lock on our Connection to access the WriteHalf of the TcpStream,
// writing to it if there's room in the kernel buffer, or otherwise create a new Waker with
Expand DownExpand Up@@ -494,7 +494,7 @@ impl Hash for SocketDescriptor {
mod tests {
use lightning::ln::features::*;
use lightning::ln::msgs::*;
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
use lightning::ln::peers::handler::{MessageHandler, PeerManager};
use lightning::util::events::*;
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@
pub mod channelmanager;
pub mod channelmonitor;
pub mod msgs;
pub mod peer_handler;
pub mod peers;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this up one so its not in ln? If we're gonna put almost everything in one top-level module, it seems like we should just not have that module :).

pub mod chan_utils;
pub mod features;
pub(crate) mod onchaintx;
Expand Down
40 changes: 40 additions & 0 deletions lightning/src/ln/peers/chacha.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
use util::byte_utils;
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in ln::peers? It seems to be pure crypto functions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the AEAD-based encryption methods are only used for handshakes and peer message encryption IIRC, and not for the onion construction.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but its also a pure-crypto primitive. I guess my preference is for such things (even if it implements a lightning protocol crypto primitive) to be in some kind of crypto module.

pub const TAG_SIZE: usize = 16;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like there's a few places where this can be used throughout the file.


pub fn encrypt(key: &[u8], nonce: u64, associated_data: &[u8], plaintext: &[u8]) -> Vec<u8> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut ciphertext = vec![0u8; plaintext.len()];
let mut authentication_tag = [0u8; 16];
chacha.encrypt(plaintext, &mut ciphertext, &mut authentication_tag);

let mut tagged_ciphertext = ciphertext;
tagged_ciphertext.extend_from_slice(&authentication_tag);
tagged_ciphertext
}

pub fn decrypt(key: &[u8], nonce: u64, associated_data: &[u8], tagged_ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let length = tagged_ciphertext.len();
if length < 16 {
return Err("ciphertext cannot be shorter than tag length of 16 bytes".to_string());
}
let end_index = length - 16;
let ciphertext = &tagged_ciphertext[0..end_index];
let authentication_tag = &tagged_ciphertext[end_index..length];

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut plaintext = vec![0u8; length - 16];
let success = chacha.decrypt(ciphertext, &mut plaintext, authentication_tag);
if success {
Ok(plaintext.to_vec())
} else {
Err("invalid hmac".to_string())
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Modular handshake by arik-so · Pull Request #494 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
eb6a371
build scaffold for handshake module substitution support
arik-so Feb 12, 2020
b71b7ea
change peer_handler.rs to use modular handshake and encryption handle…
arik-so Feb 12, 2020
92eac9b
make ephemeral private key explicit for handshake (todo: remove it fr…
arik-so Feb 12, 2020
986f25f
remove import of rand
arik-so Feb 12, 2020
ffbf5ec
make linter complain less about docs
arik-so Feb 12, 2020
19b7700
allocate act messages without vector prevarication
arik-so Feb 13, 2020
17fda75
reduce vector allocations for message encryption
arik-so Feb 13, 2020
8169b31
address some of Jeff's comments pertaining to message decryption, con…
arik-so Feb 19, 2020
f1002c5
Use type standin for remaining act lengths when parsing. Use the same…
arik-so Feb 19, 2020
f0fc10b
Improve comments and type aliasing for handshake module.
arik-so Feb 20, 2020
eb297f9
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
5492717
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
256b6f5
Reflect new modular encryption mechanism in tock ping message creation.
arik-so Feb 20, 2020
b4921e9
Elaborate on lightning codec in conduit's decrypt method.
arik-so Feb 21, 2020
299b6f7
Split up conduit unit tests by tested functionality.
arik-so Feb 21, 2020
944177a
Make handshake store the remote public key instead of passing an opti…
arik-so Feb 21, 2020
0fbd895
Panic when attempting invalid state transitions.
arik-so Feb 27, 2020
6cf5a07
Merge branch 'master' into modular_handshake
arik-so Mar 12, 2020
6f4e76a
Group peer handler's connected state checks instead of repeating them…
arik-so Mar 12, 2020
c2227b6
Fix missing init message send upon connection initiation.
arik-so Mar 13, 2020
6bae489
Merge branch 'master' into modular_handshake
arik-so Apr 9, 2020
2df93ca
fix some unit tests
arik-so Apr 9, 2020
eda13bf
Disconnect peer if act message is too short.
arik-so Apr 9, 2020
4e6b25a
Replace unwrapping public keys with handleable errors in handshake mo…
arik-so Apr 9, 2020
f1940e9
Merge branch 'master' into modular_handshake
arik-so Apr 11, 2020
4deb290
Split conduit into encryptor and decryptor components (to allow for b…
arik-so Apr 30, 2020
5e9c350
Fix conduit constructor bugs and revert indentation for message proce…
arik-so Apr 30, 2020
4b4cb98
Merge remote-tracking branch 'upstream/master' into modular_handshake
arik-so Apr 30, 2020
029bb66
Replace hashing and secp256k1 dependencies with components of the bit…
arik-so Apr 30, 2020
54b7464
Restrict conduit borrow scope for compatibility with Rust 1.22.0.
arik-so Apr 30, 2020
fe705a9
Fix lightning-net-tokio peer handler import.
arik-so Apr 30, 2020
be5e2a5
Apply message handling extraction to relocated peer handler.
arik-so Jun 12, 2020
2e4e659
Merge branch 'master' into modular_handshake
arik-so Jun 12, 2020
a4fff76
Fix unit tests
arik-so Jun 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions lightning-net-tokio/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//! type PeerManager = lightning::ln::peers::handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//!
//! // Connect to node with pubkey their_node_id at addr:
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
Expand DownExpand Up@@ -68,8 +68,8 @@ use tokio::{io, time};
use tokio::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

use lightning::ln::peer_handler;
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::peers::handler;
use lightning::ln::peers::handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use lightning::util::logger::Logger;

Expand DownExpand Up@@ -124,7 +124,7 @@ impl Connection {
_ => panic!()
}
}
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -237,7 +237,7 @@ impl Connection {
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -279,7 +279,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -351,7 +351,7 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
/// make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -402,7 +402,7 @@ impl SocketDescriptor {
Self { conn, id }
}
}
impl peer_handler::SocketDescriptor for SocketDescriptor {
impl handler::SocketDescriptor for SocketDescriptor {
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
// To send data, we take a lock on our Connection to access the WriteHalf of the TcpStream,
// writing to it if there's room in the kernel buffer, or otherwise create a new Waker with
Expand DownExpand Up@@ -494,7 +494,7 @@ impl Hash for SocketDescriptor {
mod tests {
use lightning::ln::features::*;
use lightning::ln::msgs::*;
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
use lightning::ln::peers::handler::{MessageHandler, PeerManager};
use lightning::util::events::*;
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@
pub mod channelmanager;
pub mod channelmonitor;
pub mod msgs;
pub mod peer_handler;
pub mod peers;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this up one so its not in ln? If we're gonna put almost everything in one top-level module, it seems like we should just not have that module :).

pub mod chan_utils;
pub mod features;
pub(crate) mod onchaintx;
Expand Down
40 changes: 40 additions & 0 deletions lightning/src/ln/peers/chacha.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
use util::byte_utils;
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in ln::peers? It seems to be pure crypto functions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the AEAD-based encryption methods are only used for handshakes and peer message encryption IIRC, and not for the onion construction.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but its also a pure-crypto primitive. I guess my preference is for such things (even if it implements a lightning protocol crypto primitive) to be in some kind of crypto module.

pub const TAG_SIZE: usize = 16;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like there's a few places where this can be used throughout the file.


pub fn encrypt(key: &[u8], nonce: u64, associated_data: &[u8], plaintext: &[u8]) -> Vec<u8> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut ciphertext = vec![0u8; plaintext.len()];
let mut authentication_tag = [0u8; 16];
chacha.encrypt(plaintext, &mut ciphertext, &mut authentication_tag);

let mut tagged_ciphertext = ciphertext;
tagged_ciphertext.extend_from_slice(&authentication_tag);
tagged_ciphertext
}

pub fn decrypt(key: &[u8], nonce: u64, associated_data: &[u8], tagged_ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let length = tagged_ciphertext.len();
if length < 16 {
return Err("ciphertext cannot be shorter than tag length of 16 bytes".to_string());
}
let end_index = length - 16;
let ciphertext = &tagged_ciphertext[0..end_index];
let authentication_tag = &tagged_ciphertext[end_index..length];

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut plaintext = vec![0u8; length - 16];
let success = chacha.decrypt(ciphertext, &mut plaintext, authentication_tag);
if success {
Ok(plaintext.to_vec())
} else {
Err("invalid hmac".to_string())
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Modular handshake by arik-so · Pull Request #494 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
eb6a371
build scaffold for handshake module substitution support
arik-so Feb 12, 2020
b71b7ea
change peer_handler.rs to use modular handshake and encryption handle…
arik-so Feb 12, 2020
92eac9b
make ephemeral private key explicit for handshake (todo: remove it fr…
arik-so Feb 12, 2020
986f25f
remove import of rand
arik-so Feb 12, 2020
ffbf5ec
make linter complain less about docs
arik-so Feb 12, 2020
19b7700
allocate act messages without vector prevarication
arik-so Feb 13, 2020
17fda75
reduce vector allocations for message encryption
arik-so Feb 13, 2020
8169b31
address some of Jeff's comments pertaining to message decryption, con…
arik-so Feb 19, 2020
f1002c5
Use type standin for remaining act lengths when parsing. Use the same…
arik-so Feb 19, 2020
f0fc10b
Improve comments and type aliasing for handshake module.
arik-so Feb 20, 2020
eb297f9
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
5492717
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
256b6f5
Reflect new modular encryption mechanism in tock ping message creation.
arik-so Feb 20, 2020
b4921e9
Elaborate on lightning codec in conduit's decrypt method.
arik-so Feb 21, 2020
299b6f7
Split up conduit unit tests by tested functionality.
arik-so Feb 21, 2020
944177a
Make handshake store the remote public key instead of passing an opti…
arik-so Feb 21, 2020
0fbd895
Panic when attempting invalid state transitions.
arik-so Feb 27, 2020
6cf5a07
Merge branch 'master' into modular_handshake
arik-so Mar 12, 2020
6f4e76a
Group peer handler's connected state checks instead of repeating them…
arik-so Mar 12, 2020
c2227b6
Fix missing init message send upon connection initiation.
arik-so Mar 13, 2020
6bae489
Merge branch 'master' into modular_handshake
arik-so Apr 9, 2020
2df93ca
fix some unit tests
arik-so Apr 9, 2020
eda13bf
Disconnect peer if act message is too short.
arik-so Apr 9, 2020
4e6b25a
Replace unwrapping public keys with handleable errors in handshake mo…
arik-so Apr 9, 2020
f1940e9
Merge branch 'master' into modular_handshake
arik-so Apr 11, 2020
4deb290
Split conduit into encryptor and decryptor components (to allow for b…
arik-so Apr 30, 2020
5e9c350
Fix conduit constructor bugs and revert indentation for message proce…
arik-so Apr 30, 2020
4b4cb98
Merge remote-tracking branch 'upstream/master' into modular_handshake
arik-so Apr 30, 2020
029bb66
Replace hashing and secp256k1 dependencies with components of the bit…
arik-so Apr 30, 2020
54b7464
Restrict conduit borrow scope for compatibility with Rust 1.22.0.
arik-so Apr 30, 2020
fe705a9
Fix lightning-net-tokio peer handler import.
arik-so Apr 30, 2020
be5e2a5
Apply message handling extraction to relocated peer handler.
arik-so Jun 12, 2020
2e4e659
Merge branch 'master' into modular_handshake
arik-so Jun 12, 2020
a4fff76
Fix unit tests
arik-so Jun 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions lightning-net-tokio/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//! type PeerManager = lightning::ln::peers::handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//!
//! // Connect to node with pubkey their_node_id at addr:
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
Expand DownExpand Up@@ -68,8 +68,8 @@ use tokio::{io, time};
use tokio::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

use lightning::ln::peer_handler;
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::peers::handler;
use lightning::ln::peers::handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use lightning::util::logger::Logger;

Expand DownExpand Up@@ -124,7 +124,7 @@ impl Connection {
_ => panic!()
}
}
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -237,7 +237,7 @@ impl Connection {
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -279,7 +279,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -351,7 +351,7 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
/// make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -402,7 +402,7 @@ impl SocketDescriptor {
Self { conn, id }
}
}
impl peer_handler::SocketDescriptor for SocketDescriptor {
impl handler::SocketDescriptor for SocketDescriptor {
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
// To send data, we take a lock on our Connection to access the WriteHalf of the TcpStream,
// writing to it if there's room in the kernel buffer, or otherwise create a new Waker with
Expand DownExpand Up@@ -494,7 +494,7 @@ impl Hash for SocketDescriptor {
mod tests {
use lightning::ln::features::*;
use lightning::ln::msgs::*;
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
use lightning::ln::peers::handler::{MessageHandler, PeerManager};
use lightning::util::events::*;
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@
pub mod channelmanager;
pub mod channelmonitor;
pub mod msgs;
pub mod peer_handler;
pub mod peers;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this up one so its not in ln? If we're gonna put almost everything in one top-level module, it seems like we should just not have that module :).

pub mod chan_utils;
pub mod features;
pub(crate) mod onchaintx;
Expand Down
40 changes: 40 additions & 0 deletions lightning/src/ln/peers/chacha.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
use util::byte_utils;
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in ln::peers? It seems to be pure crypto functions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the AEAD-based encryption methods are only used for handshakes and peer message encryption IIRC, and not for the onion construction.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but its also a pure-crypto primitive. I guess my preference is for such things (even if it implements a lightning protocol crypto primitive) to be in some kind of crypto module.

pub const TAG_SIZE: usize = 16;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like there's a few places where this can be used throughout the file.


pub fn encrypt(key: &[u8], nonce: u64, associated_data: &[u8], plaintext: &[u8]) -> Vec<u8> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut ciphertext = vec![0u8; plaintext.len()];
let mut authentication_tag = [0u8; 16];
chacha.encrypt(plaintext, &mut ciphertext, &mut authentication_tag);

let mut tagged_ciphertext = ciphertext;
tagged_ciphertext.extend_from_slice(&authentication_tag);
tagged_ciphertext
}

pub fn decrypt(key: &[u8], nonce: u64, associated_data: &[u8], tagged_ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let length = tagged_ciphertext.len();
if length < 16 {
return Err("ciphertext cannot be shorter than tag length of 16 bytes".to_string());
}
let end_index = length - 16;
let ciphertext = &tagged_ciphertext[0..end_index];
let authentication_tag = &tagged_ciphertext[end_index..length];

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut plaintext = vec![0u8; length - 16];
let success = chacha.decrypt(ciphertext, &mut plaintext, authentication_tag);
if success {
Ok(plaintext.to_vec())
} else {
Err("invalid hmac".to_string())
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Modular handshake by arik-so · Pull Request #494 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
eb6a371
build scaffold for handshake module substitution support
arik-so Feb 12, 2020
b71b7ea
change peer_handler.rs to use modular handshake and encryption handle…
arik-so Feb 12, 2020
92eac9b
make ephemeral private key explicit for handshake (todo: remove it fr…
arik-so Feb 12, 2020
986f25f
remove import of rand
arik-so Feb 12, 2020
ffbf5ec
make linter complain less about docs
arik-so Feb 12, 2020
19b7700
allocate act messages without vector prevarication
arik-so Feb 13, 2020
17fda75
reduce vector allocations for message encryption
arik-so Feb 13, 2020
8169b31
address some of Jeff's comments pertaining to message decryption, con…
arik-so Feb 19, 2020
f1002c5
Use type standin for remaining act lengths when parsing. Use the same…
arik-so Feb 19, 2020
f0fc10b
Improve comments and type aliasing for handshake module.
arik-so Feb 20, 2020
eb297f9
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
5492717
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
256b6f5
Reflect new modular encryption mechanism in tock ping message creation.
arik-so Feb 20, 2020
b4921e9
Elaborate on lightning codec in conduit's decrypt method.
arik-so Feb 21, 2020
299b6f7
Split up conduit unit tests by tested functionality.
arik-so Feb 21, 2020
944177a
Make handshake store the remote public key instead of passing an opti…
arik-so Feb 21, 2020
0fbd895
Panic when attempting invalid state transitions.
arik-so Feb 27, 2020
6cf5a07
Merge branch 'master' into modular_handshake
arik-so Mar 12, 2020
6f4e76a
Group peer handler's connected state checks instead of repeating them…
arik-so Mar 12, 2020
c2227b6
Fix missing init message send upon connection initiation.
arik-so Mar 13, 2020
6bae489
Merge branch 'master' into modular_handshake
arik-so Apr 9, 2020
2df93ca
fix some unit tests
arik-so Apr 9, 2020
eda13bf
Disconnect peer if act message is too short.
arik-so Apr 9, 2020
4e6b25a
Replace unwrapping public keys with handleable errors in handshake mo…
arik-so Apr 9, 2020
f1940e9
Merge branch 'master' into modular_handshake
arik-so Apr 11, 2020
4deb290
Split conduit into encryptor and decryptor components (to allow for b…
arik-so Apr 30, 2020
5e9c350
Fix conduit constructor bugs and revert indentation for message proce…
arik-so Apr 30, 2020
4b4cb98
Merge remote-tracking branch 'upstream/master' into modular_handshake
arik-so Apr 30, 2020
029bb66
Replace hashing and secp256k1 dependencies with components of the bit…
arik-so Apr 30, 2020
54b7464
Restrict conduit borrow scope for compatibility with Rust 1.22.0.
arik-so Apr 30, 2020
fe705a9
Fix lightning-net-tokio peer handler import.
arik-so Apr 30, 2020
be5e2a5
Apply message handling extraction to relocated peer handler.
arik-so Jun 12, 2020
2e4e659
Merge branch 'master' into modular_handshake
arik-so Jun 12, 2020
a4fff76
Fix unit tests
arik-so Jun 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions lightning-net-tokio/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//! type PeerManager = lightning::ln::peers::handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//!
//! // Connect to node with pubkey their_node_id at addr:
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
Expand DownExpand Up@@ -68,8 +68,8 @@ use tokio::{io, time};
use tokio::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

use lightning::ln::peer_handler;
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::peers::handler;
use lightning::ln::peers::handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use lightning::util::logger::Logger;

Expand DownExpand Up@@ -124,7 +124,7 @@ impl Connection {
_ => panic!()
}
}
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -237,7 +237,7 @@ impl Connection {
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -279,7 +279,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -351,7 +351,7 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
/// make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -402,7 +402,7 @@ impl SocketDescriptor {
Self { conn, id }
}
}
impl peer_handler::SocketDescriptor for SocketDescriptor {
impl handler::SocketDescriptor for SocketDescriptor {
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
// To send data, we take a lock on our Connection to access the WriteHalf of the TcpStream,
// writing to it if there's room in the kernel buffer, or otherwise create a new Waker with
Expand DownExpand Up@@ -494,7 +494,7 @@ impl Hash for SocketDescriptor {
mod tests {
use lightning::ln::features::*;
use lightning::ln::msgs::*;
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
use lightning::ln::peers::handler::{MessageHandler, PeerManager};
use lightning::util::events::*;
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@
pub mod channelmanager;
pub mod channelmonitor;
pub mod msgs;
pub mod peer_handler;
pub mod peers;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this up one so its not in ln? If we're gonna put almost everything in one top-level module, it seems like we should just not have that module :).

pub mod chan_utils;
pub mod features;
pub(crate) mod onchaintx;
Expand Down
40 changes: 40 additions & 0 deletions lightning/src/ln/peers/chacha.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
use util::byte_utils;
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in ln::peers? It seems to be pure crypto functions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the AEAD-based encryption methods are only used for handshakes and peer message encryption IIRC, and not for the onion construction.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but its also a pure-crypto primitive. I guess my preference is for such things (even if it implements a lightning protocol crypto primitive) to be in some kind of crypto module.

pub const TAG_SIZE: usize = 16;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like there's a few places where this can be used throughout the file.


pub fn encrypt(key: &[u8], nonce: u64, associated_data: &[u8], plaintext: &[u8]) -> Vec<u8> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut ciphertext = vec![0u8; plaintext.len()];
let mut authentication_tag = [0u8; 16];
chacha.encrypt(plaintext, &mut ciphertext, &mut authentication_tag);

let mut tagged_ciphertext = ciphertext;
tagged_ciphertext.extend_from_slice(&authentication_tag);
tagged_ciphertext
}

pub fn decrypt(key: &[u8], nonce: u64, associated_data: &[u8], tagged_ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let length = tagged_ciphertext.len();
if length < 16 {
return Err("ciphertext cannot be shorter than tag length of 16 bytes".to_string());
}
let end_index = length - 16;
let ciphertext = &tagged_ciphertext[0..end_index];
let authentication_tag = &tagged_ciphertext[end_index..length];

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut plaintext = vec![0u8; length - 16];
let success = chacha.decrypt(ciphertext, &mut plaintext, authentication_tag);
if success {
Ok(plaintext.to_vec())
} else {
Err("invalid hmac".to_string())
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Modular handshake by arik-so · Pull Request #494 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
eb6a371
build scaffold for handshake module substitution support
arik-so Feb 12, 2020
b71b7ea
change peer_handler.rs to use modular handshake and encryption handle…
arik-so Feb 12, 2020
92eac9b
make ephemeral private key explicit for handshake (todo: remove it fr…
arik-so Feb 12, 2020
986f25f
remove import of rand
arik-so Feb 12, 2020
ffbf5ec
make linter complain less about docs
arik-so Feb 12, 2020
19b7700
allocate act messages without vector prevarication
arik-so Feb 13, 2020
17fda75
reduce vector allocations for message encryption
arik-so Feb 13, 2020
8169b31
address some of Jeff's comments pertaining to message decryption, con…
arik-so Feb 19, 2020
f1002c5
Use type standin for remaining act lengths when parsing. Use the same…
arik-so Feb 19, 2020
f0fc10b
Improve comments and type aliasing for handshake module.
arik-so Feb 20, 2020
eb297f9
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
5492717
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
256b6f5
Reflect new modular encryption mechanism in tock ping message creation.
arik-so Feb 20, 2020
b4921e9
Elaborate on lightning codec in conduit's decrypt method.
arik-so Feb 21, 2020
299b6f7
Split up conduit unit tests by tested functionality.
arik-so Feb 21, 2020
944177a
Make handshake store the remote public key instead of passing an opti…
arik-so Feb 21, 2020
0fbd895
Panic when attempting invalid state transitions.
arik-so Feb 27, 2020
6cf5a07
Merge branch 'master' into modular_handshake
arik-so Mar 12, 2020
6f4e76a
Group peer handler's connected state checks instead of repeating them…
arik-so Mar 12, 2020
c2227b6
Fix missing init message send upon connection initiation.
arik-so Mar 13, 2020
6bae489
Merge branch 'master' into modular_handshake
arik-so Apr 9, 2020
2df93ca
fix some unit tests
arik-so Apr 9, 2020
eda13bf
Disconnect peer if act message is too short.
arik-so Apr 9, 2020
4e6b25a
Replace unwrapping public keys with handleable errors in handshake mo…
arik-so Apr 9, 2020
f1940e9
Merge branch 'master' into modular_handshake
arik-so Apr 11, 2020
4deb290
Split conduit into encryptor and decryptor components (to allow for b…
arik-so Apr 30, 2020
5e9c350
Fix conduit constructor bugs and revert indentation for message proce…
arik-so Apr 30, 2020
4b4cb98
Merge remote-tracking branch 'upstream/master' into modular_handshake
arik-so Apr 30, 2020
029bb66
Replace hashing and secp256k1 dependencies with components of the bit…
arik-so Apr 30, 2020
54b7464
Restrict conduit borrow scope for compatibility with Rust 1.22.0.
arik-so Apr 30, 2020
fe705a9
Fix lightning-net-tokio peer handler import.
arik-so Apr 30, 2020
be5e2a5
Apply message handling extraction to relocated peer handler.
arik-so Jun 12, 2020
2e4e659
Merge branch 'master' into modular_handshake
arik-so Jun 12, 2020
a4fff76
Fix unit tests
arik-so Jun 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions lightning-net-tokio/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//! type PeerManager = lightning::ln::peers::handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//!
//! // Connect to node with pubkey their_node_id at addr:
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
Expand DownExpand Up@@ -68,8 +68,8 @@ use tokio::{io, time};
use tokio::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

use lightning::ln::peer_handler;
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::peers::handler;
use lightning::ln::peers::handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use lightning::util::logger::Logger;

Expand DownExpand Up@@ -124,7 +124,7 @@ impl Connection {
_ => panic!()
}
}
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -237,7 +237,7 @@ impl Connection {
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -279,7 +279,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -351,7 +351,7 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
/// make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -402,7 +402,7 @@ impl SocketDescriptor {
Self { conn, id }
}
}
impl peer_handler::SocketDescriptor for SocketDescriptor {
impl handler::SocketDescriptor for SocketDescriptor {
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
// To send data, we take a lock on our Connection to access the WriteHalf of the TcpStream,
// writing to it if there's room in the kernel buffer, or otherwise create a new Waker with
Expand DownExpand Up@@ -494,7 +494,7 @@ impl Hash for SocketDescriptor {
mod tests {
use lightning::ln::features::*;
use lightning::ln::msgs::*;
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
use lightning::ln::peers::handler::{MessageHandler, PeerManager};
use lightning::util::events::*;
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@
pub mod channelmanager;
pub mod channelmonitor;
pub mod msgs;
pub mod peer_handler;
pub mod peers;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this up one so its not in ln? If we're gonna put almost everything in one top-level module, it seems like we should just not have that module :).

pub mod chan_utils;
pub mod features;
pub(crate) mod onchaintx;
Expand Down
40 changes: 40 additions & 0 deletions lightning/src/ln/peers/chacha.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
use util::byte_utils;
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in ln::peers? It seems to be pure crypto functions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the AEAD-based encryption methods are only used for handshakes and peer message encryption IIRC, and not for the onion construction.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but its also a pure-crypto primitive. I guess my preference is for such things (even if it implements a lightning protocol crypto primitive) to be in some kind of crypto module.

pub const TAG_SIZE: usize = 16;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like there's a few places where this can be used throughout the file.


pub fn encrypt(key: &[u8], nonce: u64, associated_data: &[u8], plaintext: &[u8]) -> Vec<u8> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut ciphertext = vec![0u8; plaintext.len()];
let mut authentication_tag = [0u8; 16];
chacha.encrypt(plaintext, &mut ciphertext, &mut authentication_tag);

let mut tagged_ciphertext = ciphertext;
tagged_ciphertext.extend_from_slice(&authentication_tag);
tagged_ciphertext
}

pub fn decrypt(key: &[u8], nonce: u64, associated_data: &[u8], tagged_ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let length = tagged_ciphertext.len();
if length < 16 {
return Err("ciphertext cannot be shorter than tag length of 16 bytes".to_string());
}
let end_index = length - 16;
let ciphertext = &tagged_ciphertext[0..end_index];
let authentication_tag = &tagged_ciphertext[end_index..length];

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut plaintext = vec![0u8; length - 16];
let success = chacha.decrypt(ciphertext, &mut plaintext, authentication_tag);
if success {
Ok(plaintext.to_vec())
} else {
Err("invalid hmac".to_string())
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Modular handshake by arik-so · Pull Request #494 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
eb6a371
build scaffold for handshake module substitution support
arik-so Feb 12, 2020
b71b7ea
change peer_handler.rs to use modular handshake and encryption handle…
arik-so Feb 12, 2020
92eac9b
make ephemeral private key explicit for handshake (todo: remove it fr…
arik-so Feb 12, 2020
986f25f
remove import of rand
arik-so Feb 12, 2020
ffbf5ec
make linter complain less about docs
arik-so Feb 12, 2020
19b7700
allocate act messages without vector prevarication
arik-so Feb 13, 2020
17fda75
reduce vector allocations for message encryption
arik-so Feb 13, 2020
8169b31
address some of Jeff's comments pertaining to message decryption, con…
arik-so Feb 19, 2020
f1002c5
Use type standin for remaining act lengths when parsing. Use the same…
arik-so Feb 19, 2020
f0fc10b
Improve comments and type aliasing for handshake module.
arik-so Feb 20, 2020
eb297f9
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
5492717
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
256b6f5
Reflect new modular encryption mechanism in tock ping message creation.
arik-so Feb 20, 2020
b4921e9
Elaborate on lightning codec in conduit's decrypt method.
arik-so Feb 21, 2020
299b6f7
Split up conduit unit tests by tested functionality.
arik-so Feb 21, 2020
944177a
Make handshake store the remote public key instead of passing an opti…
arik-so Feb 21, 2020
0fbd895
Panic when attempting invalid state transitions.
arik-so Feb 27, 2020
6cf5a07
Merge branch 'master' into modular_handshake
arik-so Mar 12, 2020
6f4e76a
Group peer handler's connected state checks instead of repeating them…
arik-so Mar 12, 2020
c2227b6
Fix missing init message send upon connection initiation.
arik-so Mar 13, 2020
6bae489
Merge branch 'master' into modular_handshake
arik-so Apr 9, 2020
2df93ca
fix some unit tests
arik-so Apr 9, 2020
eda13bf
Disconnect peer if act message is too short.
arik-so Apr 9, 2020
4e6b25a
Replace unwrapping public keys with handleable errors in handshake mo…
arik-so Apr 9, 2020
f1940e9
Merge branch 'master' into modular_handshake
arik-so Apr 11, 2020
4deb290
Split conduit into encryptor and decryptor components (to allow for b…
arik-so Apr 30, 2020
5e9c350
Fix conduit constructor bugs and revert indentation for message proce…
arik-so Apr 30, 2020
4b4cb98
Merge remote-tracking branch 'upstream/master' into modular_handshake
arik-so Apr 30, 2020
029bb66
Replace hashing and secp256k1 dependencies with components of the bit…
arik-so Apr 30, 2020
54b7464
Restrict conduit borrow scope for compatibility with Rust 1.22.0.
arik-so Apr 30, 2020
fe705a9
Fix lightning-net-tokio peer handler import.
arik-so Apr 30, 2020
be5e2a5
Apply message handling extraction to relocated peer handler.
arik-so Jun 12, 2020
2e4e659
Merge branch 'master' into modular_handshake
arik-so Jun 12, 2020
a4fff76
Fix unit tests
arik-so Jun 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions lightning-net-tokio/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//! type PeerManager = lightning::ln::peers::handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//!
//! // Connect to node with pubkey their_node_id at addr:
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
Expand DownExpand Up@@ -68,8 +68,8 @@ use tokio::{io, time};
use tokio::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

use lightning::ln::peer_handler;
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::peers::handler;
use lightning::ln::peers::handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use lightning::util::logger::Logger;

Expand DownExpand Up@@ -124,7 +124,7 @@ impl Connection {
_ => panic!()
}
}
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -237,7 +237,7 @@ impl Connection {
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -279,7 +279,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -351,7 +351,7 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
/// make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -402,7 +402,7 @@ impl SocketDescriptor {
Self { conn, id }
}
}
impl peer_handler::SocketDescriptor for SocketDescriptor {
impl handler::SocketDescriptor for SocketDescriptor {
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
// To send data, we take a lock on our Connection to access the WriteHalf of the TcpStream,
// writing to it if there's room in the kernel buffer, or otherwise create a new Waker with
Expand DownExpand Up@@ -494,7 +494,7 @@ impl Hash for SocketDescriptor {
mod tests {
use lightning::ln::features::*;
use lightning::ln::msgs::*;
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
use lightning::ln::peers::handler::{MessageHandler, PeerManager};
use lightning::util::events::*;
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@
pub mod channelmanager;
pub mod channelmonitor;
pub mod msgs;
pub mod peer_handler;
pub mod peers;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this up one so its not in ln? If we're gonna put almost everything in one top-level module, it seems like we should just not have that module :).

pub mod chan_utils;
pub mod features;
pub(crate) mod onchaintx;
Expand Down
40 changes: 40 additions & 0 deletions lightning/src/ln/peers/chacha.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
use util::byte_utils;
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in ln::peers? It seems to be pure crypto functions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the AEAD-based encryption methods are only used for handshakes and peer message encryption IIRC, and not for the onion construction.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but its also a pure-crypto primitive. I guess my preference is for such things (even if it implements a lightning protocol crypto primitive) to be in some kind of crypto module.

pub const TAG_SIZE: usize = 16;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like there's a few places where this can be used throughout the file.


pub fn encrypt(key: &[u8], nonce: u64, associated_data: &[u8], plaintext: &[u8]) -> Vec<u8> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut ciphertext = vec![0u8; plaintext.len()];
let mut authentication_tag = [0u8; 16];
chacha.encrypt(plaintext, &mut ciphertext, &mut authentication_tag);

let mut tagged_ciphertext = ciphertext;
tagged_ciphertext.extend_from_slice(&authentication_tag);
tagged_ciphertext
}

pub fn decrypt(key: &[u8], nonce: u64, associated_data: &[u8], tagged_ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let length = tagged_ciphertext.len();
if length < 16 {
return Err("ciphertext cannot be shorter than tag length of 16 bytes".to_string());
}
let end_index = length - 16;
let ciphertext = &tagged_ciphertext[0..end_index];
let authentication_tag = &tagged_ciphertext[end_index..length];

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut plaintext = vec![0u8; length - 16];
let success = chacha.decrypt(ciphertext, &mut plaintext, authentication_tag);
if success {
Ok(plaintext.to_vec())
} else {
Err("invalid hmac".to_string())
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Modular handshake by arik-so · Pull Request #494 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
eb6a371
build scaffold for handshake module substitution support
arik-so Feb 12, 2020
b71b7ea
change peer_handler.rs to use modular handshake and encryption handle…
arik-so Feb 12, 2020
92eac9b
make ephemeral private key explicit for handshake (todo: remove it fr…
arik-so Feb 12, 2020
986f25f
remove import of rand
arik-so Feb 12, 2020
ffbf5ec
make linter complain less about docs
arik-so Feb 12, 2020
19b7700
allocate act messages without vector prevarication
arik-so Feb 13, 2020
17fda75
reduce vector allocations for message encryption
arik-so Feb 13, 2020
8169b31
address some of Jeff's comments pertaining to message decryption, con…
arik-so Feb 19, 2020
f1002c5
Use type standin for remaining act lengths when parsing. Use the same…
arik-so Feb 19, 2020
f0fc10b
Improve comments and type aliasing for handshake module.
arik-so Feb 20, 2020
eb297f9
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
5492717
Merge branch 'master' into modular_handshake
arik-so Feb 20, 2020
256b6f5
Reflect new modular encryption mechanism in tock ping message creation.
arik-so Feb 20, 2020
b4921e9
Elaborate on lightning codec in conduit's decrypt method.
arik-so Feb 21, 2020
299b6f7
Split up conduit unit tests by tested functionality.
arik-so Feb 21, 2020
944177a
Make handshake store the remote public key instead of passing an opti…
arik-so Feb 21, 2020
0fbd895
Panic when attempting invalid state transitions.
arik-so Feb 27, 2020
6cf5a07
Merge branch 'master' into modular_handshake
arik-so Mar 12, 2020
6f4e76a
Group peer handler's connected state checks instead of repeating them…
arik-so Mar 12, 2020
c2227b6
Fix missing init message send upon connection initiation.
arik-so Mar 13, 2020
6bae489
Merge branch 'master' into modular_handshake
arik-so Apr 9, 2020
2df93ca
fix some unit tests
arik-so Apr 9, 2020
eda13bf
Disconnect peer if act message is too short.
arik-so Apr 9, 2020
4e6b25a
Replace unwrapping public keys with handleable errors in handshake mo…
arik-so Apr 9, 2020
f1940e9
Merge branch 'master' into modular_handshake
arik-so Apr 11, 2020
4deb290
Split conduit into encryptor and decryptor components (to allow for b…
arik-so Apr 30, 2020
5e9c350
Fix conduit constructor bugs and revert indentation for message proce…
arik-so Apr 30, 2020
4b4cb98
Merge remote-tracking branch 'upstream/master' into modular_handshake
arik-so Apr 30, 2020
029bb66
Replace hashing and secp256k1 dependencies with components of the bit…
arik-so Apr 30, 2020
54b7464
Restrict conduit borrow scope for compatibility with Rust 1.22.0.
arik-so Apr 30, 2020
fe705a9
Fix lightning-net-tokio peer handler import.
arik-so Apr 30, 2020
be5e2a5
Apply message handling extraction to relocated peer handler.
arik-so Jun 12, 2020
2e4e659
Merge branch 'master' into modular_handshake
arik-so Jun 12, 2020
a4fff76
Fix unit tests
arik-so Jun 13, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions fuzz/src/full_stack.rs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions lightning-net-tokio/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@
//! type ChainWatchInterface = dyn lightning::chain::chaininterface::ChainWatchInterface;
//! type ChannelMonitor = lightning::ln::channelmonitor::SimpleManyChannelMonitor<lightning::chain::transaction::OutPoint, lightning::chain::keysinterface::InMemoryChannelKeys, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<ChainWatchInterface>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChannelMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//! type PeerManager = lightning::ln::peers::handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChannelMonitor, TxBroadcaster, FeeEstimator, ChainWatchInterface, Logger>;
//!
//! // Connect to node with pubkey their_node_id at addr:
//! async fn connect_to_node(peer_manager: PeerManager, channel_monitor: Arc<ChannelMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
Expand DownExpand Up@@ -68,8 +68,8 @@ use tokio::{io, time};
use tokio::sync::mpsc;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

use lightning::ln::peer_handler;
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::peers::handler;
use lightning::ln::peers::handler::SocketDescriptor as LnSocketTrait;
use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler};
use lightning::util::logger::Logger;

Expand DownExpand Up@@ -124,7 +124,7 @@ impl Connection {
_ => panic!()
}
}
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
async fn schedule_read<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, us: Arc<Mutex<Self>>, mut reader: io::ReadHalf<TcpStream>, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -237,7 +237,7 @@ impl Connection {
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -279,7 +279,7 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
/// not need to poll the provided future in order to make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, stream: TcpStream) -> impl std::future::Future<Output=()> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -351,7 +351,7 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
/// make progress.
///
/// See the module-level documentation for how to handle the event_notify mpsc::Sender.
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
pub async fn connect_outbound<CMH, RMH, L>(peer_manager: Arc<handler::PeerManager<SocketDescriptor, Arc<CMH>, Arc<RMH>, Arc<L>>>, event_notify: mpsc::Sender<()>, their_node_id: PublicKey, addr: SocketAddr) -> Option<impl std::future::Future<Output=()>> where
CMH: ChannelMessageHandler + 'static,
RMH: RoutingMessageHandler + 'static,
L: Logger + 'static + ?Sized {
Expand DownExpand Up@@ -402,7 +402,7 @@ impl SocketDescriptor {
Self { conn, id }
}
}
impl peer_handler::SocketDescriptor for SocketDescriptor {
impl handler::SocketDescriptor for SocketDescriptor {
fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize {
// To send data, we take a lock on our Connection to access the WriteHalf of the TcpStream,
// writing to it if there's room in the kernel buffer, or otherwise create a new Waker with
Expand DownExpand Up@@ -494,7 +494,7 @@ impl Hash for SocketDescriptor {
mod tests {
use lightning::ln::features::*;
use lightning::ln::msgs::*;
use lightning::ln::peer_handler::{MessageHandler, PeerManager};
use lightning::ln::peers::handler::{MessageHandler, PeerManager};
use lightning::util::events::*;
use bitcoin::secp256k1::{Secp256k1, SecretKey, PublicKey};

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@
pub mod channelmanager;
pub mod channelmonitor;
pub mod msgs;
pub mod peer_handler;
pub mod peers;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this up one so its not in ln? If we're gonna put almost everything in one top-level module, it seems like we should just not have that module :).

pub mod chan_utils;
pub mod features;
pub(crate) mod onchaintx;
Expand Down
40 changes: 40 additions & 0 deletions lightning/src/ln/peers/chacha.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
use util::byte_utils;
use util::chacha20poly1305rfc::ChaCha20Poly1305RFC;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this in ln::peers? It seems to be pure crypto functions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the AEAD-based encryption methods are only used for handshakes and peer message encryption IIRC, and not for the onion construction.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but its also a pure-crypto primitive. I guess my preference is for such things (even if it implements a lightning protocol crypto primitive) to be in some kind of crypto module.

pub const TAG_SIZE: usize = 16;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like there's a few places where this can be used throughout the file.


pub fn encrypt(key: &[u8], nonce: u64, associated_data: &[u8], plaintext: &[u8]) -> Vec<u8> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut ciphertext = vec![0u8; plaintext.len()];
let mut authentication_tag = [0u8; 16];
chacha.encrypt(plaintext, &mut ciphertext, &mut authentication_tag);

let mut tagged_ciphertext = ciphertext;
tagged_ciphertext.extend_from_slice(&authentication_tag);
tagged_ciphertext
}

pub fn decrypt(key: &[u8], nonce: u64, associated_data: &[u8], tagged_ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let mut nonce_bytes = [0; 12];
nonce_bytes[4..].copy_from_slice(&byte_utils::le64_to_array(nonce));

let length = tagged_ciphertext.len();
if length < 16 {
return Err("ciphertext cannot be shorter than tag length of 16 bytes".to_string());
}
let end_index = length - 16;
let ciphertext = &tagged_ciphertext[0..end_index];
let authentication_tag = &tagged_ciphertext[end_index..length];

let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce_bytes, associated_data);
let mut plaintext = vec![0u8; length - 16];
let success = chacha.decrypt(ciphertext, &mut plaintext, authentication_tag);
if success {
Ok(plaintext.to_vec())
} else {
Err("invalid hmac".to_string())
}
}
Loading