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