vls_protocol_signer/
handler.rs

1#![allow(deprecated)]
2
3use alloc::boxed::Box;
4use alloc::collections::BTreeMap;
5use alloc::format;
6use alloc::string::String;
7use alloc::string::ToString;
8use alloc::vec;
9use alloc::vec::Vec;
10use core::cmp::min;
11use core::fmt::{Debug, Display, Formatter};
12use core::str::FromStr;
13use lightning_signer::bitcoin::script::PushBytesBuf;
14use lightning_signer::bitcoin::ScriptBuf;
15use lightning_signer::lightning::ln::channel_keys::RevocationKey;
16use vls_protocol::psbt::PsbtWrapper;
17
18use bitcoin::bech32::u5;
19use bitcoin::bip32::{DerivationPath, KeySource};
20use bitcoin::blockdata::script;
21use bitcoin::consensus::deserialize;
22use bitcoin::psbt::PartiallySignedTransaction;
23use bitcoin::secp256k1;
24use bitcoin::secp256k1::SecretKey;
25use bitcoin::taproot::TapLeafHash;
26use bitcoin::{Address, Network};
27use bitcoin::{OutPoint, Transaction, Witness};
28use lightning_signer::bitcoin;
29use lightning_signer::bitcoin::key::XOnlyPublicKey;
30use lightning_signer::bitcoin::sighash::EcdsaSighashType;
31use lightning_signer::channel::{
32    ChannelBalance, ChannelBase, ChannelId, ChannelSetup, SlotInfo, SlotInfoVariant, TypedSignature,
33};
34use lightning_signer::dbgvals;
35use lightning_signer::invoice::Invoice;
36use lightning_signer::lightning::ln::chan_utils::ChannelPublicKeys;
37use lightning_signer::lightning::ln::PaymentHash;
38use lightning_signer::node::{Node, NodeConfig, NodeMonitor, NodeServices};
39use lightning_signer::persist::{Mutations, Persist};
40use lightning_signer::signer::my_keys_manager::MyKeysManager;
41use lightning_signer::tx::tx::HTLCInfo2;
42use lightning_signer::util::status;
43use lightning_signer::Arc;
44use lightning_signer::{function, trace_node_state};
45use log::*;
46use secp256k1::{ecdsa, PublicKey, Secp256k1};
47
48use lightning_signer::chain::tracker::{Error as TrackerError, Headers};
49use lightning_signer::util::crypto_utils::signature_to_bitcoin_vec;
50use lightning_signer::util::debug_utils::DebugUnilateralCloseInfo;
51use lightning_signer::util::status::{Code, Status};
52use lightning_signer::wallet::Wallet;
53use serde_bolt::{to_vec, Array, Octets, WireString, WithSize};
54use vls_protocol::model::{
55    Basepoints, BitcoinSignature, DisclosedSecret, ExtKey, Htlc, PubKey, RecoverableSignature,
56    Secret, Signature, Utxo,
57};
58use vls_protocol::msgs::{
59    DeriveSecretReply, PreapproveInvoiceReply, PreapproveKeysendReply, SerBolt, SignBolt12Reply,
60    DEFAULT_MAX_PROTOCOL_VERSION, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION_NO_SECRET,
61    PROTOCOL_VERSION_REVOKE,
62};
63use vls_protocol::psbt::StreamedPSBT;
64use vls_protocol::serde_bolt;
65use vls_protocol::{msgs, msgs::DeBolt, msgs::Message, Error as ProtocolError};
66
67use crate::approver::{Approve, NegativeApprover};
68use crate::util::channel_type_to_commitment_type;
69
70/// Error
71#[derive(Debug)]
72pub enum Error {
73    /// Protocol error
74    Protocol(ProtocolError),
75    /// We failed to sign
76    Signing(Status),
77    /// We failed to sign because of a temporary error
78    Temporary(Status),
79}
80
81impl Display for Error {
82    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
83        Debug::fmt(self, f)
84    }
85}
86
87#[cfg(feature = "std")]
88impl std::error::Error for Error {}
89
90impl From<ProtocolError> for Error {
91    fn from(e: ProtocolError) -> Self {
92        Error::Protocol(e)
93    }
94}
95
96impl From<Status> for Error {
97    fn from(e: Status) -> Self {
98        if e.code() == Code::Temporary {
99            Error::Temporary(e)
100        } else {
101            Error::Signing(e)
102        }
103    }
104}
105
106fn to_bitcoin_sig(sig: ecdsa::Signature) -> BitcoinSignature {
107    BitcoinSignature {
108        signature: Signature(sig.serialize_compact()),
109        sighash: EcdsaSighashType::All as u8,
110    }
111}
112
113fn typed_to_bitcoin_sig(sig: TypedSignature) -> BitcoinSignature {
114    BitcoinSignature { signature: Signature(sig.sig.serialize_compact()), sighash: sig.typ as u8 }
115}
116
117fn to_script(bytes: &Vec<u8>) -> Option<ScriptBuf> {
118    if bytes.is_empty() {
119        None
120    } else {
121        Some(ScriptBuf::from(bytes.clone()))
122    }
123}
124
125/// Result
126pub type Result<T> = core::result::Result<T, Error>;
127
128/// A protocol handler
129/// The handle function takes an incoming message, handles it and returns a response.
130///
131/// There are two implementations of this trait - [`RootHandler`] for node level
132/// messages and [`ChannelHandler`] for channel level messages.
133pub trait Handler {
134    /// Handle a message
135    fn handle(&self, msg: Message) -> Result<Box<dyn SerBolt>> {
136        log_request(&msg);
137        let result = self.do_handle(msg);
138        if let Err(ref err) = result {
139            log_error(err);
140        }
141        let reply = result?;
142        log_reply(&reply);
143        Ok(reply)
144    }
145
146    /// Commit the persister transaction if any
147    fn commit(&self) {
148        self.node().get_persister().commit().expect("commit");
149    }
150
151    /// Actual handling
152    fn do_handle(&self, msg: Message) -> Result<Box<dyn SerBolt>>;
153    /// Unused
154    fn client_id(&self) -> u64;
155    /// Create a channel handler
156    fn for_new_client(&self, client_id: u64, peer_id: PubKey, dbid: u64) -> ChannelHandler;
157    /// Get the associated signing node.
158    /// Note that if you want to perform an operation that can result in a mutation
159    /// of the node state requiring a persist, and your persister writes to the cloud,
160    /// you must use [`Handler::with_persist`] instead.
161    fn node(&self) -> &Arc<Node>;
162
163    /// Perform an operation on the Node that requires persistence.
164    /// The operation must not mutate if it fails (returns an error).
165    /// You must call [`Handler::commit`] after you persist the mutations in the
166    /// cloud.
167    fn with_persist(&self, f: impl FnOnce(&Node) -> Result<()>) -> Result<Mutations> {
168        let node = self.node();
169        let persister = node.get_persister();
170        persister.enter().map_err(|e| {
171            error!("failed to enter persister: {:?}", e);
172            Status::internal("failed to start persister transaction")
173        })?;
174        let result = f(&*node);
175        let muts = persister.prepare();
176
177        match result {
178            Ok(()) => Ok(muts),
179            Err(e) => {
180                if !muts.is_empty() {
181                    #[cfg(not(feature = "log_pretty_print"))]
182                    debug!("stranded mutations: {:?}", &muts);
183                    #[cfg(feature = "log_pretty_print")]
184                    debug!("stranded mutations: {:#?}", &muts);
185                    panic!("failed operation with stranded mutations");
186                }
187                Err(e)
188            }
189        }
190    }
191}
192
193fn log_request(msg: &Message) {
194    #[cfg(not(feature = "log_pretty_print"))]
195    debug!("{:?}", msg);
196    #[cfg(feature = "log_pretty_print")]
197    debug!("{:#?}", msg);
198}
199
200fn log_error(err: &Error) {
201    #[cfg(not(feature = "log_pretty_print"))]
202    error!("{:?}", err);
203    #[cfg(feature = "log_pretty_print")]
204    error!("{:#?}", err);
205}
206
207fn log_reply(reply: &Box<dyn SerBolt>) {
208    #[cfg(not(feature = "log_pretty_print"))]
209    debug!("{:?}", reply);
210    #[cfg(feature = "log_pretty_print")]
211    debug!("{:#?}", reply);
212}
213
214// Log the channel slot information
215fn log_chaninfo(mut slotinfo: Vec<SlotInfo>) {
216    // log header
217    info!("chaninfo:  oid channel_id                                                                         funding_outpoint                                                   claimable  received   offered  sweeping f state");
218    // sample record:   1 0266e4598d1d3c415f572a8488830b60f7e744ed9235eb0b1ba93283b315c035180100000000000000 beef1bf6c17657470880bf85819c775a8938c7f2dfb7e936b2d07c13fa813639:0         0      0  0      0  0    100000 1 MUTUALLY_CLOSED at 109, age till 209
219
220    // Sort by oid
221    slotinfo.sort_by_key(|k| k.oid);
222
223    for slot in slotinfo {
224        let oid = slot.oid;
225        let id = slot.id;
226
227        match slot.slot {
228            SlotInfoVariant::StubInfo { pruneheight } => info!(
229                "chaninfo: {:>4} {} prune after {}",
230                oid,
231                id,
232                pruneheight // this comment makes the indentation awesome
233            ),
234            SlotInfoVariant::ChannelInfo { funding, balance, forget_seen, diagnostic } => info!(
235                "chaninfo: {:>4} {} {:<67} {:>9} {:>6} {:>2} {:>6} {:>2} {:>9} {} {}",
236                oid,
237                id,
238                funding.unwrap_or_else(|| {
239                    let mut ph = OutPoint::default();
240                    ph.vout = 0; // the default vout is much too large for our format
241                    ph
242                }),
243                balance.claimable,
244                balance.received_htlc,
245                balance.received_htlc_count,
246                balance.offered_htlc,
247                balance.offered_htlc_count,
248                balance.sweeping,
249                if forget_seen { 1 } else { 0 },
250                diagnostic,
251            ),
252        }
253    }
254}
255
256/// Initial protocol handler, for negotiating the protocol version
257#[derive(Clone)]
258pub struct InitHandler {
259    id: u64,
260    node: Arc<Node>,
261    approver: Arc<dyn Approve>,
262    max_protocol_version: u32,
263    protocol_version: Option<u32>,
264}
265
266/// Protocol handler
267#[derive(Clone)]
268pub struct RootHandler {
269    id: u64,
270    node: Arc<Node>,
271    approver: Arc<dyn Approve>,
272    protocol_version: u32,
273}
274
275/// Builder for RootHandler
276///
277/// WARNING: if you don't specify a seed, and you persist to LSS, you must get the seed
278/// from the builder and persist it yourself.  LSS does not persist the seed.
279/// If you don't persist, you will lose your keys.
280pub struct HandlerBuilder {
281    network: Network,
282    id: u64,
283    seed: [u8; 32],
284    allowlist: Vec<String>,
285    services: NodeServices,
286    approver: Arc<dyn Approve>,
287    max_protocol_version: u32,
288}
289
290impl HandlerBuilder {
291    /// Create a InitHandlerBuilder
292    pub fn new(
293        network: Network,
294        id: u64,
295        services: NodeServices,
296        seed: [u8; 32],
297    ) -> HandlerBuilder {
298        HandlerBuilder {
299            network,
300            id,
301            seed,
302            allowlist: vec![],
303            services,
304            approver: Arc::new(NegativeApprover()),
305            max_protocol_version: DEFAULT_MAX_PROTOCOL_VERSION,
306        }
307    }
308
309    /// Set the initial allowlist (only used if node is new)
310    pub fn allowlist(mut self, allowlist: Vec<String>) -> Self {
311        self.allowlist = allowlist;
312        self
313    }
314
315    /// Set the approver
316    pub fn approver(mut self, approver: Arc<dyn Approve>) -> Self {
317        self.approver = approver;
318        self
319    }
320
321    /// Set the hsmd max protocol version, may still be negotiated down by node
322    pub fn max_protocol_version(mut self, max_version: u32) -> Self {
323        self.max_protocol_version = max_version;
324        self
325    }
326
327    /// Create a keys manager - useful for bootstrapping a node from persistence, so the
328    /// persistence key can be derived.
329    pub fn build_keys_manager(&self) -> (MyKeysManager, PublicKey) {
330        let config = NodeConfig::new(self.network);
331        Node::make_keys_manager(&config, &self.seed, &self.services)
332    }
333
334    /// Build the root handler.
335    ///
336    /// Returns the handler and any mutations that need to be stored.
337    /// You must call [`Handler::commit`] after you persist the mutations in the
338    /// cloud.
339    pub fn build(self) -> Result<InitHandler> {
340        let config = NodeConfig::new(self.network);
341
342        let persister = self.services.persister.clone();
343        let nodes = persister.get_nodes().expect("get_nodes");
344        let node = if nodes.is_empty() {
345            let node = Arc::new(Node::new(config, &self.seed, vec![], self.services));
346            info!("New node {}", node.get_id());
347            node.add_allowlist(&self.allowlist).expect("allowlist");
348            // NOTE: if we persist to LSS, we don't actually persist the seed here,
349            // and the caller must provide the seed each time we restore from persistence
350            persister.new_node(&node.get_id(), &config, &*node.get_state()).expect("new_node");
351            persister.new_tracker(&node.get_id(), &node.get_tracker()).expect("new_chain_tracker");
352            node
353        } else {
354            assert_eq!(nodes.len(), 1);
355            let (node_id, entry) = nodes.into_iter().next().unwrap();
356            info!("Restore node {}", node_id);
357            Node::restore_node(&node_id, entry, &self.seed, self.services)?
358        };
359        trace_node_state!(node.get_state());
360
361        Ok(InitHandler::new(self.id, node, self.approver, self.max_protocol_version))
362    }
363
364    /// The persister
365    pub fn persister(&self) -> Arc<dyn Persist> {
366        self.services.persister.clone()
367    }
368}
369
370impl RootHandler {
371    fn channel_id(peer_id: &PubKey, dbid: u64) -> ChannelId {
372        ChannelId::new_from_peer_id_and_oid(&peer_id.0, dbid)
373    }
374
375    /// Log channel information
376    pub fn log_chaninfo(&self) {
377        log_chaninfo(self.node.chaninfo());
378    }
379
380    /// Get the channel balances
381    pub fn channel_balance(&self) -> ChannelBalance {
382        self.node.channel_balance()
383    }
384
385    /// Get the current chain height based on the tracker
386    pub fn get_chain_height(&self) -> u32 {
387        self.node.get_chain_height()
388    }
389
390    // sign any inputs that are ours, modifying the PSBT in place
391    fn sign_withdrawal(&self, streamed: &mut StreamedPSBT, utxos: Array<Utxo>) -> Result<()> {
392        let psbt = &mut streamed.psbt.inner;
393        let opaths = extract_psbt_output_paths(&psbt);
394
395        let tx = &mut psbt.unsigned_tx;
396
397        let prev_outs = psbt
398            .inputs
399            .iter()
400            .map(|i| {
401                i.witness_utxo.as_ref().expect("psbt input witness UTXOs must be populated").clone()
402            })
403            .collect::<Vec<_>>();
404
405        let secp_ctx = Secp256k1::new();
406        let mut uniclosekeys = Vec::new();
407        let mut ipaths = Vec::new();
408        for input in tx.input.iter() {
409            if let Some(utxo) = utxos.iter().find(|u| {
410                u.txid == input.previous_output.txid && u.outnum == input.previous_output.vout
411            }) {
412                ipaths.push(vec![utxo.keyindex]);
413                if let Some(ci) = utxo.close_info.as_ref() {
414                    let channel_id = Self::channel_id(&ci.peer_id, ci.channel_id);
415                    let per_commitment_point = ci
416                        .commitment_point
417                        .as_ref()
418                        .map(|p| PublicKey::from_slice(&p.0).expect("TODO"));
419
420                    let ck = self.node.with_channel(&channel_id, |chan| {
421                        let revocation_pubkey = per_commitment_point.as_ref().map(|p| {
422                            let revocation_basepoint =
423                                chan.counterparty_pubkeys().revocation_basepoint;
424                            RevocationKey::from_basepoint(&secp_ctx, &revocation_basepoint, p)
425                        });
426                        chan.get_unilateral_close_key(&per_commitment_point, &revocation_pubkey)
427                    })?;
428                    uniclosekeys.push(Some(ck));
429                } else {
430                    uniclosekeys.push(None)
431                }
432            } else {
433                ipaths.push(vec![]);
434                uniclosekeys.push(None);
435            }
436        }
437
438        // Populate script_sig for p2sh-p2wpkh signing
439        for (psbt_in, tx_in) in psbt.inputs.iter_mut().zip(tx.input.iter_mut()) {
440            if let Some(script) = psbt_in.redeem_script.as_ref() {
441                assert!(psbt_in.final_script_sig.is_none());
442                assert!(tx_in.script_sig.is_empty());
443                let mut push_bytes = PushBytesBuf::new();
444                push_bytes
445                    .extend_from_slice(script.as_bytes())
446                    .expect("push_bytes.extend_from_slice failed");
447                let script_sig = script::Builder::new().push_slice(&push_bytes).into_script();
448                psbt_in.final_script_sig = Some(script_sig);
449            }
450        }
451
452        dbgvals!(
453            ipaths,
454            opaths,
455            tx.txid(),
456            tx,
457            streamed.segwit_flags,
458            DebugUnilateralCloseInfo(&uniclosekeys)
459        );
460
461        let approved = self.approver.handle_proposed_onchain(
462            &self.node,
463            &tx,
464            &streamed.segwit_flags,
465            &prev_outs,
466            &uniclosekeys,
467            &opaths,
468        )?;
469
470        if !approved {
471            return Err(Status::failed_precondition("unapproved destination"))?;
472        }
473
474        let witvec = self.node.unchecked_sign_onchain_tx(&tx, &ipaths, &prev_outs, uniclosekeys)?;
475
476        for (i, stack) in witvec.into_iter().enumerate() {
477            if !stack.is_empty() {
478                psbt.inputs[i].final_script_witness = Some(Witness::from_vec(stack));
479            }
480        }
481        Ok(())
482    }
483}
484
485impl InitHandler {
486    /// Create a new InitHandler
487    pub fn new(
488        id: u64,
489        node: Arc<Node>,
490        approver: Arc<dyn Approve>,
491        max_protocol_version: u32,
492    ) -> InitHandler {
493        InitHandler { id, node, approver, max_protocol_version, protocol_version: None }
494    }
495
496    /// Reset the handler
497    pub fn reset(&mut self) {
498        self.protocol_version = None;
499    }
500
501    /// Get the associated node
502    pub fn node(&self) -> &Arc<Node> {
503        &self.node
504    }
505
506    /// Log channel information
507    pub fn log_chaninfo(&self) {
508        log_chaninfo(self.node.chaninfo());
509    }
510
511    /// Handle a request message, returning a boolean indicating whether the initial negotiation is complete
512    /// and a response.
513    ///
514    /// Panics if initial negotiation is already complete.
515    pub fn handle(&mut self, msg: Message) -> Result<(bool, Option<Box<dyn SerBolt>>)> {
516        assert!(self.protocol_version.is_none(), "initial negotiation already complete");
517        log_request(&msg);
518        let result = self.do_handle(msg);
519        if let Err(ref err) = result {
520            log_error(err);
521        }
522        let (is_done, maybe_reply) = result?;
523        if let Some(ref reply) = maybe_reply {
524            log_reply(&reply);
525        }
526        Ok((is_done, maybe_reply))
527    }
528
529    fn do_handle(&mut self, msg: Message) -> Result<(bool, Option<Box<dyn SerBolt>>)> {
530        match msg {
531            Message::Ping(p) => {
532                info!("got ping with {} {}", p.id, String::from_utf8(p.message.0).unwrap());
533                let reply =
534                    msgs::Pong { id: p.id, message: WireString("pong".as_bytes().to_vec()) };
535                Ok((false, Some(Box::new(reply))))
536            }
537            #[cfg(feature = "developer")]
538            Message::HsmdDevPreinit(m) => {
539                let node_id = self.node.get_id().serialize();
540                // the seed is extracted before this handler is called to create the node
541                let allowlist: Vec<_> = m
542                    .allowlist
543                    .iter()
544                    .map(|ws| String::from_utf8(ws.0.clone()).expect("utf8"))
545                    .collect();
546                self.node.add_allowlist(&allowlist)?;
547                self.protocol_version = None;
548                Ok((
549                    false, // HsmdInit{,2} will follow ...
550                    Some(Box::new(msgs::HsmdDevPreinitReply { node_id: PubKey(node_id) })),
551                ))
552            }
553            #[cfg(feature = "developer")]
554            Message::HsmdDevPreinit2(m) => {
555                assert_ne!(self.node.network(), Network::Bitcoin);
556                // the seed is extracted before this handler is called to create the node
557                let allowlist = if let Some(ref alist) = m.options.allowlist {
558                    alist.iter().map(|ws| String::from_utf8(ws.0.clone()).expect("utf8")).collect()
559                } else {
560                    vec![]
561                };
562                self.node.add_allowlist(&allowlist)?;
563                self.protocol_version = None;
564                Ok((
565                    false, // HsmdInit{,2} will follow ...
566                    None,  // There is no HsmdDevPreinit2 reply
567                ))
568            }
569            Message::HsmdInit(m) => {
570                let node_id = self.node.get_id().serialize();
571                let bip32 = self.node.get_account_extended_pubkey().encode();
572                let bolt12_pubkey = self.node.get_bolt12_pubkey().serialize();
573                #[cfg(not(feature = "developer"))]
574                if m.dev_privkey.is_some()
575                    || m.dev_bip32_seed.is_some()
576                    || m.dev_channel_secrets.is_some()
577                    || m.dev_channel_secrets_shaseed.is_some()
578                {
579                    return Err(Error::Protocol(ProtocolError::DeveloperField));
580                }
581                assert!(
582                    m.hsm_wire_min_version <= self.max_protocol_version,
583                    "node's minimum wire protocol version too large: {} > {}",
584                    m.hsm_wire_min_version,
585                    self.max_protocol_version
586                );
587                assert!(
588                    m.hsm_wire_max_version >= MIN_PROTOCOL_VERSION,
589                    "node's maximum wire protocol version too small: {} < {}",
590                    m.hsm_wire_max_version,
591                    MIN_PROTOCOL_VERSION
592                );
593                let mutual_version = min(self.max_protocol_version, m.hsm_wire_max_version);
594                info!(
595                    "signer protocol_version {}, \
596                     node hsm_wire_max_version {}, \
597                     setting protocol_version to {}",
598                    self.max_protocol_version, m.hsm_wire_max_version, mutual_version
599                );
600                self.protocol_version = Some(mutual_version);
601                if mutual_version < 4 {
602                    return Ok((
603                        true,
604                        Some(Box::new(msgs::HsmdInitReplyV2 {
605                            node_id: PubKey(node_id),
606                            bip32: ExtKey(bip32),
607                            bolt12: PubKey(bolt12_pubkey),
608                        })),
609                    ));
610                }
611                let mut hsm_capabilities = vec![
612                    msgs::CheckPubKey::TYPE as u32,
613                    msgs::SignAnyDelayedPaymentToUs::TYPE as u32,
614                    msgs::SignAnchorspend::TYPE as u32,
615                    msgs::SignHtlcTxMingle::TYPE as u32,
616                    // TODO advertise splicing when it is implemented
617                    // msgs::SignSpliceTx::TYPE as u32,
618                    msgs::CheckOutpoint::TYPE as u32,
619                    msgs::ForgetChannel::TYPE as u32,
620                ];
621                if mutual_version >= PROTOCOL_VERSION_REVOKE {
622                    hsm_capabilities.push(msgs::RevokeCommitmentTx::TYPE as u32);
623                }
624                Ok((
625                    true,
626                    Some(Box::new(msgs::HsmdInitReplyV4 {
627                        hsm_version: mutual_version,
628                        hsm_capabilities: hsm_capabilities.into(),
629                        node_id: PubKey(node_id),
630                        bip32: ExtKey(bip32),
631                        bolt12: PubKey(bolt12_pubkey),
632                    })),
633                ))
634            }
635            Message::HsmdInit2(m) => {
636                let bip32 = self.node.get_account_extended_pubkey().encode();
637                let node_id = self.node.get_id().serialize();
638                let bolt12_pubkey = self.node.get_bolt12_pubkey().serialize();
639                #[cfg(feature = "developer")]
640                {
641                    let allowlist: Vec<_> = m
642                        .dev_allowlist
643                        .iter()
644                        .map(|ws| String::from_utf8(ws.0.clone()).expect("utf8"))
645                        .collect();
646                    self.node.add_allowlist(&allowlist)?;
647                }
648
649                #[cfg(not(feature = "developer"))]
650                if m.dev_allowlist.len() != 0 || m.dev_seed.is_some() {
651                    return Err(Error::Protocol(ProtocolError::DeveloperField));
652                }
653                self.protocol_version = Some(4);
654                Ok((
655                    true,
656                    Some(Box::new(msgs::HsmdInit2Reply {
657                        node_id: PubKey(node_id),
658                        bip32: ExtKey(bip32),
659                        bolt12: PubKey(bolt12_pubkey),
660                    })),
661                ))
662            }
663            m => unimplemented!("init loop {}: unimplemented message {:?}", self.id, m),
664        }
665    }
666}
667
668impl Into<RootHandler> for InitHandler {
669    fn into(self) -> RootHandler {
670        let protocol_version = self.protocol_version.expect("initial negotiation not complete");
671        RootHandler { id: self.id, node: self.node, approver: self.approver, protocol_version }
672    }
673}
674
675impl Handler for RootHandler {
676    fn do_handle(&self, msg: Message) -> Result<Box<dyn SerBolt>> {
677        match msg {
678            Message::Ping(p) => {
679                info!("got ping with {} {}", p.id, String::from_utf8(p.message.0).unwrap());
680                let reply =
681                    msgs::Pong { id: p.id, message: WireString("pong".as_bytes().to_vec()) };
682                Ok(Box::new(reply))
683            }
684            Message::Memleak(_m) => Ok(Box::new(msgs::MemleakReply { result: false })),
685            Message::SignBolt12(m) => {
686                let tweak =
687                    if m.public_tweak.is_empty() { None } else { Some(m.public_tweak.as_slice()) };
688                let sig = self.node.sign_bolt12(
689                    &m.message_name.0,
690                    &m.field_name.0,
691                    &m.merkle_root.0,
692                    tweak,
693                )?;
694                Ok(Box::new(SignBolt12Reply { signature: Signature(sig.as_ref().clone()) }))
695            }
696            Message::PreapproveInvoice(m) => {
697                let invstr = String::from_utf8(m.invstring.0)
698                    .map_err(|e| Status::invalid_argument(e.to_string()))?;
699                let invoice = Invoice::from_str(&invstr)
700                    .map_err(|e| Status::invalid_argument(e.to_string()))?;
701                let result = self.approver.handle_proposed_invoice(&self.node, invoice)?;
702                Ok(Box::new(PreapproveInvoiceReply { result }))
703            }
704            Message::PreapproveKeysend(m) => {
705                let result = self.approver.handle_proposed_keysend(
706                    &self.node,
707                    PublicKey::from_slice(&m.destination.0)
708                        .map_err(|e| Status::invalid_argument(e.to_string()))?,
709                    PaymentHash(m.payment_hash.0),
710                    m.amount_msat,
711                )?;
712                Ok(Box::new(PreapproveKeysendReply { result }))
713            }
714            Message::DeriveSecret(m) => {
715                let secret = self.node.derive_secret(&m.info);
716                Ok(Box::new(DeriveSecretReply {
717                    secret: Secret(secret[..].try_into().expect("secret")),
718                }))
719            }
720            Message::SignMessage(m) => {
721                let sig = self.node.sign_message(&m.message)?;
722                let sig_slice = sig.try_into().expect("recoverable signature size");
723                Ok(Box::new(msgs::SignMessageReply { signature: RecoverableSignature(sig_slice) }))
724            }
725            Message::Ecdh(m) => {
726                let pubkey = PublicKey::from_slice(&m.point.0).expect("pubkey");
727                let secret = self.node.ecdh(&pubkey).as_slice().try_into().unwrap();
728                Ok(Box::new(msgs::EcdhReply { secret: Secret(secret) }))
729            }
730            Message::NewChannel(m) => {
731                self.node.new_channel(m.dbid, &m.peer_id.0, &self.node)?;
732                Ok(Box::new(msgs::NewChannelReply {}))
733            }
734            Message::ForgetChannel(m) => {
735                let channel_id = Self::channel_id(&m.node_id, m.dbid);
736                self.node.forget_channel(&channel_id)?;
737                Ok(Box::new(msgs::ForgetChannelReply {}))
738            }
739            Message::GetChannelBasepoints(m) => {
740                let channel_id = Self::channel_id(&m.node_id, m.dbid);
741                let bps = self
742                    .node
743                    .with_channel_base(&channel_id, |base| Ok(base.get_channel_basepoints()))?;
744
745                let basepoints = Basepoints {
746                    revocation: PubKey(bps.revocation_basepoint.0.serialize()),
747                    payment: PubKey(bps.payment_point.serialize()),
748                    htlc: PubKey(bps.htlc_basepoint.0.serialize()),
749                    delayed_payment: PubKey(bps.delayed_payment_basepoint.0.serialize()),
750                };
751                let funding = PubKey(bps.funding_pubkey.serialize());
752
753                Ok(Box::new(msgs::GetChannelBasepointsReply { basepoints, funding }))
754            }
755            Message::SignWithdrawal(m) => {
756                let mut streamed = m.psbt.0;
757                let utxos = m.utxos;
758
759                #[cfg(not(feature = "log_pretty_print"))]
760                debug!("SignWithdrawal psbt {:?}", streamed);
761                #[cfg(feature = "log_pretty_print")]
762                debug!("SignWithdrawal psbt {:#?}", streamed);
763
764                self.sign_withdrawal(&mut streamed, utxos)?;
765
766                Ok(Box::new(msgs::SignWithdrawalReply { psbt: WithSize(streamed.psbt) }))
767            }
768            Message::SignInvoice(m) => {
769                let hrp = String::from_utf8(m.hrp.to_vec()).expect("hrp");
770                let hrp_bytes = hrp.as_bytes();
771                let data: Vec<_> = m
772                    .u5bytes
773                    .iter()
774                    .map(|b| u5::try_from_u8(*b).expect("invoice not base32"))
775                    .collect();
776                let sig = self.node.sign_invoice(hrp_bytes, &data)?;
777                let (rid, ser) = sig.serialize_compact();
778                let mut sig_slice = [0u8; 65];
779                sig_slice[0..64].copy_from_slice(&ser);
780                sig_slice[64] = rid.to_i32() as u8;
781                Ok(Box::new(msgs::SignInvoiceReply { signature: RecoverableSignature(sig_slice) }))
782            }
783            Message::SignHtlcTxMingle(m) => {
784                // this is just an alias for SignWithdrawal (?!), and doesn't actually sign the HTLC tx -
785                // those are signed by calls such as `SignAnyLocalHtlcTx`
786                let mut streamed = m.psbt.0;
787                let utxos = m.utxos;
788
789                #[cfg(not(feature = "log_pretty_print"))]
790                debug!("SignHtlcTxMingle psbt {:?}", streamed);
791                #[cfg(feature = "log_pretty_print")]
792                debug!("SignHtlcTxMingle psbt {:#?}", streamed);
793
794                self.sign_withdrawal(&mut streamed, utxos)?;
795
796                Ok(Box::new(msgs::SignHtlcTxMingleReply { psbt: WithSize(streamed.psbt) }))
797            }
798            Message::SignSpliceTx(_m) => {
799                unimplemented!()
800            }
801            Message::SignCommitmentTx(m) => {
802                // TODO why not channel handler??
803                let channel_id = Self::channel_id(&m.peer_id, m.dbid);
804                let tx = m.tx.0;
805
806                // WORKAROUND - sometimes c-lightning calls handle_sign_commitment_tx
807                // with mutual close transactions.  We can tell the difference because
808                // the locktime field will be set to 0 for a mutual close.
809                let sig = if tx.lock_time.to_consensus_u32() == 0 {
810                    let opaths = extract_psbt_output_paths(&m.psbt.0.inner);
811                    self.node
812                        .with_channel(&channel_id, |chan| chan.sign_mutual_close_tx(&tx, &opaths))?
813                } else {
814                    // We ignore everything in the message other than the commitment number,
815                    // since the signer already has this info.
816                    self.node.with_channel(&channel_id, |chan| {
817                        chan.sign_holder_commitment_tx_phase2(m.commitment_number)
818                    })?
819                };
820                Ok(Box::new(msgs::SignCommitmentTxReply { signature: to_bitcoin_sig(sig) }))
821            }
822            Message::TipInfo(_) => {
823                let tracker = self.node.get_tracker();
824                Ok(Box::new(msgs::TipInfoReply {
825                    height: tracker.height(),
826                    block_hash: tracker.tip().0.block_hash(),
827                }))
828            }
829            Message::ForwardWatches(_) => {
830                let (txids, outpoints) = self.node.get_tracker().get_all_forward_watches();
831                Ok(Box::new(msgs::ForwardWatchesReply {
832                    txids: txids.into(),
833                    outpoints: outpoints.into(),
834                }))
835            }
836            Message::ReverseWatches(_) => {
837                let (txids, outpoints) = self.node.get_tracker().get_all_reverse_watches();
838                Ok(Box::new(msgs::ReverseWatchesReply {
839                    txids: txids.into(),
840                    outpoints: outpoints.into(),
841                }))
842            }
843            Message::AddBlock(m) => {
844                let mut tracker = self.node.get_tracker();
845                let proof = m
846                    .unspent_proof
847                    .ok_or(Status::invalid_argument("could not deserialize proof"))?;
848                match tracker
849                    .add_block(deserialize(m.header.0.as_slice()).expect("header"), proof.0)
850                {
851                    Ok(_) => (),
852                    Err(TrackerError::OrphanBlock(msg)) => {
853                        return Ok(Box::new(msgs::SignerError {
854                            code: msgs::CODE_ORPHAN_BLOCK,
855                            message: WireString(msg.into_bytes()),
856                        }));
857                    }
858                    Err(_e) => panic!("add_block"),
859                }
860                self.node
861                    .get_persister()
862                    .update_tracker(&self.node.get_id(), &tracker)
863                    .unwrap_or_else(|e| {
864                        panic!("{}: persist tracker failed: {:?}", self.node.log_prefix(), e)
865                    });
866                #[cfg(feature = "timeless_workaround")]
867                {
868                    // WORKAROUND for #206, #339, #235 - If our implementation has no clock use the
869                    // BlockHeader timestamp.
870                    use crate::handler::bitcoin::blockdata::block::Header as BlockHeader;
871                    use core::time::Duration;
872                    let header: BlockHeader =
873                        deserialize(m.header.0.as_slice()).expect("header again");
874                    let old_now = self.node.get_clock().now();
875                    let new_now = tracker.tip_time();
876                    // Don't allow retrograde time updates ...
877                    if new_now > old_now {
878                        self.node.get_clock().set_workaround_time(new_now);
879                    }
880                }
881                Ok(Box::new(msgs::AddBlockReply {}))
882            }
883            Message::RemoveBlock(m) => {
884                let mut tracker = self.node.get_tracker();
885                let proof = m
886                    .unspent_proof
887                    .map(|prf| deserialize(prf.0.as_slice()).expect("deserialize TxoProof"))
888                    .ok_or(Status::invalid_argument("could not deserialize proof"))?;
889                let prev_headers = Headers(m.prev_block_header, m.prev_filter_header);
890                tracker.remove_block(proof, prev_headers).expect("remove_block");
891                self.node
892                    .get_persister()
893                    .update_tracker(&self.node.get_id(), &tracker)
894                    .unwrap_or_else(|e| {
895                        panic!("{}: persist tracker failed: {:?}", self.node.log_prefix(), e)
896                    });
897                Ok(Box::new(msgs::RemoveBlockReply {}))
898            }
899            Message::BlockChunk(m) => {
900                let mut tracker = self.node.get_tracker();
901                tracker.block_chunk(m.hash, m.offset, &m.content.0).expect("block_chunk");
902                Ok(Box::new(msgs::BlockChunkReply {}))
903            }
904            Message::GetHeartbeat(_m) => {
905                let heartbeat = self.node.get_heartbeat();
906                let ser_hb = to_vec(&heartbeat).expect("heartbeat");
907                Ok(Box::new(msgs::GetHeartbeatReply { heartbeat: ser_hb.into() }))
908            }
909            Message::NodeInfo(_m) => {
910                let bip32 = self.node.get_account_extended_pubkey().encode();
911                let node_id = self.node.get_id().serialize();
912                let node_info = msgs::NodeInfoReply {
913                    network_name: WireString(self.node.network().to_string().into_bytes()),
914                    node_id: PubKey(node_id),
915                    bip32: ExtKey(bip32),
916                };
917                Ok(Box::new(node_info))
918            }
919            Message::Unknown(u) => {
920                unimplemented!("loop {}: unknown message type {}", self.id, u.message_type)
921            }
922            Message::SignNodeAnnouncement(m) => {
923                let message = m.announcement[64 + 2..].to_vec();
924                let sig = self.node.sign_node_announcement(&message)?;
925
926                Ok(Box::new(msgs::SignNodeAnnouncementReply {
927                    signature: Signature(sig.serialize_compact()),
928                }))
929            }
930            Message::SignChannelUpdate(m) => {
931                // NOTE this is called without a dbid by gossipd, so it gets dispatched to the root handler
932                let message = m.update[2 + 64..].to_vec();
933                let sig = self.node.sign_channel_update(&message)?;
934                let mut update = m.update;
935                update[2..2 + 64].copy_from_slice(&sig.serialize_compact());
936                Ok(Box::new(msgs::SignChannelUpdateReply { update }))
937            }
938            Message::SignGossipMessage(m) => {
939                let node_sig = self.node.sign_channel_update(&m.message.0)?;
940                Ok(Box::new(msgs::SignGossipMessageReply {
941                    signature: Signature(node_sig.serialize_compact()),
942                }))
943            }
944            Message::CheckPubKey(m) => Ok(Box::new(msgs::CheckPubKeyReply {
945                ok: self.node.check_wallet_pubkey(
946                    &[m.index],
947                    bitcoin::PublicKey::from_slice(&m.pubkey.0)
948                        .map_err(|_| Status::invalid_argument("bad public key"))?,
949                )?,
950            })),
951            Message::SignAnyDelayedPaymentToUs(m) => sign_delayed_payment_to_us(
952                &self.node,
953                &Self::channel_id(&m.peer_id, m.dbid),
954                m.commitment_number,
955                &m.tx,
956                &m.psbt.inner,
957                &m.wscript,
958                m.input,
959            ),
960            Message::SignAnyRemoteHtlcToUs(m) => sign_remote_htlc_to_us(
961                &self.node,
962                &Self::channel_id(&m.peer_id, m.dbid),
963                &m.remote_per_commitment_point,
964                &m.tx,
965                &m.psbt.inner,
966                &m.wscript,
967                m.option_anchors,
968                m.input,
969            ),
970            Message::SignAnyPenaltyToUs(m) => sign_penalty_to_us(
971                &self.node,
972                &Self::channel_id(&m.peer_id, m.dbid),
973                &m.revocation_secret,
974                &m.tx,
975                &m.psbt.inner,
976                &m.wscript,
977                m.input,
978            ),
979            Message::SignAnyLocalHtlcTx(m) => sign_local_htlc_tx(
980                &self.node,
981                &Self::channel_id(&m.peer_id, m.dbid),
982                m.commitment_number,
983                &m.tx,
984                &m.psbt.inner,
985                &m.wscript,
986                m.option_anchors,
987                m.input,
988            ),
989            Message::SignAnyChannelAnnouncement(m) => {
990                let (node_signature, bitcoin_signature) = sign_channel_announcement(
991                    &self.node,
992                    &Self::channel_id(&m.peer_id, m.dbid),
993                    &m.announcement,
994                )?;
995                Ok(Box::new(msgs::SignAnyChannelAnnouncementReply {
996                    node_signature,
997                    bitcoin_signature,
998                }))
999            }
1000            Message::SignAnchorspend(m) => {
1001                let mut streamed = m.psbt.0;
1002                let utxos = m.utxos;
1003
1004                #[cfg(not(feature = "log_pretty_print"))]
1005                debug!("SignAnchorspend psbt {:?}", streamed);
1006                #[cfg(feature = "log_pretty_print")]
1007                debug!("SignAnchorspend psbt {:#?}", streamed);
1008
1009                let channel_id = Self::channel_id(&m.peer_id, m.dbid);
1010                self.sign_withdrawal(&mut streamed, utxos)?;
1011                let anchor_redeemscript = self
1012                    .node
1013                    .with_channel(&channel_id, |channel| Ok(channel.get_anchor_redeemscript()))?;
1014                let anchor_scriptpubkey = anchor_redeemscript.to_v0_p2wsh();
1015
1016                let mut psbt = streamed.psbt().clone();
1017                let anchor_index = psbt
1018                    .inputs
1019                    .iter()
1020                    .position(|input| {
1021                        input
1022                            .witness_utxo
1023                            .as_ref()
1024                            .map(|txout| txout.script_pubkey == anchor_scriptpubkey)
1025                            .unwrap_or(false)
1026                    })
1027                    .ok_or_else(|| Status::invalid_argument("anchor not found in psbt"))?;
1028                let sig = self.node.with_channel(&channel_id, |channel| {
1029                    Ok(channel.sign_holder_anchor_input(&psbt.unsigned_tx, anchor_index)?)
1030                })?;
1031                let witness = vec![signature_to_bitcoin_vec(sig), anchor_redeemscript.to_bytes()];
1032                psbt.inputs[anchor_index].final_script_witness = Some(Witness::from_vec(witness));
1033                Ok(Box::new(msgs::SignAnchorspendReply {
1034                    psbt: WithSize(PsbtWrapper { inner: psbt }),
1035                }))
1036            }
1037            m => unimplemented!("loop {}: unimplemented message {:?}", self.id, m),
1038        }
1039    }
1040
1041    fn client_id(&self) -> u64 {
1042        self.id
1043    }
1044
1045    fn for_new_client(&self, client_id: u64, peer_id: PubKey, dbid: u64) -> ChannelHandler {
1046        let channel_id = Self::channel_id(&peer_id, dbid);
1047        ChannelHandler {
1048            id: client_id,
1049            node: Arc::clone(&self.node),
1050            protocol_version: self.protocol_version,
1051            peer_id: peer_id.0,
1052            dbid,
1053            channel_id,
1054        }
1055    }
1056
1057    fn node(&self) -> &Arc<Node> {
1058        &self.node
1059    }
1060}
1061
1062fn extract_output_path(
1063    bip32_derivation: &BTreeMap<PublicKey, KeySource>,
1064    tap_key_origins: &BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>,
1065) -> Vec<u32> {
1066    let path = if !bip32_derivation.is_empty() {
1067        if bip32_derivation.len() > 1 {
1068            unimplemented!("len > 1");
1069        }
1070        let (_fingerprint, path) = bip32_derivation.iter().next().unwrap().1;
1071        path.clone()
1072    } else if !tap_key_origins.is_empty() {
1073        if tap_key_origins.len() > 1 {
1074            unimplemented!("len > 1");
1075        }
1076        let (_xpub, (hashes, source)) = tap_key_origins.iter().next().unwrap();
1077        if !hashes.is_empty() {
1078            unimplemented!("hashes not empty");
1079        }
1080        source.1.clone()
1081    } else {
1082        DerivationPath::from(vec![])
1083    };
1084    path.into_iter().map(|i| i.clone().into()).collect()
1085}
1086
1087fn extract_psbt_output_paths(psbt: &PartiallySignedTransaction) -> Vec<Vec<u32>> {
1088    psbt.outputs
1089        .iter()
1090        .map(|o| extract_output_path(&o.bip32_derivation, &o.tap_key_origins))
1091        .collect::<Vec<Vec<u32>>>()
1092}
1093
1094/// Protocol handler
1095pub struct ChannelHandler {
1096    id: u64,
1097    node: Arc<Node>,
1098    protocol_version: u32,
1099    #[allow(unused)]
1100    peer_id: [u8; 33],
1101    dbid: u64,
1102    channel_id: ChannelId,
1103}
1104
1105impl ChannelHandler {
1106    /// A unique ID for this channel
1107    pub fn dbid(&self) -> u64 {
1108        self.dbid
1109    }
1110}
1111
1112impl Handler for ChannelHandler {
1113    fn do_handle(&self, msg: Message) -> Result<Box<dyn SerBolt>> {
1114        match msg {
1115            Message::Memleak(_m) => Ok(Box::new(msgs::MemleakReply { result: false })),
1116            Message::CheckFutureSecret(m) => {
1117                let secret_key = SecretKey::from_slice(&m.secret.0)
1118                    .map_err(|_| Status::invalid_argument("bad secret key"))?;
1119                let result = self.node.with_channel(&self.channel_id, |chan| {
1120                    chan.check_future_secret(m.commitment_number, &secret_key)
1121                })?;
1122                Ok(Box::new(msgs::CheckFutureSecretReply { result }))
1123            }
1124            Message::Ecdh(m) => {
1125                // TODO DRY with root handler
1126                let pubkey = PublicKey::from_slice(&m.point.0).expect("pubkey");
1127                let secret = self.node.ecdh(&pubkey).as_slice().try_into().unwrap();
1128                Ok(Box::new(msgs::EcdhReply { secret: Secret(secret) }))
1129            }
1130            Message::GetPerCommitmentPoint(m) => {
1131                let commitment_number = m.commitment_number;
1132                let res: core::result::Result<(PublicKey, Option<SecretKey>), status::Status> =
1133                    self.node.with_channel_base(&self.channel_id, |base| {
1134                        let point = base.get_per_commitment_point(commitment_number)?;
1135                        let secret = if self.protocol_version < PROTOCOL_VERSION_NO_SECRET
1136                            && commitment_number >= 2
1137                        {
1138                            Some(base.get_per_commitment_secret(commitment_number - 2)?)
1139                        } else {
1140                            None
1141                        };
1142                        Ok((point, secret))
1143                    });
1144
1145                let (point, old_secret) = res?;
1146
1147                let old_secret_reply =
1148                    old_secret.clone().map(|s| DisclosedSecret(s[..].try_into().unwrap()));
1149                Ok(Box::new(msgs::GetPerCommitmentPointReply {
1150                    point: PubKey(point.serialize()),
1151                    secret: old_secret_reply,
1152                }))
1153            }
1154            Message::GetPerCommitmentPoint2(m) => {
1155                let commitment_number = m.commitment_number;
1156                let point = self.node.with_channel_base(&self.channel_id, |base| {
1157                    base.get_per_commitment_point(commitment_number)
1158                })?;
1159
1160                Ok(Box::new(msgs::GetPerCommitmentPoint2Reply { point: PubKey(point.serialize()) }))
1161            }
1162            Message::SetupChannel(m) => {
1163                let funding_outpoint =
1164                    OutPoint { txid: m.funding_txid, vout: m.funding_txout as u32 };
1165
1166                let holder_shutdown_script = if m.local_shutdown_script.is_empty() {
1167                    None
1168                } else {
1169                    Some(ScriptBuf::from_bytes(m.local_shutdown_script.as_slice().to_vec()))
1170                };
1171
1172                let points = m.remote_basepoints;
1173                let counterparty_points = ChannelPublicKeys {
1174                    funding_pubkey: extract_pubkey(&m.remote_funding_pubkey),
1175                    revocation_basepoint: points.revocation.into(),
1176                    payment_point: points.payment.into(),
1177                    delayed_payment_basepoint: points.delayed_payment.into(),
1178                    htlc_basepoint: points.htlc.into(),
1179                };
1180
1181                let counterparty_shutdown_script = if m.remote_shutdown_script.is_empty() {
1182                    None
1183                } else {
1184                    Some(ScriptBuf::from_bytes(m.remote_shutdown_script.as_slice().to_vec()))
1185                };
1186
1187                // FIXME
1188                let holder_shutdown_key_path = vec![];
1189                let setup = ChannelSetup {
1190                    is_outbound: m.is_outbound,
1191                    channel_value_sat: m.channel_value,
1192                    push_value_msat: m.push_value,
1193                    funding_outpoint,
1194                    holder_selected_contest_delay: m.to_self_delay as u16,
1195                    counterparty_points,
1196                    holder_shutdown_script,
1197                    counterparty_selected_contest_delay: m.remote_to_self_delay as u16,
1198                    counterparty_shutdown_script,
1199                    commitment_type: channel_type_to_commitment_type(&m.channel_type),
1200                };
1201                self.node.setup_channel(
1202                    self.channel_id.clone(),
1203                    None,
1204                    setup,
1205                    &holder_shutdown_key_path,
1206                )?;
1207
1208                Ok(Box::new(msgs::SetupChannelReply {}))
1209            }
1210            Message::CheckOutpoint(m) => {
1211                let funding_outpoint =
1212                    OutPoint { txid: m.funding_txid, vout: m.funding_txout as u32 };
1213                // FIXME - make the call on the node!
1214                warn!("null placeholder for CheckOutpoint on outpoint {:?}", funding_outpoint);
1215                Ok(Box::new(msgs::CheckOutpointReply { is_buried: true }))
1216            }
1217            Message::LockOutpoint(m) => {
1218                let funding_outpoint =
1219                    OutPoint { txid: m.funding_txid, vout: m.funding_txout as u32 };
1220                // FIXME - make the call on the node!
1221                warn!("null placeholder for LockOutpoint on outpoint {:?}", funding_outpoint);
1222                Ok(Box::new(msgs::LockOutpointReply {}))
1223            }
1224            Message::SignRemoteHtlcTx(m) => {
1225                let psbt = &m.psbt.inner;
1226                let tx = m.tx.0;
1227                let remote_per_commitment_point =
1228                    PublicKey::from_slice(&m.remote_per_commitment_point.0).expect("pubkey");
1229                assert_eq!(psbt.outputs.len(), 1);
1230                assert_eq!(psbt.inputs.len(), 1);
1231                assert_eq!(tx.output.len(), 1);
1232                assert_eq!(tx.input.len(), 1);
1233                let redeemscript = ScriptBuf::from(m.wscript.0);
1234                let htlc_amount_sat = psbt.inputs[0]
1235                    .witness_utxo
1236                    .as_ref()
1237                    .expect("will only spend witness UTXOs")
1238                    .value;
1239                let output_witscript =
1240                    psbt.outputs[0].witness_script.as_ref().expect("output witscript");
1241                let sig = self.node.with_channel(&self.channel_id, |chan| {
1242                    chan.sign_counterparty_htlc_tx(
1243                        &tx,
1244                        &remote_per_commitment_point,
1245                        &redeemscript,
1246                        htlc_amount_sat,
1247                        &output_witscript,
1248                    )
1249                })?;
1250
1251                Ok(Box::new(msgs::SignTxReply { signature: typed_to_bitcoin_sig(sig) }))
1252            }
1253            Message::SignLocalHtlcTx2(m) => {
1254                let signature = self.node.with_channel(&self.channel_id, |chan| {
1255                    chan.sign_holder_htlc_tx_phase2(
1256                        &m.tx.0,
1257                        m.input,
1258                        m.per_commitment_number,
1259                        m.feerate_per_kw,
1260                        m.offered,
1261                        m.cltv_expiry,
1262                        m.htlc_amount_msat,
1263                        PaymentHash(m.payment_hash.0),
1264                    )
1265                })?;
1266                Ok(Box::new(msgs::SignTxReply { signature: typed_to_bitcoin_sig(signature) }))
1267            }
1268            Message::SignRemoteCommitmentTx(m) => {
1269                let psbt = &m.psbt.inner;
1270                let witscripts = extract_psbt_witscripts(&psbt);
1271                let tx = m.tx;
1272                let remote_per_commitment_point =
1273                    PublicKey::from_slice(&m.remote_per_commitment_point.0).expect("pubkey");
1274                let commit_num = m.commitment_number;
1275                let feerate_sat_per_kw = m.feerate;
1276                // Flip offered and received
1277                let (offered_htlcs, received_htlcs) = extract_htlcs(&m.htlcs);
1278                let sig = self.node.with_channel(&self.channel_id, |chan| {
1279                    chan.sign_counterparty_commitment_tx(
1280                        &tx,
1281                        &witscripts,
1282                        &remote_per_commitment_point,
1283                        commit_num,
1284                        feerate_sat_per_kw,
1285                        offered_htlcs.clone(),
1286                        received_htlcs.clone(),
1287                    )
1288                })?;
1289                Ok(Box::new(msgs::SignTxReply { signature: to_bitcoin_sig(sig) }))
1290            }
1291            Message::SignRemoteCommitmentTx2(m) => {
1292                let remote_per_commitment_point =
1293                    PublicKey::from_slice(&m.remote_per_commitment_point.0).expect("pubkey");
1294                let commit_num = m.commitment_number;
1295                let feerate_sat_per_kw = m.feerate;
1296                // Flip offered and received
1297                let (offered_htlcs, received_htlcs) = extract_htlcs(&m.htlcs);
1298                let (sig, htlc_sigs) = self.node.with_channel(&self.channel_id, |chan| {
1299                    chan.sign_counterparty_commitment_tx_phase2(
1300                        &remote_per_commitment_point,
1301                        commit_num,
1302                        feerate_sat_per_kw,
1303                        m.to_local_value_sat,
1304                        m.to_remote_value_sat,
1305                        offered_htlcs.clone(),
1306                        received_htlcs.clone(),
1307                    )
1308                })?;
1309                Ok(Box::new(msgs::SignCommitmentTxWithHtlcsReply {
1310                    signature: to_bitcoin_sig(sig),
1311                    htlc_signatures: Array(
1312                        htlc_sigs.into_iter().map(|s| to_bitcoin_sig(s)).collect(),
1313                    ),
1314                }))
1315            }
1316            Message::SignDelayedPaymentToUs(m) => sign_delayed_payment_to_us(
1317                &self.node,
1318                &self.channel_id,
1319                m.commitment_number,
1320                &m.tx,
1321                &m.psbt.inner,
1322                &m.wscript,
1323                0,
1324            ),
1325            Message::SignRemoteHtlcToUs(m) => sign_remote_htlc_to_us(
1326                &self.node,
1327                &self.channel_id,
1328                &m.remote_per_commitment_point,
1329                &m.tx,
1330                &m.psbt.inner,
1331                &m.wscript,
1332                m.option_anchors,
1333                0,
1334            ),
1335            Message::SignLocalHtlcTx(m) => sign_local_htlc_tx(
1336                &self.node,
1337                &self.channel_id,
1338                m.commitment_number,
1339                &m.tx,
1340                &m.psbt.inner,
1341                &m.wscript,
1342                m.option_anchors,
1343                0,
1344            ),
1345            Message::SignMutualCloseTx(m) => {
1346                let psbt = &m.psbt.inner;
1347                let tx = m.tx;
1348                let opaths = extract_psbt_output_paths(&psbt);
1349                debug!(
1350                    "mutual close derivation paths {:?} addresses {:?}",
1351                    opaths,
1352                    tx.output
1353                        .iter()
1354                        .map(|o| Address::from_script(&o.script_pubkey, self.node.network()))
1355                        .collect::<Vec<_>>()
1356                );
1357                let sig = self.node.with_channel(&self.channel_id, |chan| {
1358                    chan.sign_mutual_close_tx(&tx, &opaths)
1359                })?;
1360                Ok(Box::new(msgs::SignTxReply { signature: to_bitcoin_sig(sig) }))
1361            }
1362            Message::SignMutualCloseTx2(m) => {
1363                let sig = self.node.with_channel(&self.channel_id, |chan| {
1364                    chan.sign_mutual_close_tx_phase2(
1365                        m.to_local_value_sat,
1366                        m.to_remote_value_sat,
1367                        &to_script(&m.local_script),
1368                        &to_script(&m.remote_script),
1369                        &m.local_wallet_path_hint,
1370                    )
1371                })?;
1372                Ok(Box::new(msgs::SignTxReply { signature: to_bitcoin_sig(sig) }))
1373            }
1374            Message::ValidateCommitmentTx(m) => {
1375                let psbt = &m.psbt.inner;
1376                let witscripts = extract_psbt_witscripts(&psbt);
1377                let tx = m.tx.0;
1378                let commit_num = m.commitment_number;
1379                let feerate_sat_per_kw = m.feerate;
1380                let (received_htlcs, offered_htlcs) = extract_htlcs(&m.htlcs);
1381                let commit_sig =
1382                    ecdsa::Signature::from_compact(&m.signature.signature.0).expect("signature");
1383                assert_eq!(m.signature.sighash, EcdsaSighashType::All as u8);
1384                let htlc_sigs: Vec<_> = m
1385                    .htlc_signatures
1386                    .iter()
1387                    .map(|s| {
1388                        assert!(
1389                            s.sighash == EcdsaSighashType::All as u8
1390                                || s.sighash == EcdsaSighashType::SinglePlusAnyoneCanPay as u8
1391                        );
1392                        ecdsa::Signature::from_compact(&s.signature.0).expect("signature")
1393                    })
1394                    .collect();
1395                let (next_per_commitment_point, old_secret) =
1396                    self.node.with_channel(&self.channel_id, |chan| {
1397                        chan.validate_holder_commitment_tx(
1398                            &tx,
1399                            &witscripts,
1400                            commit_num,
1401                            feerate_sat_per_kw,
1402                            offered_htlcs.clone(),
1403                            received_htlcs.clone(),
1404                            &commit_sig,
1405                            &htlc_sigs,
1406                        )?;
1407                        if self.protocol_version < PROTOCOL_VERSION_REVOKE {
1408                            // The older protcol presumes the previous is immediately revoked
1409                            chan.revoke_previous_holder_commitment(commit_num)
1410                        } else {
1411                            // The newer protocol defers until an explicit `RevokeCommitmentTx`
1412                            if commit_num > 0 {
1413                                Ok((chan.get_per_commitment_point(commit_num + 1)?, None))
1414                            } else {
1415                                // Commitment 0 is special because it doesn't
1416                                // have a previous commitment.  Since the
1417                                // revocation of the previous commitment normally
1418                                // makes a new commitment "current" this final
1419                                // step must be invoked explicitly.
1420                                Ok((chan.activate_initial_commitment()?, None))
1421                            }
1422                        }
1423                    })?;
1424                let old_secret_reply =
1425                    old_secret.map(|s| DisclosedSecret(s[..].try_into().unwrap()));
1426                Ok(Box::new(msgs::ValidateCommitmentTxReply {
1427                    next_per_commitment_point: PubKey(next_per_commitment_point.serialize()),
1428                    old_commitment_secret: old_secret_reply,
1429                }))
1430            }
1431            Message::ValidateCommitmentTx2(m) => {
1432                let commit_num = m.commitment_number;
1433                let feerate_sat_per_kw = m.feerate;
1434                let (received_htlcs, offered_htlcs) = extract_htlcs(&m.htlcs);
1435                let commit_sig =
1436                    ecdsa::Signature::from_compact(&m.signature.signature.0).expect("signature");
1437                assert_eq!(m.signature.sighash, EcdsaSighashType::All as u8);
1438                let htlc_sigs: Vec<_> = m
1439                    .htlc_signatures
1440                    .iter()
1441                    .map(|s| {
1442                        assert!(
1443                            s.sighash == EcdsaSighashType::All as u8
1444                                || s.sighash == EcdsaSighashType::SinglePlusAnyoneCanPay as u8
1445                        );
1446                        ecdsa::Signature::from_compact(&s.signature.0).expect("signature")
1447                    })
1448                    .collect();
1449                let (next_per_commitment_point, old_secret) =
1450                    self.node.with_channel(&self.channel_id, |chan| {
1451                        chan.validate_holder_commitment_tx_phase2(
1452                            commit_num,
1453                            feerate_sat_per_kw,
1454                            m.to_local_value_sat,
1455                            m.to_remote_value_sat,
1456                            offered_htlcs.clone(),
1457                            received_htlcs.clone(),
1458                            &commit_sig,
1459                            &htlc_sigs,
1460                        )?;
1461                        if self.protocol_version < PROTOCOL_VERSION_REVOKE {
1462                            // The older protcol presumes the previous is immediately revoked
1463                            chan.revoke_previous_holder_commitment(commit_num)
1464                        } else {
1465                            // The newer protocol defers until an explicit `RevokeCommitmentTx`
1466                            if commit_num > 0 {
1467                                Ok((chan.get_per_commitment_point(commit_num + 1)?, None))
1468                            } else {
1469                                // Commitment 0 is special because it doesn't
1470                                // have a previous commitment.  Since the
1471                                // revocation of the previous commitment normally
1472                                // makes a new commitment "current" this final
1473                                // step must be invoked explicitly.
1474                                Ok((chan.activate_initial_commitment()?, None))
1475                            }
1476                        }
1477                    })?;
1478                let old_secret_reply =
1479                    old_secret.map(|s| DisclosedSecret(s[..].try_into().unwrap()));
1480                Ok(Box::new(msgs::ValidateCommitmentTxReply {
1481                    next_per_commitment_point: PubKey(next_per_commitment_point.serialize()),
1482                    old_commitment_secret: old_secret_reply,
1483                }))
1484            }
1485            Message::RevokeCommitmentTx(m) => {
1486                if self.protocol_version < PROTOCOL_VERSION_REVOKE {
1487                    return Err(Status::invalid_argument(format!(
1488                        "RevokeCommitmentTx called with hsmd_protocol_version {} < {}",
1489                        self.protocol_version, PROTOCOL_VERSION_REVOKE,
1490                    )))?;
1491                }
1492                let commit_num = m.commitment_number;
1493                let (next_per_commitment_point, old_secret) =
1494                    self.node.with_channel(&self.channel_id, |chan| {
1495                        chan.revoke_previous_holder_commitment(commit_num + 1)
1496                    })?;
1497                let old_secret_reply =
1498                    old_secret.map(|s| DisclosedSecret(s[..].try_into().unwrap()));
1499                let next_per_commitment_point = PubKey(next_per_commitment_point.serialize());
1500                let old_commitment_secret = old_secret_reply.ok_or_else(|| {
1501                    Status::invalid_argument(format!("no old secret for commitment {}", commit_num))
1502                })?;
1503                Ok(Box::new(msgs::RevokeCommitmentTxReply {
1504                    next_per_commitment_point,
1505                    old_commitment_secret,
1506                }))
1507            }
1508
1509            Message::SignLocalCommitmentTx2(m) => {
1510                let sig = self.node.with_channel(&self.channel_id, |chan| {
1511                    chan.sign_holder_commitment_tx_phase2(m.commitment_number)
1512                })?;
1513                Ok(Box::new(msgs::SignCommitmentTxReply { signature: to_bitcoin_sig(sig) }))
1514            }
1515            Message::ValidateRevocation(m) => {
1516                let revoke_num = m.commitment_number;
1517                let old_secret = SecretKey::from_slice(&m.commitment_secret.0).expect("secret");
1518                self.node.with_channel(&self.channel_id, |chan| {
1519                    chan.validate_counterparty_revocation(revoke_num, &old_secret)
1520                })?;
1521                Ok(Box::new(msgs::ValidateRevocationReply {}))
1522            }
1523            Message::SignPenaltyToUs(m) => sign_penalty_to_us(
1524                &self.node,
1525                &self.channel_id,
1526                &m.revocation_secret,
1527                &m.tx,
1528                &m.psbt.inner,
1529                &m.wscript,
1530                0,
1531            ),
1532            Message::SignChannelAnnouncement(m) => {
1533                let (node_signature, bitcoin_signature) =
1534                    sign_channel_announcement(&self.node, &self.channel_id, &m.announcement)?;
1535                Ok(Box::new(msgs::SignChannelAnnouncementReply {
1536                    node_signature,
1537                    bitcoin_signature,
1538                }))
1539            }
1540            Message::Unknown(u) => {
1541                unimplemented!("cloop {}: unknown message type {}", self.id, u.message_type)
1542            }
1543            m => unimplemented!("cloop {}: unimplemented message {:?}", self.id, m),
1544        }
1545    }
1546
1547    fn client_id(&self) -> u64 {
1548        self.id
1549    }
1550
1551    fn for_new_client(&self, _client_id: u64, _peer_id: PubKey, _dbid: u64) -> ChannelHandler {
1552        unimplemented!("cannot create a sub-handler from a channel handler");
1553    }
1554
1555    fn node(&self) -> &Arc<Node> {
1556        &self.node
1557    }
1558}
1559
1560fn sign_delayed_payment_to_us(
1561    node: &Node,
1562    channel_id: &ChannelId,
1563    commitment_number: u64,
1564    tx: &Transaction,
1565    psbt: &PartiallySignedTransaction,
1566    wscript: &Octets,
1567    input: u32,
1568) -> Result<Box<dyn SerBolt>> {
1569    // FIXME CLN is sending an incorrect tx in the psbt, so use the outer one in the message instead
1570    let commitment_number = commitment_number;
1571    let redeemscript = ScriptBuf::from(wscript.0.clone());
1572    let input = input as usize;
1573    let htlc_amount_sat =
1574        psbt.inputs[input].witness_utxo.as_ref().expect("will only spend witness UTXOs").value;
1575    let wallet_paths = extract_psbt_output_paths(&psbt);
1576    let sig = node.with_channel(channel_id, |chan| {
1577        chan.sign_delayed_sweep(
1578            &tx,
1579            input,
1580            commitment_number,
1581            &redeemscript,
1582            htlc_amount_sat,
1583            &wallet_paths[0],
1584        )
1585    })?;
1586    Ok(Box::new(msgs::SignTxReply {
1587        signature: BitcoinSignature {
1588            signature: Signature(sig.serialize_compact()),
1589            sighash: EcdsaSighashType::All as u8,
1590        },
1591    }))
1592}
1593
1594fn sign_remote_htlc_to_us(
1595    node: &Node,
1596    channel_id: &ChannelId,
1597    remote_per_commitment_point: &PubKey,
1598    tx: &Transaction,
1599    psbt: &PartiallySignedTransaction,
1600    wscript: &Octets,
1601    _option_anchors: bool,
1602    input: u32,
1603) -> Result<Box<dyn SerBolt>> {
1604    let remote_per_commitment_point =
1605        PublicKey::from_slice(&remote_per_commitment_point.0).expect("pubkey");
1606    let redeemscript = ScriptBuf::from(wscript.0.clone());
1607    let input = input as usize;
1608    let htlc_amount_sat =
1609        psbt.inputs[input].witness_utxo.as_ref().expect("will only spend witness UTXOs").value;
1610    let wallet_paths = extract_psbt_output_paths(&psbt);
1611    let sig = node.with_channel(channel_id, |chan| {
1612        chan.sign_counterparty_htlc_sweep(
1613            &tx,
1614            input,
1615            &remote_per_commitment_point,
1616            &redeemscript,
1617            htlc_amount_sat,
1618            &wallet_paths[0],
1619        )
1620    })?;
1621    Ok(Box::new(msgs::SignTxReply {
1622        signature: BitcoinSignature {
1623            signature: Signature(sig.serialize_compact()),
1624            sighash: EcdsaSighashType::All as u8,
1625        },
1626    }))
1627}
1628
1629fn sign_local_htlc_tx(
1630    node: &Node,
1631    channel_id: &ChannelId,
1632    commitment_number: u64,
1633    tx: &Transaction,
1634    psbt: &PartiallySignedTransaction,
1635    wscript: &Octets,
1636    _option_anchors: bool,
1637    input: u32,
1638) -> Result<Box<dyn SerBolt>> {
1639    let commitment_number = commitment_number;
1640    let redeemscript = ScriptBuf::from(wscript.0.clone());
1641    let input = input as usize;
1642    let htlc_amount_sat =
1643        psbt.inputs[input].witness_utxo.as_ref().expect("will only spend witness UTXOs").value;
1644    let output_witscript: &ScriptBuf =
1645        psbt.outputs[0].witness_script.as_ref().expect("output witscript");
1646    let sig = node.with_channel(channel_id, |chan| {
1647        chan.sign_holder_htlc_tx(
1648            &tx,
1649            commitment_number,
1650            None,
1651            &redeemscript,
1652            htlc_amount_sat,
1653            output_witscript,
1654        )
1655    })?;
1656    Ok(Box::new(msgs::SignTxReply {
1657        signature: BitcoinSignature {
1658            signature: Signature(sig.sig.serialize_compact()),
1659            sighash: sig.typ as u8,
1660        },
1661    }))
1662}
1663
1664fn sign_penalty_to_us(
1665    node: &Node,
1666    channel_id: &ChannelId,
1667    revocation_secret: &DisclosedSecret,
1668    tx: &Transaction,
1669    psbt: &PartiallySignedTransaction,
1670    wscript: &Octets,
1671    input: u32,
1672) -> Result<Box<dyn SerBolt>> {
1673    let revocation_secret = SecretKey::from_slice(&revocation_secret.0).expect("secret");
1674    let redeemscript = ScriptBuf::from(wscript.0.clone());
1675    let input = input as usize;
1676    let htlc_amount_sat =
1677        psbt.inputs[input].witness_utxo.as_ref().expect("will only spend witness UTXOs").value;
1678    let wallet_paths = extract_psbt_output_paths(&psbt);
1679    let sig = node.with_channel(&channel_id, |chan| {
1680        chan.sign_justice_sweep(
1681            &tx,
1682            input,
1683            &revocation_secret,
1684            &redeemscript,
1685            htlc_amount_sat,
1686            &wallet_paths[0],
1687        )
1688    })?;
1689    Ok(Box::new(msgs::SignTxReply {
1690        signature: BitcoinSignature {
1691            signature: Signature(sig.serialize_compact()),
1692            sighash: EcdsaSighashType::All as u8,
1693        },
1694    }))
1695}
1696
1697fn sign_channel_announcement(
1698    node: &Node,
1699    channel_id: &ChannelId,
1700    announcement: &Octets,
1701) -> Result<(Signature, Signature)> {
1702    let message = announcement[256 + 2..].to_vec();
1703    let bitcoin_sig = node.with_channel(channel_id, |chan| {
1704        Ok(chan.sign_channel_announcement_with_funding_key(&message))
1705    })?;
1706    let node_sig = node.sign_channel_update(&message)?;
1707    Ok((Signature(node_sig.serialize_compact()), Signature(bitcoin_sig.serialize_compact())))
1708}
1709
1710fn extract_pubkey(key: &PubKey) -> PublicKey {
1711    PublicKey::from_slice(&key.0).expect("pubkey")
1712}
1713
1714fn extract_psbt_witscripts(psbt: &PartiallySignedTransaction) -> Vec<Vec<u8>> {
1715    psbt.outputs
1716        .iter()
1717        .map(|o| o.witness_script.clone().unwrap_or(ScriptBuf::new()))
1718        .map(|s| s[..].to_bytes())
1719        .collect()
1720}
1721
1722fn extract_htlcs(htlcs: &Vec<Htlc>) -> (Vec<HTLCInfo2>, Vec<HTLCInfo2>) {
1723    let offered_htlcs: Vec<HTLCInfo2> = htlcs
1724        .iter()
1725        .filter(|h| h.side == Htlc::LOCAL)
1726        .map(|h| HTLCInfo2 {
1727            value_sat: h.amount / 1000,
1728            payment_hash: PaymentHash(h.payment_hash.0),
1729            cltv_expiry: h.ctlv_expiry,
1730        })
1731        .collect();
1732    let received_htlcs: Vec<HTLCInfo2> = htlcs
1733        .iter()
1734        .filter(|h| h.side == Htlc::REMOTE)
1735        .map(|h| HTLCInfo2 {
1736            value_sat: h.amount / 1000,
1737            payment_hash: PaymentHash(h.payment_hash.0),
1738            cltv_expiry: h.ctlv_expiry,
1739        })
1740        .collect();
1741    (received_htlcs, offered_htlcs)
1742}
1743
1744#[cfg(test)]
1745mod tests {
1746    use super::*;
1747    use lightning_signer::channel::CommitmentType;
1748
1749    #[test]
1750    fn test_der() {
1751        let sig = [
1752            83, 1, 22, 118, 14, 225, 143, 45, 119, 59, 51, 81, 117, 109, 12, 76, 141, 142, 137,
1753            167, 117, 28, 98, 150, 245, 134, 254, 105, 172, 236, 170, 4, 24, 195, 101, 175, 186,
1754            97, 224, 127, 128, 202, 94, 58, 56, 171, 51, 106, 153, 217, 229, 22, 217, 94, 169, 47,
1755            55, 71, 237, 36, 128, 102, 148, 61,
1756        ];
1757        ecdsa::Signature::from_compact(&sig).expect("signature");
1758    }
1759
1760    #[test]
1761    fn test_channel_type_to_commitment_type() {
1762        assert_eq!(
1763            channel_type_to_commitment_type(&vec![0x10_u8, 0x10_u8, 0x00_u8]),
1764            CommitmentType::Anchors
1765        );
1766        assert_eq!(
1767            channel_type_to_commitment_type(&vec![0x10_u8, 0x00_u8]),
1768            CommitmentType::StaticRemoteKey
1769        );
1770        assert_eq!(
1771            channel_type_to_commitment_type(&vec![0x00_u8, 0x00_u8]),
1772            CommitmentType::Legacy
1773        );
1774    }
1775
1776    #[test]
1777    #[should_panic]
1778    fn test_channel_type_to_commitment_type_panic() {
1779        channel_type_to_commitment_type(&vec![0x10_u8, 0x00_u8, 0x00_u8]);
1780    }
1781}