vls_protocol_signer/
util.rs

1use bit_vec::BitVec;
2use lightning_signer::channel::CommitmentType;
3use lightning_signer::prelude::*;
4use vls_protocol::features::*;
5
6/// Extract the commitment type from the CLN-style serialized channel features
7pub fn channel_type_to_commitment_type(channel_type: &Vec<u8>) -> CommitmentType {
8    // The byte/bit order from the wire is wrong in every way ...
9    let features = BitVec::from_bytes(
10        &channel_type.iter().rev().map(|bb| bb.reverse_bits()).collect::<Vec<u8>>(),
11    );
12    if features.get(OPT_ANCHORS_ZERO_FEE_HTLC_TX).unwrap_or_default() {
13        assert_eq!(features.get(OPT_STATIC_REMOTEKEY).unwrap_or_default(), true);
14        CommitmentType::AnchorsZeroFeeHtlc
15    } else if features.get(OPT_ANCHOR_OUTPUTS).unwrap_or_default() {
16        assert_eq!(features.get(OPT_STATIC_REMOTEKEY).unwrap_or_default(), true);
17        CommitmentType::Anchors
18    } else if features.get(OPT_STATIC_REMOTEKEY).unwrap_or_default() {
19        CommitmentType::StaticRemoteKey
20    } else {
21        CommitmentType::Legacy
22    }
23}
24
25/// Convert a commitment type to CLN-style serialized channel features
26pub fn commitment_type_to_channel_type(commitment_type: CommitmentType) -> Vec<u8> {
27    let mut channel_features = BitVec::from_elem(OPT_MAX, false);
28    channel_features.set(OPT_STATIC_REMOTEKEY, true);
29    if commitment_type == CommitmentType::Anchors
30        || commitment_type == CommitmentType::AnchorsZeroFeeHtlc
31    {
32        channel_features.set(OPT_ANCHOR_OUTPUTS, true);
33    }
34    if commitment_type == CommitmentType::AnchorsZeroFeeHtlc {
35        channel_features.set(OPT_ANCHORS_ZERO_FEE_HTLC_TX, true);
36    }
37    // The byte/bit order from the wire is wrong in every way ...
38    channel_features.to_bytes().iter().rev().map(|bb| bb.reverse_bits()).collect::<Vec<u8>>()
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn features_test() {
47        for commitment_type in vec![
48            CommitmentType::StaticRemoteKey,
49            CommitmentType::Anchors,
50            CommitmentType::AnchorsZeroFeeHtlc,
51        ] {
52            assert_eq!(
53                channel_type_to_commitment_type(&commitment_type_to_channel_type(commitment_type)),
54                commitment_type
55            );
56        }
57    }
58}