Skip to content

Commit 1455452

Browse files
committed
Pre-allocate send buffer when forwarding gossip
When forwarding gossip, rather than relying on Vec doubling, pre-allocate the message encoding buffer.
1 parent abee51b commit 1455452

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

lightning/src/ln/peer_channel_encryptor.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ use core::ops::Deref;
3434
/// and [BOLT-1](https://github.com/lightning/bolts/blob/master/01-messaging.md#lightning-message-format):
3535
pub const LN_MAX_MSG_LEN: usize = ::core::u16::MAX as usize; // Must be equal to 65535
3636

37+
/// The (rough) size buffer to pre-allocate when encoding a message. Messages should reliably be
38+
/// smaller than this size by at least 32 bytes or so.
39+
pub const MSG_BUF_ALLOC_SIZE: usize = 2048;
40+
3741
// Sha256("Noise_XK_secp256k1_ChaChaPoly_SHA256")
3842
const NOISE_CK: [u8; 32] = [0x26, 0x40, 0xf5, 0x2e, 0xeb, 0xcd, 0x9e, 0x88, 0x29, 0x58, 0x95, 0x1c, 0x79, 0x42, 0x50, 0xee, 0xdb, 0x28, 0x00, 0x2c, 0x05, 0xd7, 0xdc, 0x2e, 0xa0, 0xf1, 0x95, 0x40, 0x60, 0x42, 0xca, 0xf1];
3943
// Sha256(NOISE_CK || "lightning")
@@ -448,7 +452,7 @@ impl PeerChannelEncryptor {
448452
pub fn encrypt_message<M: wire::Type>(&mut self, message: &M) -> Vec<u8> {
449453
// Allocate a buffer with 2KB, fitting most common messages. Reserve the first 16+2 bytes
450454
// for the 2-byte message type prefix and its MAC.
451-
let mut res = VecWriter(Vec::with_capacity(2048));
455+
let mut res = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
452456
res.0.resize(16 + 2, 0);
453457
wire::write(message, &mut res).expect("In-memory messages must never fail to serialize");
454458

lightning/src/ln/peer_handler.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use crate::ln::msgs::{ChannelMessageHandler, LightningError, SocketAddress, Onio
2727
#[cfg(not(c_bindings))]
2828
use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
2929
use crate::util::ser::{VecWriter, Writeable, Writer};
30-
use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
30+
use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor, NextNoiseStep, MSG_BUF_ALLOC_SIZE};
3131
use crate::ln::wire;
3232
use crate::ln::wire::{Encode, Type};
3333
#[cfg(not(c_bindings))]
@@ -785,7 +785,7 @@ impl From<LightningError> for MessageHandlingError {
785785

786786
macro_rules! encode_msg {
787787
($msg: expr) => {{
788-
let mut buffer = VecWriter(Vec::new());
788+
let mut buffer = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
789789
wire::write($msg, &mut buffer).unwrap();
790790
buffer.0
791791
}}

0 commit comments

Comments
 (0)