Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions smite-ir/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
79 changes: 78 additions & 1 deletion smite-ir/src/mutators/operation_param.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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 {
Comment thread
devvaansh marked this conversation as resolved.
Resolved
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.
Expand Down Expand Up @@ -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())]
}
Expand All @@ -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::*;
Expand Down
11 changes: 11 additions & 0 deletions smite-ir/src/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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.
Expand Down Expand Up @@ -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) => {
Comment thread
morehouse marked this conversation as resolved.
Resolved
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})"),
Expand Down Expand Up @@ -576,6 +583,7 @@ impl Operation {
pub fn output_type(&self) -> Option<VariableType> {
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),
Expand All @@ -602,6 +610,7 @@ impl Operation {
pub fn input_types(&self) -> Vec<VariableType> {
match self {
Self::LoadAmount(_)
| Self::LoadShortChannelId(_)
| Self::LoadFeeratePerKw(_)
| Self::LoadBlockHeight(_)
| Self::LoadTimestamp(_)
Expand Down Expand Up @@ -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(_)
Expand Down Expand Up @@ -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(_)
Expand Down
41 changes: 40 additions & 1 deletion smite-ir/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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![],
Expand Down Expand Up @@ -1297,6 +1303,39 @@ fn param_mutator_changes_mined_num_blocks() {
);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: could also add LoadShortChannelId to the postcard_roundtrip tests as well


#[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 {
Expand Down
6 changes: 5 additions & 1 deletion smite-ir/src/variable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -78,6 +81,7 @@ pub enum VariableType {
Bytes,
ChainHash,
ChannelId,
ShortChannelId,
Point,
PrivateKey,
Amount,
Expand Down
5 changes: 4 additions & 1 deletion smite-scenarios/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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)),
Expand Down
28 changes: 16 additions & 12 deletions smite/src/bolt/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down Expand Up @@ -69,15 +64,20 @@ 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
///
/// 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)
}
Expand Down Expand Up @@ -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]
Expand Down