diff --git a/smite-ir/src/builder.rs b/smite-ir/src/builder.rs index 9697893a..bd779440 100644 --- a/smite-ir/src/builder.rs +++ b/smite-ir/src/builder.rs @@ -157,6 +157,9 @@ impl ProgramBuilder { } VariableType::PrivateKey => self.append(Operation::LoadPrivateKey(rng.random()), &[]), VariableType::ChannelId => self.append(Operation::LoadChannelId(rng.random()), &[]), + VariableType::ShortChannelId => { + self.append(Operation::LoadShortChannelId(rng.random()), &[]) + } VariableType::ChainHash => self.append(Operation::LoadChainHashFromContext, &[]), VariableType::Point => { let sk_idx = self.generate_fresh(VariableType::PrivateKey, rng); diff --git a/smite-ir/src/mutators/operation_param.rs b/smite-ir/src/mutators/operation_param.rs index 80cc6fd3..91fb7849 100644 --- a/smite-ir/src/mutators/operation_param.rs +++ b/smite-ir/src/mutators/operation_param.rs @@ -2,7 +2,7 @@ use rand::seq::IteratorRandom; use rand::{Rng, RngExt}; -use smite::bolt::MAX_MESSAGE_SIZE; +use smite::bolt::{MAX_MESSAGE_SIZE, ShortChannelId}; use super::Mutator; use crate::operation::{AcceptChannelField, ChannelTypeVariant, ShutdownScriptVariant}; @@ -37,6 +37,10 @@ fn mutate_operation(op: &mut Operation, rng: &mut impl Rng) -> bool { *v = tweak_u64(*v, rng); true } + Operation::LoadShortChannelId(v) => { + *v = tweak_short_channel_id(*v, rng); + true + } Operation::LoadFeeratePerKw(v) | Operation::LoadBlockHeight(v) | Operation::LoadTimestamp(v) => { @@ -141,6 +145,44 @@ fn tweak_u8(v: u8, rng: &mut impl Rng) -> u8 { } } +// -- Short channel id mutations -- + +/// Mutates a packed BOLT 7 `short_channel_id`. +/// +/// Unlike a plain u64 tweak, this picks values that are interesting at the +/// component level (`block` / `tx_index` / `output_index`), since most SCID +/// parsing and validation logic is sensitive to those boundaries rather than +/// to the packed integer as a whole. +fn tweak_short_channel_id(v: u64, rng: &mut impl Rng) -> u64 { + let scid = ShortChannelId::from_u64(v); + let block = scid.block(); + let tx_index = scid.tx_index(); + let output_index = scid.output_index(); + + match rng.random_range(0..8) { + // Replace with an SCID at a known interesting boundary. + 0 => interesting_scid(rng).as_u64(), + // Replace just the block component with an interesting value. + 1 => ShortChannelId::new(interesting_scid_u24(rng), tx_index, output_index).as_u64(), + // Replace just the tx_index component with an interesting value. + 2 => ShortChannelId::new(block, interesting_scid_u24(rng), output_index).as_u64(), + // Replace just the output_index component with an interesting value. + 3 => ShortChannelId::new(block, tx_index, interesting_u16(rng)).as_u64(), + // Build a fully random but well-formed SCID. + 4 => ShortChannelId::new( + rng.random_range(0..=ShortChannelId::MAX_BLOCK), + rng.random_range(0..=ShortChannelId::MAX_TX_INDEX), + rng.random(), + ) + .as_u64(), + // Small delta on the packed form: may straddle component boundaries. + 5 => v.wrapping_add(rng.random_range(1..=256)), + 6 => v.wrapping_sub(rng.random_range(1..=256)), + // Fully random u64 (may exceed valid component ranges). + _ => rng.random(), + } +} + // -- Byte mutations -- /// Shuffle a random subrange of `bytes` using Fisher-Yates. @@ -388,6 +430,33 @@ const INTERESTING_U64: &[u64] = &[ 2_100_000_000_000_000_000, // 21M BTC (msats) ]; +/// Interesting SCID boundary values. Covers the all-zero SCID, each component +/// independently maxed out, all components maxed simultaneously, and each +/// component set to its smallest non-zero value. +const INTERESTING_SCID: &[ShortChannelId] = &[ + ShortChannelId::new(0, 0, 0), + ShortChannelId::new(ShortChannelId::MAX_BLOCK, 0, 0), + ShortChannelId::new(0, ShortChannelId::MAX_TX_INDEX, 0), + ShortChannelId::new(0, 0, u16::MAX), + ShortChannelId::new( + ShortChannelId::MAX_BLOCK, + ShortChannelId::MAX_TX_INDEX, + u16::MAX, + ), + ShortChannelId::new(1, 0, 0), + ShortChannelId::new(0, 1, 0), + ShortChannelId::new(0, 0, 1), +]; + +/// Interesting boundary values for 24-bit SCID components (`block` and `tx_index`). +const INTERESTING_SCID_U24: &[u32] = &[ + 0, + 1, + ShortChannelId::MAX_BLOCK / 2, + ShortChannelId::MAX_BLOCK - 1, + ShortChannelId::MAX_BLOCK, +]; + fn interesting_u8(rng: &mut impl Rng) -> u8 { INTERESTING_U8[rng.random_range(0..INTERESTING_U8.len())] } @@ -404,6 +473,14 @@ fn interesting_u64(rng: &mut impl Rng) -> u64 { INTERESTING_U64[rng.random_range(0..INTERESTING_U64.len())] } +fn interesting_scid(rng: &mut impl Rng) -> ShortChannelId { + INTERESTING_SCID[rng.random_range(0..INTERESTING_SCID.len())] +} + +fn interesting_scid_u24(rng: &mut impl Rng) -> u32 { + INTERESTING_SCID_U24[rng.random_range(0..INTERESTING_SCID_U24.len())] +} + #[cfg(test)] mod tests { use super::*; diff --git a/smite-ir/src/operation.rs b/smite-ir/src/operation.rs index 1e2d6fef..25073c0b 100644 --- a/smite-ir/src/operation.rs +++ b/smite-ir/src/operation.rs @@ -14,6 +14,7 @@ use std::fmt::Write; use bitcoin::{opcodes::all as opcodes, script::Builder, script::PushBytes}; use rand::{Rng, RngExt}; use serde::{Deserialize, Serialize}; +use smite::bolt::ShortChannelId; use super::VariableType; @@ -24,6 +25,9 @@ pub enum Operation { // -- Load: produce a variable from an embedded literal or the context -- /// Load a satoshi or millisatoshi amount. LoadAmount(u64), + /// Load a BOLT 7 `short_channel_id` in its packed `u64` form + /// (`(block << 40) | (tx_index << 16) | output_index`). + LoadShortChannelId(u64), /// Load a fee rate in sat/kw. LoadFeeratePerKw(u32), /// Load a block height or count. @@ -538,6 +542,9 @@ impl fmt::Display for Operation { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::LoadAmount(v) => write!(f, "LoadAmount({v})"), + Self::LoadShortChannelId(v) => { + write!(f, "LoadShortChannelId({})", ShortChannelId::from_u64(*v)) + } Self::LoadFeeratePerKw(v) => write!(f, "LoadFeeratePerKw({v})"), Self::LoadBlockHeight(v) => write!(f, "LoadBlockHeight({v})"), Self::LoadTimestamp(v) => write!(f, "LoadTimestamp({v})"), @@ -576,6 +583,7 @@ impl Operation { pub fn output_type(&self) -> Option { match self { Self::LoadAmount(_) => Some(VariableType::Amount), + Self::LoadShortChannelId(_) => Some(VariableType::ShortChannelId), Self::LoadFeeratePerKw(_) => Some(VariableType::FeeratePerKw), Self::LoadBlockHeight(_) => Some(VariableType::BlockHeight), Self::LoadTimestamp(_) => Some(VariableType::Timestamp), @@ -602,6 +610,7 @@ impl Operation { pub fn input_types(&self) -> Vec { match self { Self::LoadAmount(_) + | Self::LoadShortChannelId(_) | Self::LoadFeeratePerKw(_) | Self::LoadBlockHeight(_) | Self::LoadTimestamp(_) @@ -669,6 +678,7 @@ impl Operation { pub fn extractable_fields(&self) -> Vec<(Operation, VariableType)> { match self { Self::LoadAmount(_) + | Self::LoadShortChannelId(_) | Self::LoadFeeratePerKw(_) | Self::LoadBlockHeight(_) | Self::LoadTimestamp(_) @@ -703,6 +713,7 @@ impl Operation { pub fn is_param_mutable(&self) -> bool { match self { Self::LoadAmount(_) + | Self::LoadShortChannelId(_) | Self::LoadFeeratePerKw(_) | Self::LoadBlockHeight(_) | Self::LoadTimestamp(_) diff --git a/smite-ir/src/tests.rs b/smite-ir/src/tests.rs index eded45d4..6fb162a3 100644 --- a/smite-ir/src/tests.rs +++ b/smite-ir/src/tests.rs @@ -3,7 +3,7 @@ use rand::RngExt; use rand::SeedableRng; use rand::rngs::SmallRng; -use smite::bolt::MAX_MESSAGE_SIZE; +use smite::bolt::{MAX_MESSAGE_SIZE, ShortChannelId}; use super::*; use generators::{NodeAnnouncementGenerator, OpenChannelGenerator}; @@ -276,6 +276,12 @@ fn postcard_roundtrip() { operation: Operation::LoadChannelId([0xab; 32]), inputs: vec![], }, + Instruction { + operation: Operation::LoadShortChannelId( + ShortChannelId::new(700_000, 1234, 0).as_u64(), + ), + inputs: vec![], + }, Instruction { operation: Operation::LoadAmount(50_000), inputs: vec![], @@ -1297,6 +1303,39 @@ fn param_mutator_changes_mined_num_blocks() { ); } +#[test] +fn param_mutator_changes_short_channel_id() { + let original = Program { + instructions: vec![Instruction { + operation: Operation::LoadShortChannelId(0), + inputs: vec![], + }], + }; + let mut program = original.clone(); + let mutator = OperationParamMutator; + let mut rng = SmallRng::seed_from_u64(0); + + let mut diff_count = 0; + for _ in 0..100 { + mutator.mutate(&mut program, &mut rng); + // Ensure the operation type is unchanged. + assert!( + matches!( + program.instructions[0].operation, + Operation::LoadShortChannelId(_) + ), + "OperationParamMutator changed the operation type" + ); + if program != original { + diff_count += 1; + } + } + assert!( + diff_count > 90, + "OperationParamMutator has an unexpected bias" + ); +} + #[test] fn param_mutator_returns_false_on_empty_program() { let mut program = Program { diff --git a/smite-ir/src/variable.rs b/smite-ir/src/variable.rs index e6c1a08e..5bbd35a5 100644 --- a/smite-ir/src/variable.rs +++ b/smite-ir/src/variable.rs @@ -4,7 +4,7 @@ //! The serialized program stores data only in [`Operation`] literals. use bitcoin::secp256k1::PublicKey; -use smite::bolt::{AcceptChannel, ChannelId}; +use smite::bolt::{AcceptChannel, ChannelId, ShortChannelId}; use smite::channel_tx::FundingTransaction; const CHAIN_HASH_SIZE: usize = 32; @@ -20,6 +20,8 @@ pub enum Variable { ChainHash([u8; CHAIN_HASH_SIZE]), /// 32-byte channel identifier. ChannelId(ChannelId), + /// BOLT 7 `short_channel_id` (packed block / `tx_index` / `output_index`). + ShortChannelId(ShortChannelId), /// secp256k1 public key. Point(PublicKey), /// secp256k1 private key. @@ -55,6 +57,7 @@ impl Variable { Self::Bytes(_) => VariableType::Bytes, Self::ChainHash(_) => VariableType::ChainHash, Self::ChannelId(_) => VariableType::ChannelId, + Self::ShortChannelId(_) => VariableType::ShortChannelId, Self::Point(_) => VariableType::Point, Self::PrivateKey(_) => VariableType::PrivateKey, Self::Amount(_) => VariableType::Amount, @@ -78,6 +81,7 @@ pub enum VariableType { Bytes, ChainHash, ChannelId, + ShortChannelId, Point, PrivateKey, Amount, diff --git a/smite-scenarios/src/executor.rs b/smite-scenarios/src/executor.rs index e355dbb9..5052b2df 100644 --- a/smite-scenarios/src/executor.rs +++ b/smite-scenarios/src/executor.rs @@ -9,7 +9,7 @@ use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; use smite::bitcoin::{BitcoinCli, Utxo}; use smite::bolt::{ AcceptChannel, ChannelId, Message, NodeAnnouncement, OpenChannel, OpenChannelTlvs, Pong, - msg_type, + ShortChannelId, msg_type, }; use smite::channel_tx::{FundingTransaction, build_funding_transaction}; use smite::noise::{ConnectionError, NoiseConnection}; @@ -156,6 +156,9 @@ pub fn execute( let result = match &instr.operation { // -- Load operations -- Operation::LoadAmount(v) => Some(Variable::Amount(*v)), + Operation::LoadShortChannelId(v) => { + Some(Variable::ShortChannelId(ShortChannelId::from_u64(*v))) + } Operation::LoadFeeratePerKw(v) => Some(Variable::FeeratePerKw(*v)), Operation::LoadBlockHeight(v) => Some(Variable::BlockHeight(*v)), Operation::LoadTimestamp(v) => Some(Variable::Timestamp(*v)), diff --git a/smite/src/bolt/types.rs b/smite/src/bolt/types.rs index b489a382..91241daf 100644 --- a/smite/src/bolt/types.rs +++ b/smite/src/bolt/types.rs @@ -26,11 +26,6 @@ pub const PUBLIC_KEY_SIZE: usize = 33; /// Size of an encoded `short_channel_id` in bytes. pub const SHORT_CHANNEL_ID_SIZE: usize = 8; -/// Maximum representable block height (3 bytes, big-endian). -const MAX_BLOCK: u32 = 0x00ff_ffff; -/// Maximum representable transaction index (3 bytes, big-endian). -const MAX_TX_INDEX: u32 = 0x00ff_ffff; - /// A 32-byte channel identifier. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct ChannelId(pub [u8; CHANNEL_ID_SIZE]); @@ -69,6 +64,11 @@ impl ChannelId { pub struct ShortChannelId(u64); impl ShortChannelId { + /// Maximum representable block height (3 bytes, big-endian). + pub const MAX_BLOCK: u32 = 0x00ff_ffff; + /// Maximum representable transaction index (3 bytes, big-endian). + pub const MAX_TX_INDEX: u32 = 0x00ff_ffff; + /// Constructs a `short_channel_id` from its components. /// /// # Panics @@ -76,8 +76,8 @@ impl ShortChannelId { /// Panics if `block` or `tx_index` exceed their 24-bit field. #[must_use] pub const fn new(block: u32, tx_index: u32, output_index: u16) -> Self { - assert!(block <= MAX_BLOCK, "block is out-of-range"); - assert!(tx_index <= MAX_TX_INDEX, "tx_index is out-of-range"); + assert!(block <= Self::MAX_BLOCK, "block is out-of-range"); + assert!(tx_index <= Self::MAX_TX_INDEX, "tx_index is out-of-range"); let packed = ((block as u64) << 40) | ((tx_index as u64) << 16) | (output_index as u64); Self(packed) } @@ -209,22 +209,26 @@ mod tests { #[test] fn short_channel_id_new_accepts_max_components() { - let scid = ShortChannelId::new(MAX_BLOCK, MAX_TX_INDEX, u16::MAX); - assert_eq!(scid.block(), MAX_BLOCK); - assert_eq!(scid.tx_index(), MAX_TX_INDEX); + let scid = ShortChannelId::new( + ShortChannelId::MAX_BLOCK, + ShortChannelId::MAX_TX_INDEX, + u16::MAX, + ); + assert_eq!(scid.block(), ShortChannelId::MAX_BLOCK); + assert_eq!(scid.tx_index(), ShortChannelId::MAX_TX_INDEX); assert_eq!(scid.output_index(), u16::MAX); } #[test] #[should_panic(expected = "block is out-of-range")] fn short_channel_id_new_panics_on_block_overflow() { - let _ = ShortChannelId::new(MAX_BLOCK + 1, 0, 0); + let _ = ShortChannelId::new(ShortChannelId::MAX_BLOCK + 1, 0, 0); } #[test] #[should_panic(expected = "tx_index is out-of-range")] fn short_channel_id_new_panics_on_tx_index_overflow() { - let _ = ShortChannelId::new(0, MAX_TX_INDEX + 1, 0); + let _ = ShortChannelId::new(0, ShortChannelId::MAX_TX_INDEX + 1, 0); } #[test]