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