use lightning::chain;
use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
-use lightning::chain::keysinterface::{ChannelKeys, KeysInterface};
+use lightning::chain::keysinterface::{Sign, KeysInterface};
use lightning::ln::channelmanager::ChannelManager;
use lightning::util::logger::Logger;
-use lightning::util::ser::Writeable;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
/// [`thread_handle`]: struct.BackgroundProcessor.html#structfield.thread_handle
/// [`ChannelManager::write`]: ../lightning/ln/channelmanager/struct.ChannelManager.html#method.write
/// [`FilesystemPersister::persist_manager`]: ../lightning_persister/struct.FilesystemPersister.html#impl
- pub fn start<PM, ChanSigner, M, T, K, F, L>(persist_manager: PM, manager: Arc<ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>>, logger: Arc<L>) -> Self
- where ChanSigner: 'static + ChannelKeys + Writeable,
- M: 'static + chain::Watch<Keys=ChanSigner>,
+ pub fn start<PM, Signer, M, T, K, F, L>(persist_manager: PM, manager: Arc<ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>>, logger: Arc<L>) -> Self
+ where Signer: 'static + Sign,
+ M: 'static + chain::Watch<Signer>,
T: 'static + BroadcasterInterface,
- K: 'static + KeysInterface<ChanKeySigner=ChanSigner>,
+ K: 'static + KeysInterface<Signer=Signer>,
F: 'static + FeeEstimator,
L: 'static + Logger,
- PM: 'static + Send + Fn(&ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>,
+ PM: 'static + Send + Fn(&ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>,
{
let stop_thread = Arc::new(AtomicBool::new(false));
let stop_thread_clone = stop_thread.clone();
use lightning::chain;
use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
use lightning::chain::chainmonitor;
- use lightning::chain::keysinterface::{ChannelKeys, InMemoryChannelKeys, KeysInterface, KeysManager};
+ use lightning::chain::keysinterface::{Sign, InMemorySigner, KeysInterface, KeysManager};
use lightning::chain::transaction::OutPoint;
use lightning::get_event_msg;
use lightning::ln::channelmanager::{ChannelManager, SimpleArcChannelManager};
use std::time::Duration;
use super::BackgroundProcessor;
- type ChainMonitor = chainmonitor::ChainMonitor<InMemoryChannelKeys, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
+ type ChainMonitor = chainmonitor::ChainMonitor<InMemorySigner, Arc<test_utils::TestChainSource>, Arc<test_utils::TestBroadcaster>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>, Arc<FilesystemPersister>>;
struct Node {
node: SimpleArcChannelManager<ChainMonitor, test_utils::TestBroadcaster, test_utils::TestFeeEstimator, test_utils::TestLogger>,
// Initiate the background processors to watch each node.
let data_dir = nodes[0].persister.get_data_dir();
- let callback = move |node: &ChannelManager<InMemoryChannelKeys, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
+ let callback = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone());
// Go through the channel creation process until each node should have something persisted.
// `CHAN_FRESHNESS_TIMER`.
let nodes = create_nodes(1, "test_chan_freshness_called".to_string());
let data_dir = nodes[0].persister.get_data_dir();
- let callback = move |node: &ChannelManager<InMemoryChannelKeys, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
+ let callback = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
let bg_processor = BackgroundProcessor::start(callback, nodes[0].node.clone(), nodes[0].logger.clone());
loop {
let log_entries = nodes[0].logger.lines.lock().unwrap();
#[test]
fn test_persist_error() {
// Test that if we encounter an error during manager persistence, the thread panics.
- fn persist_manager<ChanSigner, M, T, K, F, L>(_data: &ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>
- where ChanSigner: 'static + ChannelKeys + Writeable,
- M: 'static + chain::Watch<Keys=ChanSigner>,
+ fn persist_manager<Signer, M, T, K, F, L>(_data: &ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>) -> Result<(), std::io::Error>
+ where Signer: 'static + Sign,
+ M: 'static + chain::Watch<Signer>,
T: 'static + BroadcasterInterface,
- K: 'static + KeysInterface<ChanKeySigner=ChanSigner>,
+ K: 'static + KeysInterface<Signer=Signer>,
F: 'static + FeeEstimator,
L: 'static + Logger,
{
use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent};
use lightning::chain::transaction::OutPoint;
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
-use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys};
+use lightning::chain::keysinterface::{KeysInterface, InMemorySigner};
use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, PaymentSendFailure, ChannelManagerReadArgs};
use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, DecodeError, ErrorAction, UpdateAddHTLC, Init};
-use lightning::util::enforcing_trait_impls::{EnforcingChannelKeys, INITIAL_REVOKED_COMMITMENT_NUMBER};
+use lightning::util::enforcing_trait_impls::{EnforcingSigner, INITIAL_REVOKED_COMMITMENT_NUMBER};
use lightning::util::errors::APIError;
use lightning::util::events;
use lightning::util::logger::Logger;
struct TestChainMonitor {
pub logger: Arc<dyn Logger>,
- pub chain_monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
+ pub chain_monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
// If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
// logic will automatically force-close our channels for us (as we don't have an up-to-date
}
}
}
-impl chain::Watch for TestChainMonitor {
- type Keys = EnforcingChannelKeys;
-
- fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+impl chain::Watch<EnforcingSigner> for TestChainMonitor {
+ fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
let mut ser = VecWriter(Vec::new());
monitor.write(&mut ser).unwrap();
if let Some(_) = self.latest_monitors.lock().unwrap().insert(funding_txo, (monitor.get_latest_update_id(), ser.0)) {
hash_map::Entry::Occupied(entry) => entry,
hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
};
- let mut deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::
+ let mut deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::
read(&mut Cursor::new(&map_entry.get().1), &OnlyReadsKeysInterface {}).unwrap().1;
deserialized_monitor.update_monitor(&update, &&TestBroadcaster{}, &&FuzzEstimator{}, &self.logger).unwrap();
let mut ser = VecWriter(Vec::new());
revoked_commitments: Mutex<HashMap<[u8;32], Arc<Mutex<u64>>>>,
}
impl KeysInterface for KeyProvider {
- type ChanKeySigner = EnforcingChannelKeys;
+ type Signer = EnforcingSigner;
fn get_node_secret(&self) -> SecretKey {
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_id]).unwrap()
PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, self.node_id]).unwrap())
}
- fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
+ fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
let secp_ctx = Secp256k1::signing_only();
let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
- let keys = InMemoryChannelKeys::new(
+ let keys = InMemorySigner::new(
&secp_ctx,
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, self.node_id]).unwrap(),
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, self.node_id]).unwrap(),
[0; 32],
);
let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
- EnforcingChannelKeys::new_with_revoked(keys, revoked_commitment, false)
+ EnforcingSigner::new_with_revoked(keys, revoked_commitment, false)
}
fn get_secure_random_bytes(&self) -> [u8; 32] {
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, id, 11, self.node_id]
}
- fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::ChanKeySigner, DecodeError> {
+ fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, DecodeError> {
let mut reader = std::io::Cursor::new(buffer);
- let inner: InMemoryChannelKeys = Readable::read(&mut reader)?;
+ let inner: InMemorySigner = Readable::read(&mut reader)?;
let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed);
let last_commitment_number = Readable::read(&mut reader)?;
- Ok(EnforcingChannelKeys {
+ Ok(EnforcingSigner {
inner,
last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
revoked_commitment,
}
}
-type ChanMan = ChannelManager<EnforcingChannelKeys, Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
+type ChanMan = ChannelManager<EnforcingSigner, Arc<TestChainMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
#[inline]
fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8) -> bool {
let mut monitors = HashMap::new();
let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
- monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&monitor_ser), &OnlyReadsKeysInterface {}).expect("Failed to read monitor").1);
+ monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&monitor_ser), &OnlyReadsKeysInterface {}).expect("Failed to read monitor").1);
chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
}
let mut monitor_refs = HashMap::new();
use bitcoin::hash_types::BlockHash;
use lightning::chain::channelmonitor;
-use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
+use lightning::util::enforcing_trait_impls::EnforcingSigner;
use lightning::util::ser::{ReadableArgs, Writer, Writeable};
use lightning::util::test_utils::OnlyReadsKeysInterface;
#[inline]
pub fn do_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
- if let Ok((latest_block_hash, monitor)) = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(data), &OnlyReadsKeysInterface {}) {
+ if let Ok((latest_block_hash, monitor)) = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(data), &OnlyReadsKeysInterface {}) {
let mut w = VecWriter(Vec::new());
monitor.write(&mut w).unwrap();
- let deserialized_copy = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&w.0), &OnlyReadsKeysInterface {}).unwrap();
+ let deserialized_copy = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&w.0), &OnlyReadsKeysInterface {}).unwrap();
assert!(latest_block_hash == deserialized_copy.0);
assert!(monitor == deserialized_copy.1);
}
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
use lightning::chain::chainmonitor;
use lightning::chain::transaction::OutPoint;
-use lightning::chain::keysinterface::{InMemoryChannelKeys, KeysInterface};
+use lightning::chain::keysinterface::{InMemorySigner, KeysInterface};
use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret};
use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor};
use lightning::ln::msgs::DecodeError;
use lightning::routing::network_graph::NetGraphMsgHandler;
use lightning::util::config::UserConfig;
use lightning::util::events::{EventsProvider,Event};
-use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
+use lightning::util::enforcing_trait_impls::EnforcingSigner;
use lightning::util::logger::Logger;
use lightning::util::ser::Readable;
}
type ChannelMan = ChannelManager<
- EnforcingChannelKeys,
- Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
+ EnforcingSigner,
+ Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan>, Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<dyn Logger>>>, Arc<dyn Logger>>;
struct MoneyLossDetector<'a> {
manager: Arc<ChannelMan>,
- monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
+ monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
handler: PeerMan<'a>,
peers: &'a RefCell<[bool; 256]>,
impl<'a> MoneyLossDetector<'a> {
pub fn new(peers: &'a RefCell<[bool; 256]>,
manager: Arc<ChannelMan>,
- monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
+ monitor: Arc<chainmonitor::ChainMonitor<EnforcingSigner, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<TestPersister>>>,
handler: PeerMan<'a>) -> Self {
MoneyLossDetector {
manager,
counter: AtomicU64,
}
impl KeysInterface for KeyProvider {
- type ChanKeySigner = EnforcingChannelKeys;
+ type Signer = EnforcingSigner;
fn get_node_secret(&self) -> SecretKey {
self.node_secret.clone()
PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap())
}
- fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
+ fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8;
let secp_ctx = Secp256k1::signing_only();
- EnforcingChannelKeys::new(if inbound {
- InMemoryChannelKeys::new(
+ EnforcingSigner::new(if inbound {
+ InMemorySigner::new(
&secp_ctx,
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ctr]).unwrap(),
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, ctr]).unwrap(),
[0; 32]
)
} else {
- InMemoryChannelKeys::new(
+ InMemorySigner::new(
&secp_ctx,
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, ctr]).unwrap(),
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, ctr]).unwrap(),
(ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8, (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8]
}
- fn read_chan_signer(&self, data: &[u8]) -> Result<EnforcingChannelKeys, DecodeError> {
- EnforcingChannelKeys::read(&mut std::io::Cursor::new(data))
+ fn read_chan_signer(&self, data: &[u8]) -> Result<EnforcingSigner, DecodeError> {
+ EnforcingSigner::read(&mut std::io::Cursor::new(data))
}
}
use lightning::chain::channelmonitor;
use lightning::chain::transaction::OutPoint;
-use lightning::util::enforcing_trait_impls::EnforcingChannelKeys;
+use lightning::util::enforcing_trait_impls::EnforcingSigner;
pub struct TestPersister {}
-impl channelmonitor::Persist<EnforcingChannelKeys> for TestPersister {
- fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+impl channelmonitor::Persist<EnforcingSigner> for TestPersister {
+ fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
Ok(())
}
- fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+ fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
Ok(())
}
}
LDK::PeerManager net1 = PeerManager_new(std::move(msg_handler1), node_secret1, &random_bytes.data, logger1);
// Demo getting a channel key and check that its returning real pubkeys:
- LDK::ChannelKeys chan_keys1 = keys_source1->get_channel_keys(keys_source1->this_arg, false, 42);
- chan_keys1->set_pubkeys(&chan_keys1); // Make sure pubkeys is defined
- LDKPublicKey payment_point = ChannelPublicKeys_get_payment_point(&chan_keys1->pubkeys);
+ LDK::Sign chan_signer1 = keys_source1->get_channel_signer(keys_source1->this_arg, false, 42);
+ chan_signer1->set_pubkeys(&chan_signer1); // Make sure pubkeys is defined
+ LDKPublicKey payment_point = ChannelPublicKeys_get_payment_point(&chan_signer1->pubkeys);
assert(memcmp(&payment_point, &null_pk, sizeof(null_pk)));
// Instantiate classes for node 2:
memset(&sk, 42, 32);
LDKThirtyTwoBytes kdiv_params;
memset(&kdiv_params, 43, 32);
- LDK::InMemoryChannelKeys keys = InMemoryChannelKeys_new(sk, sk, sk, sk, sk, random_bytes, 42, kdiv_params);
+ LDK::InMemorySigner signer = InMemorySigner_new(sk, sk, sk, sk, sk, random_bytes, 42, kdiv_params);
}
*
* To derive the delayed_payment key which is used to sign for this input, you must pass the
* holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
- * ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
+ * Sign::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
* chan_utils::derive_private_key. The public key can be generated without the secret key
* using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
- * ChannelKeys::pubkeys().
+ * Sign::pubkeys().
*
* To derive the revocation_pubkey provided here (which is used in the witness
* script generation), you must pass the counterparty revocation_basepoint (which appears in the
- * call to ChannelKeys::ready_channel) and the provided per_commitment point
+ * call to Sign::ready_channel) and the provided per_commitment point
* to chan_utils::derive_public_revocation_key.
*
* The witness script which is hashed and included in the output script_pubkey may be
LDKSpendableOutputDescriptor_DelayedPaymentOutput,
/**
* An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
- * corresponds to the public key in ChannelKeys::pubkeys().payment_point).
+ * corresponds to the public key in Sign::pubkeys().payment_point).
* The witness in the spending input, is, thus, simply:
* <BIP 143 signature> <payment key>
*
} LDKUnsignedChannelAnnouncement;
/**
- * Set of lightning keys needed to operate a channel as described in BOLT 3.
+ * A trait to sign lightning channel transactions as described in BOLT 3.
*
* Signing services could be implemented on a hardware wallet. In this case,
- * the current ChannelKeys would be a front-end on top of a communication
+ * the current Sign would be a front-end on top of a communication
* channel connected to your secure device and lightning key material wouldn't
* reside on a hot server. Nevertheless, a this deployment would still need
* to trust the ChannelManager to avoid loss of funds as this latest component
* to act, as liveness and breach reply correctness are always going to be hard requirements
* of LN security model, orthogonal of key management issues.
*/
-typedef struct LDKChannelKeys {
+typedef struct LDKSign {
void *this_arg;
/**
* Gets the per-commitment point for a specific commitment number
* Note that this takes a pointer to this object, not the this_ptr like other methods do
* This function pointer may be NULL if pubkeys is filled in when this object is created and never needs updating.
*/
- void (*set_pubkeys)(const struct LDKChannelKeys*NONNULL_PTR );
+ void (*set_pubkeys)(const struct LDKSign*NONNULL_PTR );
/**
* Gets an arbitrary identifier describing the set of keys which are provided back to you in
* some SpendableOutputDescriptor types. This should be sufficient to identify this
- * ChannelKeys object uniquely and lookup or re-derive its keys.
+ * Sign object uniquely and lookup or re-derive its keys.
*/
struct LDKThirtyTwoBytes (*channel_keys_id)(const void *this_arg);
/**
void *(*clone)(const void *this_arg);
struct LDKCVec_u8Z (*write)(const void *this_arg);
void (*free)(void *this_arg);
-} LDKChannelKeys;
+} LDKSign;
void (*free)(void *this_arg);
} LDKBroadcasterInterface;
-typedef union LDKCResult_ChannelKeysDecodeErrorZPtr {
- struct LDKChannelKeys *result;
+typedef union LDKCResult_SignDecodeErrorZPtr {
+ struct LDKSign *result;
struct LDKDecodeError *err;
-} LDKCResult_ChannelKeysDecodeErrorZPtr;
+} LDKCResult_SignDecodeErrorZPtr;
-typedef struct LDKCResult_ChannelKeysDecodeErrorZ {
- union LDKCResult_ChannelKeysDecodeErrorZPtr contents;
+typedef struct LDKCResult_SignDecodeErrorZ {
+ union LDKCResult_SignDecodeErrorZPtr contents;
bool result_ok;
-} LDKCResult_ChannelKeysDecodeErrorZ;
+} LDKCResult_SignDecodeErrorZ;
typedef struct LDKu8slice {
const uint8_t *data;
*/
struct LDKPublicKey (*get_shutdown_pubkey)(const void *this_arg);
/**
- * Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
+ * Get a new set of Sign for per-channel secrets. These MUST be unique even if you
* restarted with some stale data!
*
* This method must return a different value each time it is called.
*/
- struct LDKChannelKeys (*get_channel_keys)(const void *this_arg, bool inbound, uint64_t channel_value_satoshis);
+ struct LDKSign (*get_channel_signer)(const void *this_arg, bool inbound, uint64_t channel_value_satoshis);
/**
* Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
* onion packets and for temporary channel IDs. There is no requirement that these be
*/
struct LDKThirtyTwoBytes (*get_secure_random_bytes)(const void *this_arg);
/**
- * Reads a `ChanKeySigner` for this `KeysInterface` from the given input stream.
+ * Reads a `Signer` for this `KeysInterface` from the given input stream.
* This is only called during deserialization of other objects which contain
- * `ChannelKeys`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
- * The bytes are exactly those which `<Self::ChanKeySigner as Writeable>::write()` writes, and
+ * `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
+ * The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
* contain no versioning scheme. You may wish to include your own version prefix and ensure
* you've read all of the provided bytes to ensure no corruption occurred.
*/
- struct LDKCResult_ChannelKeysDecodeErrorZ (*read_chan_signer)(const void *this_arg, struct LDKu8slice reader);
+ struct LDKCResult_SignDecodeErrorZ (*read_chan_signer)(const void *this_arg, struct LDKu8slice reader);
void (*free)(void *this_arg);
} LDKKeysInterface;
/**
- * A simple implementation of ChannelKeys that just keeps the private keys in memory.
+ * A simple implementation of Sign that just keeps the private keys in memory.
*
* This implementation performs no policy checks and is insufficient by itself as
* a secure external signer.
*/
-typedef struct MUST_USE_STRUCT LDKInMemoryChannelKeys {
+typedef struct MUST_USE_STRUCT LDKInMemorySigner {
/**
* Nearly everywhere, inner must be non-null, however in places where
* the Rust equivalent takes an Option, it may be set to null to indicate None.
*/
- LDKnativeInMemoryChannelKeys *inner;
+ LDKnativeInMemorySigner *inner;
bool is_owned;
-} LDKInMemoryChannelKeys;
+} LDKInMemorySigner;
-typedef union LDKCResult_InMemoryChannelKeysDecodeErrorZPtr {
- struct LDKInMemoryChannelKeys *result;
+typedef union LDKCResult_InMemorySignerDecodeErrorZPtr {
+ struct LDKInMemorySigner *result;
struct LDKDecodeError *err;
-} LDKCResult_InMemoryChannelKeysDecodeErrorZPtr;
+} LDKCResult_InMemorySignerDecodeErrorZPtr;
-typedef struct LDKCResult_InMemoryChannelKeysDecodeErrorZ {
- union LDKCResult_InMemoryChannelKeysDecodeErrorZPtr contents;
+typedef struct LDKCResult_InMemorySignerDecodeErrorZ {
+ union LDKCResult_InMemorySignerDecodeErrorZPtr contents;
bool result_ok;
-} LDKCResult_InMemoryChannelKeysDecodeErrorZ;
+} LDKCResult_InMemorySignerDecodeErrorZ;
typedef struct LDKCVec_TxOutZ {
struct LDKTxOut *data;
struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_clone(const struct LDKCResult_SignatureNoneZ *NONNULL_PTR orig);
-struct LDKCResult_ChannelKeysDecodeErrorZ CResult_ChannelKeysDecodeErrorZ_ok(struct LDKChannelKeys o);
+struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_ok(struct LDKSign o);
-struct LDKCResult_ChannelKeysDecodeErrorZ CResult_ChannelKeysDecodeErrorZ_err(struct LDKDecodeError e);
+struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_err(struct LDKDecodeError e);
-void CResult_ChannelKeysDecodeErrorZ_free(struct LDKCResult_ChannelKeysDecodeErrorZ _res);
+void CResult_SignDecodeErrorZ_free(struct LDKCResult_SignDecodeErrorZ _res);
-struct LDKCResult_ChannelKeysDecodeErrorZ CResult_ChannelKeysDecodeErrorZ_clone(const struct LDKCResult_ChannelKeysDecodeErrorZ *NONNULL_PTR orig);
+struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_clone(const struct LDKCResult_SignDecodeErrorZ *NONNULL_PTR orig);
void CVec_CVec_u8ZZ_free(struct LDKCVec_CVec_u8ZZ _res);
struct LDKCResult_CVec_CVec_u8ZZNoneZ CResult_CVec_CVec_u8ZZNoneZ_clone(const struct LDKCResult_CVec_CVec_u8ZZNoneZ *NONNULL_PTR orig);
-struct LDKCResult_InMemoryChannelKeysDecodeErrorZ CResult_InMemoryChannelKeysDecodeErrorZ_ok(struct LDKInMemoryChannelKeys o);
+struct LDKCResult_InMemorySignerDecodeErrorZ CResult_InMemorySignerDecodeErrorZ_ok(struct LDKInMemorySigner o);
-struct LDKCResult_InMemoryChannelKeysDecodeErrorZ CResult_InMemoryChannelKeysDecodeErrorZ_err(struct LDKDecodeError e);
+struct LDKCResult_InMemorySignerDecodeErrorZ CResult_InMemorySignerDecodeErrorZ_err(struct LDKDecodeError e);
-void CResult_InMemoryChannelKeysDecodeErrorZ_free(struct LDKCResult_InMemoryChannelKeysDecodeErrorZ _res);
+void CResult_InMemorySignerDecodeErrorZ_free(struct LDKCResult_InMemorySignerDecodeErrorZ _res);
-struct LDKCResult_InMemoryChannelKeysDecodeErrorZ CResult_InMemoryChannelKeysDecodeErrorZ_clone(const struct LDKCResult_InMemoryChannelKeysDecodeErrorZ *NONNULL_PTR orig);
+struct LDKCResult_InMemorySignerDecodeErrorZ CResult_InMemorySignerDecodeErrorZ_clone(const struct LDKCResult_InMemorySignerDecodeErrorZ *NONNULL_PTR orig);
void CVec_TxOutZ_free(struct LDKCVec_TxOutZ _res);
/**
* Arbitrary identification information returned by a call to
- * `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+ * `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
* the channel to spend the output.
*/
const uint8_t (*DelayedPaymentOutputDescriptor_get_channel_keys_id(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr))[32];
/**
* Arbitrary identification information returned by a call to
- * `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+ * `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
* the channel to spend the output.
*/
void DelayedPaymentOutputDescriptor_set_channel_keys_id(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
/**
* Arbitrary identification information returned by a call to
- * `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+ * `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
* the channel to spend the output.
*/
const uint8_t (*StaticPaymentOutputDescriptor_get_channel_keys_id(const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr))[32];
/**
* Arbitrary identification information returned by a call to
- * `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+ * `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
* the channel to spend the output.
*/
void StaticPaymentOutputDescriptor_set_channel_keys_id(struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ SpendableOutputDescriptor_read(struct LDKu8slice ser);
-struct LDKChannelKeys ChannelKeys_clone(const struct LDKChannelKeys *NONNULL_PTR orig);
+struct LDKSign Sign_clone(const struct LDKSign *NONNULL_PTR orig);
/**
* Calls the free function if one is set
*/
-void ChannelKeys_free(struct LDKChannelKeys this_ptr);
+void Sign_free(struct LDKSign this_ptr);
/**
* Calls the free function if one is set
*/
void KeysInterface_free(struct LDKKeysInterface this_ptr);
-void InMemoryChannelKeys_free(struct LDKInMemoryChannelKeys this_ptr);
+void InMemorySigner_free(struct LDKInMemorySigner this_ptr);
/**
* Private key of anchor tx
*/
-const uint8_t (*InMemoryChannelKeys_get_funding_key(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr))[32];
+const uint8_t (*InMemorySigner_get_funding_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
/**
* Private key of anchor tx
*/
-void InMemoryChannelKeys_set_funding_key(struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr, struct LDKSecretKey val);
+void InMemorySigner_set_funding_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
/**
* Holder secret key for blinded revocation pubkey
*/
-const uint8_t (*InMemoryChannelKeys_get_revocation_base_key(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr))[32];
+const uint8_t (*InMemorySigner_get_revocation_base_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
/**
* Holder secret key for blinded revocation pubkey
*/
-void InMemoryChannelKeys_set_revocation_base_key(struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr, struct LDKSecretKey val);
+void InMemorySigner_set_revocation_base_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
/**
* Holder secret key used for our balance in counterparty-broadcasted commitment transactions
*/
-const uint8_t (*InMemoryChannelKeys_get_payment_key(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr))[32];
+const uint8_t (*InMemorySigner_get_payment_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
/**
* Holder secret key used for our balance in counterparty-broadcasted commitment transactions
*/
-void InMemoryChannelKeys_set_payment_key(struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr, struct LDKSecretKey val);
+void InMemorySigner_set_payment_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
/**
* Holder secret key used in HTLC tx
*/
-const uint8_t (*InMemoryChannelKeys_get_delayed_payment_base_key(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr))[32];
+const uint8_t (*InMemorySigner_get_delayed_payment_base_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
/**
* Holder secret key used in HTLC tx
*/
-void InMemoryChannelKeys_set_delayed_payment_base_key(struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr, struct LDKSecretKey val);
+void InMemorySigner_set_delayed_payment_base_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
/**
* Holder htlc secret key used in commitment tx htlc outputs
*/
-const uint8_t (*InMemoryChannelKeys_get_htlc_base_key(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr))[32];
+const uint8_t (*InMemorySigner_get_htlc_base_key(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
/**
* Holder htlc secret key used in commitment tx htlc outputs
*/
-void InMemoryChannelKeys_set_htlc_base_key(struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr, struct LDKSecretKey val);
+void InMemorySigner_set_htlc_base_key(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKSecretKey val);
/**
* Commitment seed
*/
-const uint8_t (*InMemoryChannelKeys_get_commitment_seed(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr))[32];
+const uint8_t (*InMemorySigner_get_commitment_seed(const struct LDKInMemorySigner *NONNULL_PTR this_ptr))[32];
/**
* Commitment seed
*/
-void InMemoryChannelKeys_set_commitment_seed(struct LDKInMemoryChannelKeys *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
+void InMemorySigner_set_commitment_seed(struct LDKInMemorySigner *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val);
-struct LDKInMemoryChannelKeys InMemoryChannelKeys_clone(const struct LDKInMemoryChannelKeys *NONNULL_PTR orig);
+struct LDKInMemorySigner InMemorySigner_clone(const struct LDKInMemorySigner *NONNULL_PTR orig);
/**
- * Create a new InMemoryChannelKeys
+ * Create a new InMemorySigner
*/
-MUST_USE_RES struct LDKInMemoryChannelKeys InMemoryChannelKeys_new(struct LDKSecretKey funding_key, struct LDKSecretKey revocation_base_key, struct LDKSecretKey payment_key, struct LDKSecretKey delayed_payment_base_key, struct LDKSecretKey htlc_base_key, struct LDKThirtyTwoBytes commitment_seed, uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id);
+MUST_USE_RES struct LDKInMemorySigner InMemorySigner_new(struct LDKSecretKey funding_key, struct LDKSecretKey revocation_base_key, struct LDKSecretKey payment_key, struct LDKSecretKey delayed_payment_base_key, struct LDKSecretKey htlc_base_key, struct LDKThirtyTwoBytes commitment_seed, uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id);
/**
* Counterparty pubkeys.
* Will panic if ready_channel wasn't called.
*/
-MUST_USE_RES struct LDKChannelPublicKeys InMemoryChannelKeys_counterparty_pubkeys(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg);
+MUST_USE_RES struct LDKChannelPublicKeys InMemorySigner_counterparty_pubkeys(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
/**
* The contest_delay value specified by our counterparty and applied on holder-broadcastable
* broadcast a transaction.
* Will panic if ready_channel wasn't called.
*/
-MUST_USE_RES uint16_t InMemoryChannelKeys_counterparty_selected_contest_delay(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg);
+MUST_USE_RES uint16_t InMemorySigner_counterparty_selected_contest_delay(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
/**
* The contest_delay value specified by us and applied on transactions broadcastable
* if they broadcast a transaction.
* Will panic if ready_channel wasn't called.
*/
-MUST_USE_RES uint16_t InMemoryChannelKeys_holder_selected_contest_delay(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg);
+MUST_USE_RES uint16_t InMemorySigner_holder_selected_contest_delay(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
/**
* Whether the holder is the initiator
* Will panic if ready_channel wasn't called.
*/
-MUST_USE_RES bool InMemoryChannelKeys_is_outbound(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg);
+MUST_USE_RES bool InMemorySigner_is_outbound(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
/**
* Funding outpoint
* Will panic if ready_channel wasn't called.
*/
-MUST_USE_RES struct LDKOutPoint InMemoryChannelKeys_funding_outpoint(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg);
+MUST_USE_RES struct LDKOutPoint InMemorySigner_funding_outpoint(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
/**
* Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
*
* Will panic if ready_channel wasn't called.
*/
-MUST_USE_RES struct LDKChannelTransactionParameters InMemoryChannelKeys_get_channel_parameters(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg);
+MUST_USE_RES struct LDKChannelTransactionParameters InMemorySigner_get_channel_parameters(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
/**
* Sign the single input of spend_tx at index `input_idx` which spends the output
* Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
* or is not spending the outpoint described by `descriptor.outpoint`.
*/
-MUST_USE_RES struct LDKCResult_CVec_CVec_u8ZZNoneZ InMemoryChannelKeys_sign_counterparty_payment_input(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg, struct LDKTransaction spend_tx, uintptr_t input_idx, const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR descriptor);
+MUST_USE_RES struct LDKCResult_CVec_CVec_u8ZZNoneZ InMemorySigner_sign_counterparty_payment_input(const struct LDKInMemorySigner *NONNULL_PTR this_arg, struct LDKTransaction spend_tx, uintptr_t input_idx, const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR descriptor);
/**
* Sign the single input of spend_tx at index `input_idx` which spends the output
* is not spending the outpoint described by `descriptor.outpoint`, or does not have a
* sequence set to `descriptor.to_self_delay`.
*/
-MUST_USE_RES struct LDKCResult_CVec_CVec_u8ZZNoneZ InMemoryChannelKeys_sign_dynamic_p2wsh_input(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg, struct LDKTransaction spend_tx, uintptr_t input_idx, const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR descriptor);
+MUST_USE_RES struct LDKCResult_CVec_CVec_u8ZZNoneZ InMemorySigner_sign_dynamic_p2wsh_input(const struct LDKInMemorySigner *NONNULL_PTR this_arg, struct LDKTransaction spend_tx, uintptr_t input_idx, const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR descriptor);
-struct LDKChannelKeys InMemoryChannelKeys_as_ChannelKeys(const struct LDKInMemoryChannelKeys *NONNULL_PTR this_arg);
+struct LDKSign InMemorySigner_as_Sign(const struct LDKInMemorySigner *NONNULL_PTR this_arg);
-struct LDKCVec_u8Z InMemoryChannelKeys_write(const struct LDKInMemoryChannelKeys *NONNULL_PTR obj);
+struct LDKCVec_u8Z InMemorySigner_write(const struct LDKInMemorySigner *NONNULL_PTR obj);
-struct LDKCResult_InMemoryChannelKeysDecodeErrorZ InMemoryChannelKeys_read(struct LDKu8slice ser);
+struct LDKCResult_InMemorySignerDecodeErrorZ InMemorySigner_read(struct LDKu8slice ser);
void KeysManager_free(struct LDKKeysManager this_ptr);
MUST_USE_RES struct LDKKeysManager KeysManager_new(const uint8_t (*seed)[32], uint64_t starting_time_secs, uint32_t starting_time_nanos);
/**
- * Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
+ * Derive an old set of Sign for per-channel secrets based on a key derivation
* parameters.
* Key derivation parameters are accessible through a per-channel secrets
- * ChannelKeys::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
+ * Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
* onchain output detection for which a corresponding delayed_payment_key must be derived.
*/
-MUST_USE_RES struct LDKInMemoryChannelKeys KeysManager_derive_channel_keys(const struct LDKKeysManager *NONNULL_PTR this_arg, uint64_t channel_value_satoshis, const uint8_t (*params)[32]);
+MUST_USE_RES struct LDKInMemorySigner KeysManager_derive_channel_keys(const struct LDKKeysManager *NONNULL_PTR this_arg, uint64_t channel_value_satoshis, const uint8_t (*params)[32]);
/**
* Creates a Transaction which spends the given descriptors to the given outputs, plus an
* We do not enforce that outputs meet the dust limit or that any output scripts are standard.
*
* May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used
- * this KeysManager or one of the `InMemoryChannelKeys` created by this KeysManager.
+ * this KeysManager or one of the `InMemorySigner` created by this KeysManager.
*/
MUST_USE_RES struct LDKCResult_TransactionNoneZ KeysManager_spend_spendable_outputs(const struct LDKKeysManager *NONNULL_PTR this_arg, struct LDKCVec_SpendableOutputDescriptorZ descriptors, struct LDKCVec_TxOutZ outputs, struct LDKCVec_u8Z change_destination_script, uint32_t feerate_sat_per_1000_weight);
*/
void ChannelManager_block_disconnected(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*header)[80]);
+/**
+ * Blocks until ChannelManager needs to be persisted. Only one listener on `wait` is
+ * guaranteed to be woken up.
+ */
+void ChannelManager_wait(const struct LDKChannelManager *NONNULL_PTR this_arg);
+
struct LDKChannelMessageHandler ChannelManager_as_ChannelMessageHandler(const struct LDKChannelManager *NONNULL_PTR this_arg);
struct LDKCVec_u8Z ChannelManager_write(const struct LDKChannelManager *NONNULL_PTR obj);
const LDKSpendableOutputDescriptor* operator &() const { return &self; }
const LDKSpendableOutputDescriptor* operator ->() const { return &self; }
};
-class ChannelKeys {
+class Sign {
private:
- LDKChannelKeys self;
+ LDKSign self;
public:
- ChannelKeys(const ChannelKeys&) = delete;
- ChannelKeys(ChannelKeys&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelKeys)); }
- ChannelKeys(LDKChannelKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelKeys)); }
- operator LDKChannelKeys() && { LDKChannelKeys res = self; memset(&self, 0, sizeof(LDKChannelKeys)); return res; }
- ~ChannelKeys() { ChannelKeys_free(self); }
- ChannelKeys& operator=(ChannelKeys&& o) { ChannelKeys_free(self); self = o.self; memset(&o, 0, sizeof(ChannelKeys)); return *this; }
- LDKChannelKeys* operator &() { return &self; }
- LDKChannelKeys* operator ->() { return &self; }
- const LDKChannelKeys* operator &() const { return &self; }
- const LDKChannelKeys* operator ->() const { return &self; }
+ Sign(const Sign&) = delete;
+ Sign(Sign&& o) : self(o.self) { memset(&o, 0, sizeof(Sign)); }
+ Sign(LDKSign&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSign)); }
+ operator LDKSign() && { LDKSign res = self; memset(&self, 0, sizeof(LDKSign)); return res; }
+ ~Sign() { Sign_free(self); }
+ Sign& operator=(Sign&& o) { Sign_free(self); self = o.self; memset(&o, 0, sizeof(Sign)); return *this; }
+ LDKSign* operator &() { return &self; }
+ LDKSign* operator ->() { return &self; }
+ const LDKSign* operator &() const { return &self; }
+ const LDKSign* operator ->() const { return &self; }
};
class KeysInterface {
private:
const LDKKeysInterface* operator &() const { return &self; }
const LDKKeysInterface* operator ->() const { return &self; }
};
-class InMemoryChannelKeys {
+class InMemorySigner {
private:
- LDKInMemoryChannelKeys self;
+ LDKInMemorySigner self;
public:
- InMemoryChannelKeys(const InMemoryChannelKeys&) = delete;
- InMemoryChannelKeys(InMemoryChannelKeys&& o) : self(o.self) { memset(&o, 0, sizeof(InMemoryChannelKeys)); }
- InMemoryChannelKeys(LDKInMemoryChannelKeys&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKInMemoryChannelKeys)); }
- operator LDKInMemoryChannelKeys() && { LDKInMemoryChannelKeys res = self; memset(&self, 0, sizeof(LDKInMemoryChannelKeys)); return res; }
- ~InMemoryChannelKeys() { InMemoryChannelKeys_free(self); }
- InMemoryChannelKeys& operator=(InMemoryChannelKeys&& o) { InMemoryChannelKeys_free(self); self = o.self; memset(&o, 0, sizeof(InMemoryChannelKeys)); return *this; }
- LDKInMemoryChannelKeys* operator &() { return &self; }
- LDKInMemoryChannelKeys* operator ->() { return &self; }
- const LDKInMemoryChannelKeys* operator &() const { return &self; }
- const LDKInMemoryChannelKeys* operator ->() const { return &self; }
+ InMemorySigner(const InMemorySigner&) = delete;
+ InMemorySigner(InMemorySigner&& o) : self(o.self) { memset(&o, 0, sizeof(InMemorySigner)); }
+ InMemorySigner(LDKInMemorySigner&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKInMemorySigner)); }
+ operator LDKInMemorySigner() && { LDKInMemorySigner res = self; memset(&self, 0, sizeof(LDKInMemorySigner)); return res; }
+ ~InMemorySigner() { InMemorySigner_free(self); }
+ InMemorySigner& operator=(InMemorySigner&& o) { InMemorySigner_free(self); self = o.self; memset(&o, 0, sizeof(InMemorySigner)); return *this; }
+ LDKInMemorySigner* operator &() { return &self; }
+ LDKInMemorySigner* operator ->() { return &self; }
+ const LDKInMemorySigner* operator &() const { return &self; }
+ const LDKInMemorySigner* operator ->() const { return &self; }
};
class KeysManager {
private:
const LDKCVec_ChannelDetailsZ* operator &() const { return &self; }
const LDKCVec_ChannelDetailsZ* operator ->() const { return &self; }
};
+class CResult_SignDecodeErrorZ {
+private:
+ LDKCResult_SignDecodeErrorZ self;
+public:
+ CResult_SignDecodeErrorZ(const CResult_SignDecodeErrorZ&) = delete;
+ CResult_SignDecodeErrorZ(CResult_SignDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SignDecodeErrorZ)); }
+ CResult_SignDecodeErrorZ(LDKCResult_SignDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SignDecodeErrorZ)); }
+ operator LDKCResult_SignDecodeErrorZ() && { LDKCResult_SignDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_SignDecodeErrorZ)); return res; }
+ ~CResult_SignDecodeErrorZ() { CResult_SignDecodeErrorZ_free(self); }
+ CResult_SignDecodeErrorZ& operator=(CResult_SignDecodeErrorZ&& o) { CResult_SignDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SignDecodeErrorZ)); return *this; }
+ LDKCResult_SignDecodeErrorZ* operator &() { return &self; }
+ LDKCResult_SignDecodeErrorZ* operator ->() { return &self; }
+ const LDKCResult_SignDecodeErrorZ* operator &() const { return &self; }
+ const LDKCResult_SignDecodeErrorZ* operator ->() const { return &self; }
+};
class CVec_MessageSendEventZ {
private:
LDKCVec_MessageSendEventZ self;
const LDKC2Tuple_OutPointScriptZ* operator &() const { return &self; }
const LDKC2Tuple_OutPointScriptZ* operator ->() const { return &self; }
};
-class CResult_InMemoryChannelKeysDecodeErrorZ {
-private:
- LDKCResult_InMemoryChannelKeysDecodeErrorZ self;
-public:
- CResult_InMemoryChannelKeysDecodeErrorZ(const CResult_InMemoryChannelKeysDecodeErrorZ&) = delete;
- CResult_InMemoryChannelKeysDecodeErrorZ(CResult_InMemoryChannelKeysDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InMemoryChannelKeysDecodeErrorZ)); }
- CResult_InMemoryChannelKeysDecodeErrorZ(LDKCResult_InMemoryChannelKeysDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InMemoryChannelKeysDecodeErrorZ)); }
- operator LDKCResult_InMemoryChannelKeysDecodeErrorZ() && { LDKCResult_InMemoryChannelKeysDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InMemoryChannelKeysDecodeErrorZ)); return res; }
- ~CResult_InMemoryChannelKeysDecodeErrorZ() { CResult_InMemoryChannelKeysDecodeErrorZ_free(self); }
- CResult_InMemoryChannelKeysDecodeErrorZ& operator=(CResult_InMemoryChannelKeysDecodeErrorZ&& o) { CResult_InMemoryChannelKeysDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InMemoryChannelKeysDecodeErrorZ)); return *this; }
- LDKCResult_InMemoryChannelKeysDecodeErrorZ* operator &() { return &self; }
- LDKCResult_InMemoryChannelKeysDecodeErrorZ* operator ->() { return &self; }
- const LDKCResult_InMemoryChannelKeysDecodeErrorZ* operator &() const { return &self; }
- const LDKCResult_InMemoryChannelKeysDecodeErrorZ* operator ->() const { return &self; }
-};
class CResult_UpdateFailMalformedHTLCDecodeErrorZ {
private:
LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ self;
const LDKCResult_UpdateFulfillHTLCDecodeErrorZ* operator &() const { return &self; }
const LDKCResult_UpdateFulfillHTLCDecodeErrorZ* operator ->() const { return &self; }
};
-class CResult_ChannelKeysDecodeErrorZ {
-private:
- LDKCResult_ChannelKeysDecodeErrorZ self;
-public:
- CResult_ChannelKeysDecodeErrorZ(const CResult_ChannelKeysDecodeErrorZ&) = delete;
- CResult_ChannelKeysDecodeErrorZ(CResult_ChannelKeysDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_ChannelKeysDecodeErrorZ)); }
- CResult_ChannelKeysDecodeErrorZ(LDKCResult_ChannelKeysDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_ChannelKeysDecodeErrorZ)); }
- operator LDKCResult_ChannelKeysDecodeErrorZ() && { LDKCResult_ChannelKeysDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_ChannelKeysDecodeErrorZ)); return res; }
- ~CResult_ChannelKeysDecodeErrorZ() { CResult_ChannelKeysDecodeErrorZ_free(self); }
- CResult_ChannelKeysDecodeErrorZ& operator=(CResult_ChannelKeysDecodeErrorZ&& o) { CResult_ChannelKeysDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_ChannelKeysDecodeErrorZ)); return *this; }
- LDKCResult_ChannelKeysDecodeErrorZ* operator &() { return &self; }
- LDKCResult_ChannelKeysDecodeErrorZ* operator ->() { return &self; }
- const LDKCResult_ChannelKeysDecodeErrorZ* operator &() const { return &self; }
- const LDKCResult_ChannelKeysDecodeErrorZ* operator ->() const { return &self; }
-};
class CResult_NodeFeaturesDecodeErrorZ {
private:
LDKCResult_NodeFeaturesDecodeErrorZ self;
const LDKCResult_NodeFeaturesDecodeErrorZ* operator &() const { return &self; }
const LDKCResult_NodeFeaturesDecodeErrorZ* operator ->() const { return &self; }
};
+class CResult_InMemorySignerDecodeErrorZ {
+private:
+ LDKCResult_InMemorySignerDecodeErrorZ self;
+public:
+ CResult_InMemorySignerDecodeErrorZ(const CResult_InMemorySignerDecodeErrorZ&) = delete;
+ CResult_InMemorySignerDecodeErrorZ(CResult_InMemorySignerDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InMemorySignerDecodeErrorZ)); }
+ CResult_InMemorySignerDecodeErrorZ(LDKCResult_InMemorySignerDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InMemorySignerDecodeErrorZ)); }
+ operator LDKCResult_InMemorySignerDecodeErrorZ() && { LDKCResult_InMemorySignerDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InMemorySignerDecodeErrorZ)); return res; }
+ ~CResult_InMemorySignerDecodeErrorZ() { CResult_InMemorySignerDecodeErrorZ_free(self); }
+ CResult_InMemorySignerDecodeErrorZ& operator=(CResult_InMemorySignerDecodeErrorZ&& o) { CResult_InMemorySignerDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InMemorySignerDecodeErrorZ)); return *this; }
+ LDKCResult_InMemorySignerDecodeErrorZ* operator &() { return &self; }
+ LDKCResult_InMemorySignerDecodeErrorZ* operator ->() { return &self; }
+ const LDKCResult_InMemorySignerDecodeErrorZ* operator &() const { return &self; }
+ const LDKCResult_InMemorySignerDecodeErrorZ* operator ->() const { return &self; }
+};
class CResult_ReplyShortChannelIdsEndDecodeErrorZ {
private:
LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ self;
typedef struct nativeDelayedPaymentOutputDescriptorOpaque LDKnativeDelayedPaymentOutputDescriptor;
struct nativeStaticPaymentOutputDescriptorOpaque;
typedef struct nativeStaticPaymentOutputDescriptorOpaque LDKnativeStaticPaymentOutputDescriptor;
-struct LDKChannelKeys;
-typedef struct LDKChannelKeys LDKChannelKeys;
-struct nativeInMemoryChannelKeysOpaque;
-typedef struct nativeInMemoryChannelKeysOpaque LDKnativeInMemoryChannelKeys;
+struct LDKSign;
+typedef struct LDKSign LDKSign;
+struct nativeInMemorySignerOpaque;
+typedef struct nativeInMemorySignerOpaque LDKnativeInMemorySigner;
struct nativeKeysManagerOpaque;
typedef struct nativeKeysManagerOpaque LDKnativeKeysManager;
struct nativeRouteHopOpaque;
#[no_mangle]
pub extern "C" fn CResult_SignatureNoneZ_clone(orig: &CResult_SignatureNoneZ) -> CResult_SignatureNoneZ { orig.clone() }
#[repr(C)]
-pub union CResult_ChannelKeysDecodeErrorZPtr {
- pub result: *mut crate::chain::keysinterface::ChannelKeys,
+pub union CResult_SignDecodeErrorZPtr {
+ pub result: *mut crate::chain::keysinterface::Sign,
pub err: *mut crate::ln::msgs::DecodeError,
}
#[repr(C)]
-pub struct CResult_ChannelKeysDecodeErrorZ {
- pub contents: CResult_ChannelKeysDecodeErrorZPtr,
+pub struct CResult_SignDecodeErrorZ {
+ pub contents: CResult_SignDecodeErrorZPtr,
pub result_ok: bool,
}
#[no_mangle]
-pub extern "C" fn CResult_ChannelKeysDecodeErrorZ_ok(o: crate::chain::keysinterface::ChannelKeys) -> CResult_ChannelKeysDecodeErrorZ {
- CResult_ChannelKeysDecodeErrorZ {
- contents: CResult_ChannelKeysDecodeErrorZPtr {
+pub extern "C" fn CResult_SignDecodeErrorZ_ok(o: crate::chain::keysinterface::Sign) -> CResult_SignDecodeErrorZ {
+ CResult_SignDecodeErrorZ {
+ contents: CResult_SignDecodeErrorZPtr {
result: Box::into_raw(Box::new(o)),
},
result_ok: true,
}
}
#[no_mangle]
-pub extern "C" fn CResult_ChannelKeysDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_ChannelKeysDecodeErrorZ {
- CResult_ChannelKeysDecodeErrorZ {
- contents: CResult_ChannelKeysDecodeErrorZPtr {
+pub extern "C" fn CResult_SignDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_SignDecodeErrorZ {
+ CResult_SignDecodeErrorZ {
+ contents: CResult_SignDecodeErrorZPtr {
err: Box::into_raw(Box::new(e)),
},
result_ok: false,
}
}
#[no_mangle]
-pub extern "C" fn CResult_ChannelKeysDecodeErrorZ_free(_res: CResult_ChannelKeysDecodeErrorZ) { }
-impl Drop for CResult_ChannelKeysDecodeErrorZ {
+pub extern "C" fn CResult_SignDecodeErrorZ_free(_res: CResult_SignDecodeErrorZ) { }
+impl Drop for CResult_SignDecodeErrorZ {
fn drop(&mut self) {
if self.result_ok {
if unsafe { !(self.contents.result as *mut ()).is_null() } {
}
}
}
-impl From<crate::c_types::CResultTempl<crate::chain::keysinterface::ChannelKeys, crate::ln::msgs::DecodeError>> for CResult_ChannelKeysDecodeErrorZ {
- fn from(mut o: crate::c_types::CResultTempl<crate::chain::keysinterface::ChannelKeys, crate::ln::msgs::DecodeError>) -> Self {
+impl From<crate::c_types::CResultTempl<crate::chain::keysinterface::Sign, crate::ln::msgs::DecodeError>> for CResult_SignDecodeErrorZ {
+ fn from(mut o: crate::c_types::CResultTempl<crate::chain::keysinterface::Sign, crate::ln::msgs::DecodeError>) -> Self {
let contents = if o.result_ok {
let result = unsafe { o.contents.result };
unsafe { o.contents.result = std::ptr::null_mut() };
- CResult_ChannelKeysDecodeErrorZPtr { result }
+ CResult_SignDecodeErrorZPtr { result }
} else {
let err = unsafe { o.contents.err };
unsafe { o.contents.err = std::ptr::null_mut(); }
- CResult_ChannelKeysDecodeErrorZPtr { err }
+ CResult_SignDecodeErrorZPtr { err }
};
Self {
contents,
}
}
}
-impl Clone for CResult_ChannelKeysDecodeErrorZ {
+impl Clone for CResult_SignDecodeErrorZ {
fn clone(&self) -> Self {
if self.result_ok {
- Self { result_ok: true, contents: CResult_ChannelKeysDecodeErrorZPtr {
- result: Box::into_raw(Box::new(<crate::chain::keysinterface::ChannelKeys>::clone(unsafe { &*self.contents.result })))
+ Self { result_ok: true, contents: CResult_SignDecodeErrorZPtr {
+ result: Box::into_raw(Box::new(<crate::chain::keysinterface::Sign>::clone(unsafe { &*self.contents.result })))
} }
} else {
- Self { result_ok: false, contents: CResult_ChannelKeysDecodeErrorZPtr {
+ Self { result_ok: false, contents: CResult_SignDecodeErrorZPtr {
err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
} }
}
}
}
#[no_mangle]
-pub extern "C" fn CResult_ChannelKeysDecodeErrorZ_clone(orig: &CResult_ChannelKeysDecodeErrorZ) -> CResult_ChannelKeysDecodeErrorZ { orig.clone() }
+pub extern "C" fn CResult_SignDecodeErrorZ_clone(orig: &CResult_SignDecodeErrorZ) -> CResult_SignDecodeErrorZ { orig.clone() }
#[repr(C)]
pub struct CVec_CVec_u8ZZ {
pub data: *mut crate::c_types::derived::CVec_u8Z,
#[no_mangle]
pub extern "C" fn CResult_CVec_CVec_u8ZZNoneZ_clone(orig: &CResult_CVec_CVec_u8ZZNoneZ) -> CResult_CVec_CVec_u8ZZNoneZ { orig.clone() }
#[repr(C)]
-pub union CResult_InMemoryChannelKeysDecodeErrorZPtr {
- pub result: *mut crate::chain::keysinterface::InMemoryChannelKeys,
+pub union CResult_InMemorySignerDecodeErrorZPtr {
+ pub result: *mut crate::chain::keysinterface::InMemorySigner,
pub err: *mut crate::ln::msgs::DecodeError,
}
#[repr(C)]
-pub struct CResult_InMemoryChannelKeysDecodeErrorZ {
- pub contents: CResult_InMemoryChannelKeysDecodeErrorZPtr,
+pub struct CResult_InMemorySignerDecodeErrorZ {
+ pub contents: CResult_InMemorySignerDecodeErrorZPtr,
pub result_ok: bool,
}
#[no_mangle]
-pub extern "C" fn CResult_InMemoryChannelKeysDecodeErrorZ_ok(o: crate::chain::keysinterface::InMemoryChannelKeys) -> CResult_InMemoryChannelKeysDecodeErrorZ {
- CResult_InMemoryChannelKeysDecodeErrorZ {
- contents: CResult_InMemoryChannelKeysDecodeErrorZPtr {
+pub extern "C" fn CResult_InMemorySignerDecodeErrorZ_ok(o: crate::chain::keysinterface::InMemorySigner) -> CResult_InMemorySignerDecodeErrorZ {
+ CResult_InMemorySignerDecodeErrorZ {
+ contents: CResult_InMemorySignerDecodeErrorZPtr {
result: Box::into_raw(Box::new(o)),
},
result_ok: true,
}
}
#[no_mangle]
-pub extern "C" fn CResult_InMemoryChannelKeysDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_InMemoryChannelKeysDecodeErrorZ {
- CResult_InMemoryChannelKeysDecodeErrorZ {
- contents: CResult_InMemoryChannelKeysDecodeErrorZPtr {
+pub extern "C" fn CResult_InMemorySignerDecodeErrorZ_err(e: crate::ln::msgs::DecodeError) -> CResult_InMemorySignerDecodeErrorZ {
+ CResult_InMemorySignerDecodeErrorZ {
+ contents: CResult_InMemorySignerDecodeErrorZPtr {
err: Box::into_raw(Box::new(e)),
},
result_ok: false,
}
}
#[no_mangle]
-pub extern "C" fn CResult_InMemoryChannelKeysDecodeErrorZ_free(_res: CResult_InMemoryChannelKeysDecodeErrorZ) { }
-impl Drop for CResult_InMemoryChannelKeysDecodeErrorZ {
+pub extern "C" fn CResult_InMemorySignerDecodeErrorZ_free(_res: CResult_InMemorySignerDecodeErrorZ) { }
+impl Drop for CResult_InMemorySignerDecodeErrorZ {
fn drop(&mut self) {
if self.result_ok {
if unsafe { !(self.contents.result as *mut ()).is_null() } {
}
}
}
-impl From<crate::c_types::CResultTempl<crate::chain::keysinterface::InMemoryChannelKeys, crate::ln::msgs::DecodeError>> for CResult_InMemoryChannelKeysDecodeErrorZ {
- fn from(mut o: crate::c_types::CResultTempl<crate::chain::keysinterface::InMemoryChannelKeys, crate::ln::msgs::DecodeError>) -> Self {
+impl From<crate::c_types::CResultTempl<crate::chain::keysinterface::InMemorySigner, crate::ln::msgs::DecodeError>> for CResult_InMemorySignerDecodeErrorZ {
+ fn from(mut o: crate::c_types::CResultTempl<crate::chain::keysinterface::InMemorySigner, crate::ln::msgs::DecodeError>) -> Self {
let contents = if o.result_ok {
let result = unsafe { o.contents.result };
unsafe { o.contents.result = std::ptr::null_mut() };
- CResult_InMemoryChannelKeysDecodeErrorZPtr { result }
+ CResult_InMemorySignerDecodeErrorZPtr { result }
} else {
let err = unsafe { o.contents.err };
unsafe { o.contents.err = std::ptr::null_mut(); }
- CResult_InMemoryChannelKeysDecodeErrorZPtr { err }
+ CResult_InMemorySignerDecodeErrorZPtr { err }
};
Self {
contents,
}
}
}
-impl Clone for CResult_InMemoryChannelKeysDecodeErrorZ {
+impl Clone for CResult_InMemorySignerDecodeErrorZ {
fn clone(&self) -> Self {
if self.result_ok {
- Self { result_ok: true, contents: CResult_InMemoryChannelKeysDecodeErrorZPtr {
- result: Box::into_raw(Box::new(<crate::chain::keysinterface::InMemoryChannelKeys>::clone(unsafe { &*self.contents.result })))
+ Self { result_ok: true, contents: CResult_InMemorySignerDecodeErrorZPtr {
+ result: Box::into_raw(Box::new(<crate::chain::keysinterface::InMemorySigner>::clone(unsafe { &*self.contents.result })))
} }
} else {
- Self { result_ok: false, contents: CResult_InMemoryChannelKeysDecodeErrorZPtr {
+ Self { result_ok: false, contents: CResult_InMemorySignerDecodeErrorZPtr {
err: Box::into_raw(Box::new(<crate::ln::msgs::DecodeError>::clone(unsafe { &*self.contents.err })))
} }
}
}
}
#[no_mangle]
-pub extern "C" fn CResult_InMemoryChannelKeysDecodeErrorZ_clone(orig: &CResult_InMemoryChannelKeysDecodeErrorZ) -> CResult_InMemoryChannelKeysDecodeErrorZ { orig.clone() }
+pub extern "C" fn CResult_InMemorySignerDecodeErrorZ_clone(orig: &CResult_InMemorySignerDecodeErrorZ) -> CResult_InMemorySignerDecodeErrorZ { orig.clone() }
#[repr(C)]
pub struct CVec_TxOutZ {
pub data: *mut crate::c_types::TxOut,
use lightning::chain::chainmonitor::ChainMonitor as nativeChainMonitorImport;
-type nativeChainMonitor = nativeChainMonitorImport<crate::chain::keysinterface::ChannelKeys, crate::chain::Filter, crate::chain::chaininterface::BroadcasterInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger, crate::chain::channelmonitor::Persist>;
+type nativeChainMonitor = nativeChainMonitorImport<crate::chain::keysinterface::Sign, crate::chain::Filter, crate::chain::chaininterface::BroadcasterInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger, crate::chain::channelmonitor::Persist>;
/// An implementation of [`chain::Watch`] for monitoring channels.
///
}
use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport;
-type nativeChannelMonitor = nativeChannelMonitorImport<crate::chain::keysinterface::ChannelKeys>;
+type nativeChannelMonitor = nativeChannelMonitorImport<crate::chain::keysinterface::Sign>;
/// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
/// on-chain transactions to ensure no loss of funds occurs.
unsafe impl Sync for Persist {}
use lightning::chain::channelmonitor::Persist as rustPersist;
-impl rustPersist<crate::chain::keysinterface::ChannelKeys> for Persist {
- fn persist_new_channel(&self, id: lightning::chain::transaction::OutPoint, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::ChannelKeys>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
+impl rustPersist<crate::chain::keysinterface::Sign> for Persist {
+ fn persist_new_channel(&self, id: lightning::chain::transaction::OutPoint, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
let mut ret = (self.persist_new_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
local_ret
}
- fn update_persisted_channel(&self, id: lightning::chain::transaction::OutPoint, update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::ChannelKeys>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
+ fn update_persisted_channel(&self, id: lightning::chain::transaction::OutPoint, update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
let mut ret = (self.update_persisted_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (update as *const _) as *mut _ }, is_owned: false }, &crate::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
local_ret
#[no_mangle]
pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg: &crate::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
let arg_conv = arg;
- let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::ChannelKeys>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
+ let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
unsafe { &mut *this_ptr.inner }.revocation_pubkey = val.into_rust();
}
/// Arbitrary identification information returned by a call to
-/// `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+/// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
/// the channel to spend the output.
#[no_mangle]
pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &DelayedPaymentOutputDescriptor) -> *const [u8; 32] {
&(*inner_val)
}
/// Arbitrary identification information returned by a call to
-/// `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+/// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
/// the channel to spend the output.
#[no_mangle]
pub extern "C" fn DelayedPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) {
unsafe { &mut *this_ptr.inner }.output = val.into_rust();
}
/// Arbitrary identification information returned by a call to
-/// `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+/// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
/// the channel to spend the output.
#[no_mangle]
pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &StaticPaymentOutputDescriptor) -> *const [u8; 32] {
&(*inner_val)
}
/// Arbitrary identification information returned by a call to
-/// `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+/// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
/// the channel to spend the output.
#[no_mangle]
pub extern "C" fn StaticPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) {
///
/// To derive the delayed_payment key which is used to sign for this input, you must pass the
/// holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
- /// ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
+ /// Sign::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
/// chan_utils::derive_private_key. The public key can be generated without the secret key
/// using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
- /// ChannelKeys::pubkeys().
+ /// Sign::pubkeys().
///
/// To derive the revocation_pubkey provided here (which is used in the witness
/// script generation), you must pass the counterparty revocation_basepoint (which appears in the
- /// call to ChannelKeys::ready_channel) and the provided per_commitment point
+ /// call to Sign::ready_channel) and the provided per_commitment point
/// to chan_utils::derive_public_revocation_key.
///
/// The witness script which is hashed and included in the output script_pubkey may be
/// chan_utils::get_revokeable_redeemscript.
DelayedPaymentOutput(crate::chain::keysinterface::DelayedPaymentOutputDescriptor),
/// An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
- /// corresponds to the public key in ChannelKeys::pubkeys().payment_point).
+ /// corresponds to the public key in Sign::pubkeys().payment_point).
/// The witness in the spending input, is, thus, simply:
/// <BIP 143 signature> <payment key>
///
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::keysinterface::SpendableOutputDescriptor::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
-/// Set of lightning keys needed to operate a channel as described in BOLT 3.
+/// A trait to sign lightning channel transactions as described in BOLT 3.
///
/// Signing services could be implemented on a hardware wallet. In this case,
-/// the current ChannelKeys would be a front-end on top of a communication
+/// the current Sign would be a front-end on top of a communication
/// channel connected to your secure device and lightning key material wouldn't
/// reside on a hot server. Nevertheless, a this deployment would still need
/// to trust the ChannelManager to avoid loss of funds as this latest component
/// to act, as liveness and breach reply correctness are always going to be hard requirements
/// of LN security model, orthogonal of key management issues.
#[repr(C)]
-pub struct ChannelKeys {
+pub struct Sign {
pub this_arg: *mut c_void,
/// Gets the per-commitment point for a specific commitment number
///
/// Fill in the pubkeys field as a reference to it will be given to Rust after this returns
/// Note that this takes a pointer to this object, not the this_ptr like other methods do
/// This function pointer may be NULL if pubkeys is filled in when this object is created and never needs updating.
- pub set_pubkeys: Option<extern "C" fn(&ChannelKeys)>,
+ pub set_pubkeys: Option<extern "C" fn(&Sign)>,
/// Gets an arbitrary identifier describing the set of keys which are provided back to you in
/// some SpendableOutputDescriptor types. This should be sufficient to identify this
- /// ChannelKeys object uniquely and lookup or re-derive its keys.
+ /// Sign object uniquely and lookup or re-derive its keys.
#[must_use]
pub channel_keys_id: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes,
/// Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
}
-unsafe impl Send for ChannelKeys {}
+unsafe impl Send for Sign {}
#[no_mangle]
-pub extern "C" fn ChannelKeys_clone(orig: &ChannelKeys) -> ChannelKeys {
- ChannelKeys {
+pub extern "C" fn Sign_clone(orig: &Sign) -> Sign {
+ Sign {
this_arg: if let Some(f) = orig.clone { (f)(orig.this_arg) } else { orig.this_arg },
get_per_commitment_point: orig.get_per_commitment_point.clone(),
release_commitment_secret: orig.release_commitment_secret.clone(),
free: orig.free.clone(),
}
}
-impl Clone for ChannelKeys {
+impl Clone for Sign {
fn clone(&self) -> Self {
- ChannelKeys_clone(self)
+ Sign_clone(self)
}
}
-impl lightning::util::ser::Writeable for ChannelKeys {
+impl lightning::util::ser::Writeable for Sign {
fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
let vec = (self.write)(self.this_arg);
w.write_all(vec.as_slice())
}
}
-use lightning::chain::keysinterface::ChannelKeys as rustChannelKeys;
-impl rustChannelKeys for ChannelKeys {
+use lightning::chain::keysinterface::Sign as rustSign;
+impl rustSign for Sign {
fn get_per_commitment_point<T:bitcoin::secp256k1::Signing + bitcoin::secp256k1::Verification>(&self, idx: u64, _secp_ctx: &bitcoin::secp256k1::Secp256k1<T>) -> bitcoin::secp256k1::key::PublicKey {
let mut ret = (self.get_per_commitment_point)(self.this_arg, idx);
ret.into_rust()
// We're essentially a pointer already, or at least a set of pointers, so allow us to be used
// directly as a Deref trait in higher-level structs:
-impl std::ops::Deref for ChannelKeys {
+impl std::ops::Deref for Sign {
type Target = Self;
fn deref(&self) -> &Self {
self
}
/// Calls the free function if one is set
#[no_mangle]
-pub extern "C" fn ChannelKeys_free(this_ptr: ChannelKeys) { }
-impl Drop for ChannelKeys {
+pub extern "C" fn Sign_free(this_ptr: Sign) { }
+impl Drop for Sign {
fn drop(&mut self) {
if let Some(f) = self.free {
f(self.this_arg);
/// on-chain funds across channels as controlled to the same user.
#[must_use]
pub get_shutdown_pubkey: extern "C" fn (this_arg: *const c_void) -> crate::c_types::PublicKey,
- /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
+ /// Get a new set of Sign for per-channel secrets. These MUST be unique even if you
/// restarted with some stale data!
///
/// This method must return a different value each time it is called.
#[must_use]
- pub get_channel_keys: extern "C" fn (this_arg: *const c_void, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::ChannelKeys,
+ pub get_channel_signer: extern "C" fn (this_arg: *const c_void, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::Sign,
/// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
/// onion packets and for temporary channel IDs. There is no requirement that these be
/// persisted anywhere, though they must be unique across restarts.
/// This method must return a different value each time it is called.
#[must_use]
pub get_secure_random_bytes: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes,
- /// Reads a `ChanKeySigner` for this `KeysInterface` from the given input stream.
+ /// Reads a `Signer` for this `KeysInterface` from the given input stream.
/// This is only called during deserialization of other objects which contain
- /// `ChannelKeys`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
- /// The bytes are exactly those which `<Self::ChanKeySigner as Writeable>::write()` writes, and
+ /// `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
+ /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
/// contain no versioning scheme. You may wish to include your own version prefix and ensure
/// you've read all of the provided bytes to ensure no corruption occurred.
#[must_use]
- pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelKeysDecodeErrorZ,
+ pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ,
pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
}
unsafe impl Send for KeysInterface {}
use lightning::chain::keysinterface::KeysInterface as rustKeysInterface;
impl rustKeysInterface for KeysInterface {
- type ChanKeySigner = crate::chain::keysinterface::ChannelKeys;
+ type Signer = crate::chain::keysinterface::Sign;
fn get_node_secret(&self) -> bitcoin::secp256k1::key::SecretKey {
let mut ret = (self.get_node_secret)(self.this_arg);
ret.into_rust()
let mut ret = (self.get_shutdown_pubkey)(self.this_arg);
ret.into_rust()
}
- fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::ChannelKeys {
- let mut ret = (self.get_channel_keys)(self.this_arg, inbound, channel_value_satoshis);
+ fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> crate::chain::keysinterface::Sign {
+ let mut ret = (self.get_channel_signer)(self.this_arg, inbound, channel_value_satoshis);
ret
}
fn get_secure_random_bytes(&self) -> [u8; 32] {
let mut ret = (self.get_secure_random_bytes)(self.this_arg);
ret.data
}
- fn read_chan_signer(&self, reader: &[u8]) -> Result<crate::chain::keysinterface::ChannelKeys, lightning::ln::msgs::DecodeError> {
+ fn read_chan_signer(&self, reader: &[u8]) -> Result<crate::chain::keysinterface::Sign, lightning::ln::msgs::DecodeError> {
let mut local_reader = crate::c_types::u8slice::from_slice(reader);
let mut ret = (self.read_chan_signer)(self.this_arg, local_reader);
let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }) }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })};
}
}
-use lightning::chain::keysinterface::InMemoryChannelKeys as nativeInMemoryChannelKeysImport;
-type nativeInMemoryChannelKeys = nativeInMemoryChannelKeysImport;
+use lightning::chain::keysinterface::InMemorySigner as nativeInMemorySignerImport;
+type nativeInMemorySigner = nativeInMemorySignerImport;
-/// A simple implementation of ChannelKeys that just keeps the private keys in memory.
+/// A simple implementation of Sign that just keeps the private keys in memory.
///
/// This implementation performs no policy checks and is insufficient by itself as
/// a secure external signer.
#[must_use]
#[repr(C)]
-pub struct InMemoryChannelKeys {
+pub struct InMemorySigner {
/// Nearly everywhere, inner must be non-null, however in places where
/// the Rust equivalent takes an Option, it may be set to null to indicate None.
- pub inner: *mut nativeInMemoryChannelKeys,
+ pub inner: *mut nativeInMemorySigner,
pub is_owned: bool,
}
-impl Drop for InMemoryChannelKeys {
+impl Drop for InMemorySigner {
fn drop(&mut self) {
if self.is_owned && !self.inner.is_null() {
let _ = unsafe { Box::from_raw(self.inner) };
}
}
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_free(this_ptr: InMemoryChannelKeys) { }
+pub extern "C" fn InMemorySigner_free(this_ptr: InMemorySigner) { }
#[allow(unused)]
/// Used only if an object of this type is returned as a trait impl by a method
-extern "C" fn InMemoryChannelKeys_free_void(this_ptr: *mut c_void) {
- unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInMemoryChannelKeys); }
+extern "C" fn InMemorySigner_free_void(this_ptr: *mut c_void) {
+ unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInMemorySigner); }
}
#[allow(unused)]
/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
-impl InMemoryChannelKeys {
- pub(crate) fn take_inner(mut self) -> *mut nativeInMemoryChannelKeys {
+impl InMemorySigner {
+ pub(crate) fn take_inner(mut self) -> *mut nativeInMemorySigner {
assert!(self.is_owned);
let ret = self.inner;
self.inner = std::ptr::null_mut();
}
/// Private key of anchor tx
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_funding_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_funding_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_key;
(*inner_val).as_ref()
}
/// Private key of anchor tx
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_funding_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_funding_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
unsafe { &mut *this_ptr.inner }.funding_key = val.into_rust();
}
/// Holder secret key for blinded revocation pubkey
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_revocation_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_revocation_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_base_key;
(*inner_val).as_ref()
}
/// Holder secret key for blinded revocation pubkey
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_revocation_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_revocation_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
unsafe { &mut *this_ptr.inner }.revocation_base_key = val.into_rust();
}
/// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_payment_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_payment_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_key;
(*inner_val).as_ref()
}
/// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_payment_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_payment_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
unsafe { &mut *this_ptr.inner }.payment_key = val.into_rust();
}
/// Holder secret key used in HTLC tx
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_delayed_payment_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_delayed_payment_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_base_key;
(*inner_val).as_ref()
}
/// Holder secret key used in HTLC tx
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_delayed_payment_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_delayed_payment_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
unsafe { &mut *this_ptr.inner }.delayed_payment_base_key = val.into_rust();
}
/// Holder htlc secret key used in commitment tx htlc outputs
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_htlc_base_key(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_htlc_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_base_key;
(*inner_val).as_ref()
}
/// Holder htlc secret key used in commitment tx htlc outputs
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_htlc_base_key(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::SecretKey) {
+pub extern "C" fn InMemorySigner_set_htlc_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
unsafe { &mut *this_ptr.inner }.htlc_base_key = val.into_rust();
}
/// Commitment seed
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_commitment_seed(this_ptr: &InMemoryChannelKeys) -> *const [u8; 32] {
+pub extern "C" fn InMemorySigner_get_commitment_seed(this_ptr: &InMemorySigner) -> *const [u8; 32] {
let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.commitment_seed;
&(*inner_val)
}
/// Commitment seed
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_set_commitment_seed(this_ptr: &mut InMemoryChannelKeys, mut val: crate::c_types::ThirtyTwoBytes) {
+pub extern "C" fn InMemorySigner_set_commitment_seed(this_ptr: &mut InMemorySigner, mut val: crate::c_types::ThirtyTwoBytes) {
unsafe { &mut *this_ptr.inner }.commitment_seed = val.data;
}
-impl Clone for InMemoryChannelKeys {
+impl Clone for InMemorySigner {
fn clone(&self) -> Self {
Self {
inner: if self.inner.is_null() { std::ptr::null_mut() } else {
}
#[allow(unused)]
/// Used only if an object of this type is returned as a trait impl by a method
-pub(crate) extern "C" fn InMemoryChannelKeys_clone_void(this_ptr: *const c_void) -> *mut c_void {
- Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInMemoryChannelKeys)).clone() })) as *mut c_void
+pub(crate) extern "C" fn InMemorySigner_clone_void(this_ptr: *const c_void) -> *mut c_void {
+ Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeInMemorySigner)).clone() })) as *mut c_void
}
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_clone(orig: &InMemoryChannelKeys) -> InMemoryChannelKeys {
+pub extern "C" fn InMemorySigner_clone(orig: &InMemorySigner) -> InMemorySigner {
orig.clone()
}
-/// Create a new InMemoryChannelKeys
+/// Create a new InMemorySigner
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_new(mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::chain::keysinterface::InMemoryChannelKeys {
- let mut ret = lightning::chain::keysinterface::InMemoryChannelKeys::new(&bitcoin::secp256k1::Secp256k1::new(), funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, channel_keys_id.data);
- crate::chain::keysinterface::InMemoryChannelKeys { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+pub extern "C" fn InMemorySigner_new(mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::chain::keysinterface::InMemorySigner {
+ let mut ret = lightning::chain::keysinterface::InMemorySigner::new(&bitcoin::secp256k1::Secp256k1::new(), funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, channel_keys_id.data);
+ crate::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
/// Counterparty pubkeys.
/// Will panic if ready_channel wasn't called.
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_counterparty_pubkeys(this_arg: &InMemoryChannelKeys) -> crate::ln::chan_utils::ChannelPublicKeys {
+pub extern "C" fn InMemorySigner_counterparty_pubkeys(this_arg: &InMemorySigner) -> crate::ln::chan_utils::ChannelPublicKeys {
let mut ret = unsafe { &*this_arg.inner }.counterparty_pubkeys();
crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
}
/// Will panic if ready_channel wasn't called.
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_counterparty_selected_contest_delay(this_arg: &InMemoryChannelKeys) -> u16 {
+pub extern "C" fn InMemorySigner_counterparty_selected_contest_delay(this_arg: &InMemorySigner) -> u16 {
let mut ret = unsafe { &*this_arg.inner }.counterparty_selected_contest_delay();
ret
}
/// Will panic if ready_channel wasn't called.
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_holder_selected_contest_delay(this_arg: &InMemoryChannelKeys) -> u16 {
+pub extern "C" fn InMemorySigner_holder_selected_contest_delay(this_arg: &InMemorySigner) -> u16 {
let mut ret = unsafe { &*this_arg.inner }.holder_selected_contest_delay();
ret
}
/// Will panic if ready_channel wasn't called.
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_is_outbound(this_arg: &InMemoryChannelKeys) -> bool {
+pub extern "C" fn InMemorySigner_is_outbound(this_arg: &InMemorySigner) -> bool {
let mut ret = unsafe { &*this_arg.inner }.is_outbound();
ret
}
/// Will panic if ready_channel wasn't called.
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_funding_outpoint(this_arg: &InMemoryChannelKeys) -> crate::chain::transaction::OutPoint {
+pub extern "C" fn InMemorySigner_funding_outpoint(this_arg: &InMemorySigner) -> crate::chain::transaction::OutPoint {
let mut ret = unsafe { &*this_arg.inner }.funding_outpoint();
crate::chain::transaction::OutPoint { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
}
/// Will panic if ready_channel wasn't called.
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_get_channel_parameters(this_arg: &InMemoryChannelKeys) -> crate::ln::chan_utils::ChannelTransactionParameters {
+pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &InMemorySigner) -> crate::ln::chan_utils::ChannelTransactionParameters {
let mut ret = unsafe { &*this_arg.inner }.get_channel_parameters();
crate::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
}
/// or is not spending the outpoint described by `descriptor.outpoint`.
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_sign_counterparty_payment_input(this_arg: &InMemoryChannelKeys, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::chain::keysinterface::StaticPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ {
+pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::chain::keysinterface::StaticPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ {
let mut ret = unsafe { &*this_arg.inner }.sign_counterparty_payment_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
local_ret
/// sequence set to `descriptor.to_self_delay`.
#[must_use]
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_sign_dynamic_p2wsh_input(this_arg: &InMemoryChannelKeys, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::chain::keysinterface::DelayedPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ {
+pub extern "C" fn InMemorySigner_sign_dynamic_p2wsh_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::chain::keysinterface::DelayedPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ {
let mut ret = unsafe { &*this_arg.inner }.sign_dynamic_p2wsh_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
local_ret
}
-impl From<nativeInMemoryChannelKeys> for crate::chain::keysinterface::ChannelKeys {
- fn from(obj: nativeInMemoryChannelKeys) -> Self {
- let mut rust_obj = InMemoryChannelKeys { inner: Box::into_raw(Box::new(obj)), is_owned: true };
- let mut ret = InMemoryChannelKeys_as_ChannelKeys(&rust_obj);
+impl From<nativeInMemorySigner> for crate::chain::keysinterface::Sign {
+ fn from(obj: nativeInMemorySigner) -> Self {
+ let mut rust_obj = InMemorySigner { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+ let mut ret = InMemorySigner_as_Sign(&rust_obj);
// We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
rust_obj.inner = std::ptr::null_mut();
- ret.free = Some(InMemoryChannelKeys_free_void);
+ ret.free = Some(InMemorySigner_free_void);
ret
}
}
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_as_ChannelKeys(this_arg: &InMemoryChannelKeys) -> crate::chain::keysinterface::ChannelKeys {
- crate::chain::keysinterface::ChannelKeys {
+pub extern "C" fn InMemorySigner_as_Sign(this_arg: &InMemorySigner) -> crate::chain::keysinterface::Sign {
+ crate::chain::keysinterface::Sign {
this_arg: unsafe { (*this_arg).inner as *mut c_void },
free: None,
- get_per_commitment_point: InMemoryChannelKeys_ChannelKeys_get_per_commitment_point,
- release_commitment_secret: InMemoryChannelKeys_ChannelKeys_release_commitment_secret,
+ get_per_commitment_point: InMemorySigner_Sign_get_per_commitment_point,
+ release_commitment_secret: InMemorySigner_Sign_release_commitment_secret,
pubkeys: crate::ln::chan_utils::ChannelPublicKeys { inner: std::ptr::null_mut(), is_owned: true },
- set_pubkeys: Some(InMemoryChannelKeys_ChannelKeys_set_pubkeys),
- channel_keys_id: InMemoryChannelKeys_ChannelKeys_channel_keys_id,
- sign_counterparty_commitment: InMemoryChannelKeys_ChannelKeys_sign_counterparty_commitment,
- sign_holder_commitment_and_htlcs: InMemoryChannelKeys_ChannelKeys_sign_holder_commitment_and_htlcs,
- sign_justice_transaction: InMemoryChannelKeys_ChannelKeys_sign_justice_transaction,
- sign_counterparty_htlc_transaction: InMemoryChannelKeys_ChannelKeys_sign_counterparty_htlc_transaction,
- sign_closing_transaction: InMemoryChannelKeys_ChannelKeys_sign_closing_transaction,
- sign_channel_announcement: InMemoryChannelKeys_ChannelKeys_sign_channel_announcement,
- ready_channel: InMemoryChannelKeys_ChannelKeys_ready_channel,
- clone: Some(InMemoryChannelKeys_clone_void),
- write: InMemoryChannelKeys_write_void,
+ set_pubkeys: Some(InMemorySigner_Sign_set_pubkeys),
+ channel_keys_id: InMemorySigner_Sign_channel_keys_id,
+ sign_counterparty_commitment: InMemorySigner_Sign_sign_counterparty_commitment,
+ sign_holder_commitment_and_htlcs: InMemorySigner_Sign_sign_holder_commitment_and_htlcs,
+ sign_justice_transaction: InMemorySigner_Sign_sign_justice_transaction,
+ sign_counterparty_htlc_transaction: InMemorySigner_Sign_sign_counterparty_htlc_transaction,
+ sign_closing_transaction: InMemorySigner_Sign_sign_closing_transaction,
+ sign_channel_announcement: InMemorySigner_Sign_sign_channel_announcement,
+ ready_channel: InMemorySigner_Sign_ready_channel,
+ clone: Some(InMemorySigner_clone_void),
+ write: InMemorySigner_write_void,
}
}
-use lightning::chain::keysinterface::ChannelKeys as ChannelKeysTraitImport;
+use lightning::chain::keysinterface::Sign as SignTraitImport;
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_get_per_commitment_point(this_arg: *const c_void, mut idx: u64) -> crate::c_types::PublicKey {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.get_per_commitment_point(idx, &bitcoin::secp256k1::Secp256k1::new());
+extern "C" fn InMemorySigner_Sign_get_per_commitment_point(this_arg: *const c_void, mut idx: u64) -> crate::c_types::PublicKey {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.get_per_commitment_point(idx, &bitcoin::secp256k1::Secp256k1::new());
crate::c_types::PublicKey::from_rust(&ret)
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_release_commitment_secret(this_arg: *const c_void, mut idx: u64) -> crate::c_types::ThirtyTwoBytes {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.release_commitment_secret(idx);
+extern "C" fn InMemorySigner_Sign_release_commitment_secret(this_arg: *const c_void, mut idx: u64) -> crate::c_types::ThirtyTwoBytes {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.release_commitment_secret(idx);
crate::c_types::ThirtyTwoBytes { data: ret }
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_pubkeys(this_arg: *const c_void) -> crate::ln::chan_utils::ChannelPublicKeys {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.pubkeys();
+extern "C" fn InMemorySigner_Sign_pubkeys(this_arg: *const c_void) -> crate::ln::chan_utils::ChannelPublicKeys {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.pubkeys();
crate::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
}
-extern "C" fn InMemoryChannelKeys_ChannelKeys_set_pubkeys(trait_self_arg: &ChannelKeys) {
+extern "C" fn InMemorySigner_Sign_set_pubkeys(trait_self_arg: &Sign) {
// This is a bit race-y in the general case, but for our specific use-cases today, we're safe
// Specifically, we must ensure that the first time we're called it can never be in parallel
if trait_self_arg.pubkeys.inner.is_null() {
- unsafe { &mut *(trait_self_arg as *const ChannelKeys as *mut ChannelKeys) }.pubkeys = InMemoryChannelKeys_ChannelKeys_pubkeys(trait_self_arg.this_arg);
+ unsafe { &mut *(trait_self_arg as *const Sign as *mut Sign) }.pubkeys = InMemorySigner_Sign_pubkeys(trait_self_arg.this_arg);
}
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_channel_keys_id(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.channel_keys_id();
+extern "C" fn InMemorySigner_Sign_channel_keys_id(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.channel_keys_id();
crate::c_types::ThirtyTwoBytes { data: ret }
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_counterparty_commitment(unsafe { &*commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
+extern "C" fn InMemorySigner_Sign_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_counterparty_commitment(unsafe { &*commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
local_ret
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_holder_commitment_and_htlcs(unsafe { &*commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
+extern "C" fn InMemorySigner_Sign_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_holder_commitment_and_htlcs(unsafe { &*commitment_tx.inner }, &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
local_ret
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_justice_transaction(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
+extern "C" fn InMemorySigner_Sign_sign_justice_transaction(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
let mut local_htlc = if htlc.inner.is_null() { None } else { Some((* { unsafe { &*htlc.inner } }).clone()) };
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_justice_transaction(&justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), &local_htlc, &bitcoin::secp256k1::Secp256k1::new());
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_justice_transaction(&justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), &local_htlc, &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
local_ret
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_counterparty_htlc_transaction(&htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, &bitcoin::secp256k1::Secp256k1::new());
+extern "C" fn InMemorySigner_Sign_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_counterparty_htlc_transaction(&htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
local_ret
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_closing_transaction(this_arg: *const c_void, mut closing_tx: crate::c_types::Transaction) -> crate::c_types::derived::CResult_SignatureNoneZ {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_closing_transaction(&closing_tx.into_bitcoin(), &bitcoin::secp256k1::Secp256k1::new());
+extern "C" fn InMemorySigner_Sign_sign_closing_transaction(this_arg: *const c_void, mut closing_tx: crate::c_types::Transaction) -> crate::c_types::derived::CResult_SignatureNoneZ {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_closing_transaction(&closing_tx.into_bitcoin(), &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
local_ret
}
#[must_use]
-extern "C" fn InMemoryChannelKeys_ChannelKeys_sign_channel_announcement(this_arg: *const c_void, msg: &crate::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.sign_channel_announcement(unsafe { &*msg.inner }, &bitcoin::secp256k1::Secp256k1::new());
+extern "C" fn InMemorySigner_Sign_sign_channel_announcement(this_arg: *const c_void, msg: &crate::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.sign_channel_announcement(unsafe { &*msg.inner }, &bitcoin::secp256k1::Secp256k1::new());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { 0u8 /*e*/ }).into() };
local_ret
}
-extern "C" fn InMemoryChannelKeys_ChannelKeys_ready_channel(this_arg: *mut c_void, channel_parameters: &crate::ln::chan_utils::ChannelTransactionParameters) {
- unsafe { &mut *(this_arg as *mut nativeInMemoryChannelKeys) }.ready_channel(unsafe { &*channel_parameters.inner })
+extern "C" fn InMemorySigner_Sign_ready_channel(this_arg: *mut c_void, channel_parameters: &crate::ln::chan_utils::ChannelTransactionParameters) {
+ unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }.ready_channel(unsafe { &*channel_parameters.inner })
}
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_write(obj: &InMemoryChannelKeys) -> crate::c_types::derived::CVec_u8Z {
+pub extern "C" fn InMemorySigner_write(obj: &InMemorySigner) -> crate::c_types::derived::CVec_u8Z {
crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
}
#[no_mangle]
-pub(crate) extern "C" fn InMemoryChannelKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
- crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeInMemoryChannelKeys) })
+pub(crate) extern "C" fn InMemorySigner_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+ crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeInMemorySigner) })
}
#[no_mangle]
-pub extern "C" fn InMemoryChannelKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InMemoryChannelKeysDecodeErrorZ {
+pub extern "C" fn InMemorySigner_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InMemorySignerDecodeErrorZ {
let res = crate::c_types::deserialize_obj(ser);
- let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::keysinterface::InMemoryChannelKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+ let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
KeysManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
-/// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
+/// Derive an old set of Sign for per-channel secrets based on a key derivation
/// parameters.
/// Key derivation parameters are accessible through a per-channel secrets
-/// ChannelKeys::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
+/// Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
/// onchain output detection for which a corresponding delayed_payment_key must be derived.
#[must_use]
#[no_mangle]
-pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut channel_value_satoshis: u64, params: *const [u8; 32]) -> crate::chain::keysinterface::InMemoryChannelKeys {
+pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut channel_value_satoshis: u64, params: *const [u8; 32]) -> crate::chain::keysinterface::InMemorySigner {
let mut ret = unsafe { &*this_arg.inner }.derive_channel_keys(channel_value_satoshis, unsafe { &*params});
- crate::chain::keysinterface::InMemoryChannelKeys { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+ crate::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(ret)), is_owned: true }
}
/// Creates a Transaction which spends the given descriptors to the given outputs, plus an
/// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
///
/// May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used
-/// this KeysManager or one of the `InMemoryChannelKeys` created by this KeysManager.
+/// this KeysManager or one of the `InMemorySigner` created by this KeysManager.
#[must_use]
#[no_mangle]
pub extern "C" fn KeysManager_spend_spendable_outputs(this_arg: &KeysManager, mut descriptors: crate::c_types::derived::CVec_SpendableOutputDescriptorZ, mut outputs: crate::c_types::derived::CVec_TxOutZ, mut change_destination_script: crate::c_types::derived::CVec_u8Z, mut feerate_sat_per_1000_weight: u32) -> crate::c_types::derived::CResult_TransactionNoneZ {
get_node_secret: KeysManager_KeysInterface_get_node_secret,
get_destination_script: KeysManager_KeysInterface_get_destination_script,
get_shutdown_pubkey: KeysManager_KeysInterface_get_shutdown_pubkey,
- get_channel_keys: KeysManager_KeysInterface_get_channel_keys,
+ get_channel_signer: KeysManager_KeysInterface_get_channel_signer,
get_secure_random_bytes: KeysManager_KeysInterface_get_secure_random_bytes,
read_chan_signer: KeysManager_KeysInterface_read_chan_signer,
}
crate::c_types::PublicKey::from_rust(&ret)
}
#[must_use]
-extern "C" fn KeysManager_KeysInterface_get_channel_keys(this_arg: *const c_void, mut _inbound: bool, mut channel_value_satoshis: u64) -> crate::chain::keysinterface::ChannelKeys {
- let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_channel_keys(_inbound, channel_value_satoshis);
+extern "C" fn KeysManager_KeysInterface_get_channel_signer(this_arg: *const c_void, mut _inbound: bool, mut channel_value_satoshis: u64) -> crate::chain::keysinterface::Sign {
+ let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.get_channel_signer(_inbound, channel_value_satoshis);
ret.into()
}
#[must_use]
crate::c_types::ThirtyTwoBytes { data: ret }
}
#[must_use]
-extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelKeysDecodeErrorZ {
+extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ {
let mut ret = unsafe { &mut *(this_arg as *mut nativeKeysManager) }.read_chan_signer(reader.to_slice());
let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_ret
unsafe impl Sync for Watch {}
use lightning::chain::Watch as rustWatch;
-impl rustWatch for Watch {
- type Keys = crate::chain::keysinterface::ChannelKeys;
- fn watch_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::ChannelKeys>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
+impl rustWatch<crate::chain::keysinterface::Sign> for Watch {
+ fn watch_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
let mut ret = (self.watch_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(monitor)), is_owned: true });
let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
local_ret
//! Various utilities for building scripts and deriving keys related to channels. These are
-//! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing
-//! by hand.
+//! largely of interest for those implementing chain::keysinterface::Sign message signing by hand.
use std::ffi::c_void;
use bitcoin::hashes::Hash;
use lightning::ln::channelmanager::ChannelManager as nativeChannelManagerImport;
-type nativeChannelManager = nativeChannelManagerImport<crate::chain::keysinterface::ChannelKeys, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
+type nativeChannelManager = nativeChannelManagerImport<crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
/// Manager which keeps track of a number of channels and sends messages to the appropriate
/// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap())
}
+/// Blocks until ChannelManager needs to be persisted. Only one listener on `wait` is
+/// guaranteed to be woken up.
+#[no_mangle]
+pub extern "C" fn ChannelManager_wait(this_arg: &ChannelManager) {
+ unsafe { &*this_arg.inner }.wait()
+}
+
impl From<nativeChannelManager> for crate::ln::msgs::ChannelMessageHandler {
fn from(obj: nativeChannelManager) -> Self {
let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
}
use lightning::ln::channelmanager::ChannelManagerReadArgs as nativeChannelManagerReadArgsImport;
-type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::chain::keysinterface::ChannelKeys, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
+type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
/// Arguments for the creation of a ChannelManager that are not deserialized.
///
#[no_mangle]
pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
let arg_conv = *unsafe { Box::from_raw(arg.take_inner()) };
- let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager<crate::chain::keysinterface::ChannelKeys, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
+ let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager<crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::ln::channelmanager::ChannelManager { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
local_res
}
--- /dev/null
+/// Logging macro utilities.
+
+use std::ffi::c_void;
+use bitcoin::hashes::Hash;
+use crate::c_types::*;
+
pub mod events;
pub mod errors;
pub mod ser;
+pub mod macro_logger;
pub mod logger;
pub mod config;
//! type Logger = dyn lightning::util::logger::Logger;
//! type ChainAccess = dyn lightning::chain::Access;
//! type ChainFilter = dyn lightning::chain::Filter;
-//! type DataPersister = dyn lightning::chain::channelmonitor::Persist<lightning::chain::keysinterface::InMemoryChannelKeys>;
-//! type ChainMonitor = lightning::chain::chainmonitor::ChainMonitor<lightning::chain::keysinterface::InMemoryChannelKeys, Arc<ChainFilter>, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<DataPersister>>;
+//! type DataPersister = dyn lightning::chain::channelmonitor::Persist<lightning::chain::keysinterface::InMemorySigner>;
+//! type ChainMonitor = lightning::chain::chainmonitor::ChainMonitor<lightning::chain::keysinterface::InMemorySigner, Arc<ChainFilter>, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>, Arc<DataPersister>>;
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChainMonitor, TxBroadcaster, FeeEstimator, Logger>;
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChainMonitor, TxBroadcaster, FeeEstimator, ChainAccess, Logger>;
//!
use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr};
use lightning::chain::channelmonitor;
-use lightning::chain::keysinterface::{ChannelKeys, KeysInterface};
+use lightning::chain::keysinterface::{Sign, KeysInterface};
use lightning::chain::transaction::OutPoint;
use lightning::ln::channelmanager::ChannelManager;
use lightning::util::logger::Logger;
path_to_channel_data: String,
}
-impl<ChanSigner: ChannelKeys> DiskWriteable for ChannelMonitor<ChanSigner> {
+impl<Signer: Sign> DiskWriteable for ChannelMonitor<Signer> {
fn write_to_file(&self, writer: &mut fs::File) -> Result<(), Error> {
self.write(writer)
}
}
-impl<ChanSigner, M, T, K, F, L> DiskWriteable for ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
-where ChanSigner: ChannelKeys + Writeable,
- M: chain::Watch<Keys=ChanSigner>,
- T: BroadcasterInterface,
- K: KeysInterface<ChanKeySigner=ChanSigner>,
- F: FeeEstimator,
- L: Logger,
+impl<Signer: Sign, M, T, K, F, L> DiskWriteable for ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
+where M: chain::Watch<Signer>,
+ T: BroadcasterInterface,
+ K: KeysInterface<Signer=Signer>,
+ F: FeeEstimator,
+ L: Logger,
{
fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error> {
self.write(writer)
/// Writes the provided `ChannelManager` to the path provided at `FilesystemPersister`
/// initialization, within a file called "manager".
- pub fn persist_manager<ChanSigner, M, T, K, F, L>(
+ pub fn persist_manager<Signer, M, T, K, F, L>(
data_dir: String,
- manager: &ChannelManager<ChanSigner, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
+ manager: &ChannelManager<Signer, Arc<M>, Arc<T>, Arc<K>, Arc<F>, Arc<L>>
) -> Result<(), std::io::Error>
- where ChanSigner: ChannelKeys + Writeable,
- M: chain::Watch<Keys=ChanSigner>,
- T: BroadcasterInterface,
- K: KeysInterface<ChanKeySigner=ChanSigner>,
- F: FeeEstimator,
- L: Logger
+ where Signer: Sign,
+ M: chain::Watch<Signer>,
+ T: BroadcasterInterface,
+ K: KeysInterface<Signer=Signer>,
+ F: FeeEstimator,
+ L: Logger
{
util::write_to_file(data_dir, "manager".to_string(), manager)
}
#[cfg(test)]
fn load_channel_data<Keys: KeysInterface>(&self, keys: &Keys) ->
- Result<HashMap<OutPoint, ChannelMonitor<Keys::ChanKeySigner>>, ChannelMonitorUpdateErr> {
+ Result<HashMap<OutPoint, ChannelMonitor<Keys::Signer>>, ChannelMonitorUpdateErr> {
if let Err(_) = fs::create_dir_all(&self.path_to_channel_data) {
return Err(ChannelMonitorUpdateErr::PermanentFailure);
}
if contents.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
if let Ok((_, loaded_monitor)) =
- <(BlockHash, ChannelMonitor<Keys::ChanKeySigner>)>::read(&mut Cursor::new(&contents.unwrap()), keys) {
+ <(BlockHash, ChannelMonitor<Keys::Signer>)>::read(&mut Cursor::new(&contents.unwrap()), keys) {
res.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, loaded_monitor);
} else {
return Err(ChannelMonitorUpdateErr::PermanentFailure);
}
}
-impl<ChanSigner: ChannelKeys + Send + Sync> channelmonitor::Persist<ChanSigner> for FilesystemPersister {
- fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
+impl<ChannelSigner: Sign + Send + Sync> channelmonitor::Persist<ChannelSigner> for FilesystemPersister {
+ fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
util::write_to_file(self.path_to_channel_data.clone(), filename, monitor)
.map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
}
- fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
+ fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &ChannelMonitorUpdate, monitor: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
let filename = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
util::write_to_file(self.path_to_channel_data.clone(), filename, monitor)
.map_err(|_| ChannelMonitorUpdateErr::PermanentFailure)
use chain::channelmonitor;
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, Persist};
use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::ChannelKeys;
+use chain::keysinterface::Sign;
use util::logger::Logger;
use util::events;
use util::events::Event;
/// [`chain::Watch`]: ../trait.Watch.html
/// [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html
/// [module-level documentation]: index.html
-pub struct ChainMonitor<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
+pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
where C::Target: chain::Filter,
T::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
- P::Target: channelmonitor::Persist<ChanSigner>,
+ P::Target: channelmonitor::Persist<ChannelSigner>,
{
/// The monitors
- pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChanSigner>>>,
+ pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChannelSigner>>>,
chain_source: Option<C>,
broadcaster: T,
logger: L,
persister: P,
}
-impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChanSigner, C, T, F, L, P>
+impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
where C::Target: chain::Filter,
T::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
- P::Target: channelmonitor::Persist<ChanSigner>,
+ P::Target: channelmonitor::Persist<ChannelSigner>,
{
/// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
/// of a channel and reacting accordingly based on transactions in the connected block. See
}
}
-impl<ChanSigner: ChannelKeys, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, P: Deref + Sync + Send> chain::Watch for ChainMonitor<ChanSigner, C, T, F, L, P>
+impl<ChannelSigner: Sign, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, P: Deref + Sync + Send>
+chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
where C::Target: chain::Filter,
T::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
- P::Target: channelmonitor::Persist<ChanSigner>,
+ P::Target: channelmonitor::Persist<ChannelSigner>,
{
- type Keys = ChanSigner;
-
/// Adds the monitor that watches the channel referred to by the given outpoint.
///
/// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
/// monitors lock.
///
/// [`chain::Filter`]: ../trait.Filter.html
- fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
+ fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
let mut monitors = self.monitors.lock().unwrap();
let entry = match monitors.entry(funding_outpoint) {
hash_map::Entry::Occupied(_) => {
}
}
-impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChanSigner, C, T, F, L, P>
+impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
where C::Target: chain::Filter,
T::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
- P::Target: channelmonitor::Persist<ChanSigner>,
+ P::Target: channelmonitor::Persist<ChannelSigner>,
{
fn get_and_clear_pending_events(&self) -> Vec<Event> {
let mut pending_events = Vec::new();
use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, ChannelKeys, KeysInterface};
+use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
use util::logger::Logger;
use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48};
use util::byte_utils;
/// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
/// returned block hash and the the current chain and then reconnecting blocks to get to the
/// best chain) upon deserializing the object!
-pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
+pub struct ChannelMonitor<Signer: Sign> {
latest_update_id: u64,
commitment_transaction_number_obscure_factor: u64,
outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
#[cfg(test)]
- pub onchain_tx_handler: OnchainTxHandler<ChanSigner>,
+ pub onchain_tx_handler: OnchainTxHandler<Signer>,
#[cfg(not(test))]
- onchain_tx_handler: OnchainTxHandler<ChanSigner>,
+ onchain_tx_handler: OnchainTxHandler<Signer>,
// This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
// channel has been force-closed. After this is set, no further holder commitment transaction
#[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
/// Used only in testing and fuzztarget to check serialization roundtrips don't change the
/// underlying object
-impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
+impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
fn eq(&self, other: &Self) -> bool {
if self.latest_update_id != other.latest_update_id ||
self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
}
}
-impl<ChanSigner: ChannelKeys> Writeable for ChannelMonitor<ChanSigner> {
+impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
//TODO: We still write out all the serialization here manually instead of using the fancy
//serialization framework we have, we should migrate things over to it.
}
}
-impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
- pub(crate) fn new(keys: ChanSigner, shutdown_pubkey: &PublicKey,
+impl<Signer: Sign> ChannelMonitor<Signer> {
+ pub(crate) fn new(keys: Signer, shutdown_pubkey: &PublicKey,
on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
channel_parameters: &ChannelTransactionParameters,
funding_redeemscript: Script, channel_value_satoshis: u64,
commitment_transaction_number_obscure_factor: u64,
- initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor<ChanSigner> {
+ initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor<Signer> {
assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
let our_channel_close_key_hash = WPubkeyHash::hash(&shutdown_pubkey.serialize());
/// transaction and losing money. This is a risk because previous channel states
/// are toxic, so it's important that whatever channel state is persisted is
/// kept up-to-date.
-pub trait Persist<Keys: ChannelKeys>: Send + Sync {
+pub trait Persist<ChannelSigner: Sign>: Send + Sync {
/// Persist a new channel's data. The data can be stored any way you want, but
/// the identifier provided by Rust-Lightning is the channel's outpoint (and
/// it is up to you to maintain a correct mapping between the outpoint and the
///
/// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
/// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
- fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<Keys>) -> Result<(), ChannelMonitorUpdateErr>;
+ fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
/// Update one channel's data. The provided `ChannelMonitor` has already
/// applied the given update.
/// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
/// [`ChannelMonitorUpdate::write`]: struct.ChannelMonitorUpdate.html#method.write
/// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
- fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<Keys>) -> Result<(), ChannelMonitorUpdateErr>;
+ fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
}
const MAX_ALLOC_SIZE: usize = 64*1024;
-impl<'a, ChanSigner: ChannelKeys, K: KeysInterface<ChanKeySigner = ChanSigner>> ReadableArgs<&'a K>
- for (BlockHash, ChannelMonitor<ChanSigner>) {
+impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
+ for (BlockHash, ChannelMonitor<Signer>) {
fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
macro_rules! unwrap_obj {
($key: expr) => {
use bitcoin::secp256k1::key::{SecretKey,PublicKey};
use bitcoin::secp256k1::Secp256k1;
use std::sync::{Arc, Mutex};
- use chain::keysinterface::InMemoryChannelKeys;
+ use chain::keysinterface::InMemorySigner;
#[test]
fn test_prune_preimages() {
}
}
- let keys = InMemoryChannelKeys::new(
+ let keys = InMemorySigner::new(
&secp_ctx,
SecretKey::from_slice(&[41; 32]).unwrap(),
SecretKey::from_slice(&[41; 32]).unwrap(),
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
}
}
- assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
+ assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
// Claim tx with 1 offered HTLCs, 3 received HTLCs
claim_tx.input.clear();
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
}
}
- assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
+ assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
// Justice tx with 1 revoked HTLC-Success tx output
claim_tx.input.clear();
sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs);
}
}
- assert_eq!(base_weight + OnchainTxHandler::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
+ assert_eq!(base_weight + OnchainTxHandler::<InMemorySigner>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
}
// Further testing is done in the ChannelManager integration tests.
/// derive the witnessScript for this output.
pub revocation_pubkey: PublicKey,
/// Arbitrary identification information returned by a call to
- /// `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+ /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
/// the channel to spend the output.
pub channel_keys_id: [u8; 32],
/// The value of the channel which this output originated from, possibly indirectly.
/// The output which is referenced by the given outpoint
pub output: TxOut,
/// Arbitrary identification information returned by a call to
- /// `ChannelKeys::channel_keys_id()`. This may be useful in re-deriving keys used in
+ /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
/// the channel to spend the output.
pub channel_keys_id: [u8; 32],
/// The value of the channel which this transactions spends.
///
/// To derive the delayed_payment key which is used to sign for this input, you must pass the
/// holder delayed_payment_base_key (ie the private key which corresponds to the pubkey in
- /// ChannelKeys::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
+ /// Sign::pubkeys().delayed_payment_basepoint) and the provided per_commitment_point to
/// chan_utils::derive_private_key. The public key can be generated without the secret key
/// using chan_utils::derive_public_key and only the delayed_payment_basepoint which appears in
- /// ChannelKeys::pubkeys().
+ /// Sign::pubkeys().
///
/// To derive the revocation_pubkey provided here (which is used in the witness
/// script generation), you must pass the counterparty revocation_basepoint (which appears in the
- /// call to ChannelKeys::ready_channel) and the provided per_commitment point
+ /// call to Sign::ready_channel) and the provided per_commitment point
/// to chan_utils::derive_public_revocation_key.
///
/// The witness script which is hashed and included in the output script_pubkey may be
/// chan_utils::get_revokeable_redeemscript.
DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
/// An output to a P2WPKH, spendable exclusively by our payment key (ie the private key which
- /// corresponds to the public key in ChannelKeys::pubkeys().payment_point).
+ /// corresponds to the public key in Sign::pubkeys().payment_point).
/// The witness in the spending input, is, thus, simply:
/// <BIP 143 signature> <payment key>
///
}
}
-/// Set of lightning keys needed to operate a channel as described in BOLT 3.
+/// A trait to sign lightning channel transactions as described in BOLT 3.
///
/// Signing services could be implemented on a hardware wallet. In this case,
-/// the current ChannelKeys would be a front-end on top of a communication
+/// the current Sign would be a front-end on top of a communication
/// channel connected to your secure device and lightning key material wouldn't
/// reside on a hot server. Nevertheless, a this deployment would still need
/// to trust the ChannelManager to avoid loss of funds as this latest component
/// In any case, ChannelMonitor or fallback watchtowers are always going to be trusted
/// to act, as liveness and breach reply correctness are always going to be hard requirements
/// of LN security model, orthogonal of key management issues.
-// TODO: We should remove Clone by instead requesting a new ChannelKeys copy when we create
+// TODO: We should remove Clone by instead requesting a new Sign copy when we create
// ChannelMonitors instead of expecting to clone the one out of the Channel into the monitors.
-pub trait ChannelKeys : Send+Clone + Writeable {
+pub trait Sign : Send+Clone + Writeable {
/// Gets the per-commitment point for a specific commitment number
///
/// Note that the commitment number starts at (1 << 48) - 1 and counts backwards.
fn pubkeys(&self) -> &ChannelPublicKeys;
/// Gets an arbitrary identifier describing the set of keys which are provided back to you in
/// some SpendableOutputDescriptor types. This should be sufficient to identify this
- /// ChannelKeys object uniquely and lookup or re-derive its keys.
+ /// Sign object uniquely and lookup or re-derive its keys.
fn channel_keys_id(&self) -> [u8; 32];
/// Create a signature for a counterparty's commitment transaction and associated HTLC transactions.
/// A trait to describe an object which can get user secrets and key material.
pub trait KeysInterface: Send + Sync {
- /// A type which implements ChannelKeys which will be returned by get_channel_keys.
- type ChanKeySigner : ChannelKeys;
+ /// A type which implements Sign which will be returned by get_channel_signer.
+ type Signer : Sign;
/// Get node secret key (aka node_id or network_key).
///
/// This method should return a different value each time it is called, to avoid linking
/// on-chain funds across channels as controlled to the same user.
fn get_shutdown_pubkey(&self) -> PublicKey;
- /// Get a new set of ChannelKeys for per-channel secrets. These MUST be unique even if you
+ /// Get a new set of Sign for per-channel secrets. These MUST be unique even if you
/// restarted with some stale data!
///
/// This method must return a different value each time it is called.
- fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner;
+ fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> Self::Signer;
/// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting
/// onion packets and for temporary channel IDs. There is no requirement that these be
/// persisted anywhere, though they must be unique across restarts.
/// This method must return a different value each time it is called.
fn get_secure_random_bytes(&self) -> [u8; 32];
- /// Reads a `ChanKeySigner` for this `KeysInterface` from the given input stream.
+ /// Reads a `Signer` for this `KeysInterface` from the given input stream.
/// This is only called during deserialization of other objects which contain
- /// `ChannelKeys`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
- /// The bytes are exactly those which `<Self::ChanKeySigner as Writeable>::write()` writes, and
+ /// `Sign`-implementing objects (ie `ChannelMonitor`s and `ChannelManager`s).
+ /// The bytes are exactly those which `<Self::Signer as Writeable>::write()` writes, and
/// contain no versioning scheme. You may wish to include your own version prefix and ensure
/// you've read all of the provided bytes to ensure no corruption occurred.
- fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::ChanKeySigner, DecodeError>;
+ fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError>;
}
#[derive(Clone)]
-/// A simple implementation of ChannelKeys that just keeps the private keys in memory.
+/// A simple implementation of Sign that just keeps the private keys in memory.
///
/// This implementation performs no policy checks and is insufficient by itself as
/// a secure external signer.
-pub struct InMemoryChannelKeys {
+pub struct InMemorySigner {
/// Private key of anchor tx
pub funding_key: SecretKey,
/// Holder secret key for blinded revocation pubkey
channel_keys_id: [u8; 32],
}
-impl InMemoryChannelKeys {
- /// Create a new InMemoryChannelKeys
+impl InMemorySigner {
+ /// Create a new InMemorySigner
pub fn new<C: Signing>(
secp_ctx: &Secp256k1<C>,
funding_key: SecretKey,
htlc_base_key: SecretKey,
commitment_seed: [u8; 32],
channel_value_satoshis: u64,
- channel_keys_id: [u8; 32]) -> InMemoryChannelKeys {
+ channel_keys_id: [u8; 32]) -> InMemorySigner {
let holder_channel_pubkeys =
- InMemoryChannelKeys::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
+ InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
&payment_key, &delayed_payment_base_key,
&htlc_base_key);
- InMemoryChannelKeys {
+ InMemorySigner {
funding_key,
revocation_base_key,
payment_key,
}
}
-impl ChannelKeys for InMemoryChannelKeys {
+impl Sign for InMemorySigner {
fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey {
let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
PublicKey::from_secret_key(secp_ctx, &commitment_secret)
}
}
-impl Writeable for InMemoryChannelKeys {
+impl Writeable for InMemorySigner {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
self.funding_key.write(writer)?;
self.revocation_base_key.write(writer)?;
}
}
-impl Readable for InMemoryChannelKeys {
+impl Readable for InMemorySigner {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let funding_key = Readable::read(reader)?;
let revocation_base_key = Readable::read(reader)?;
let channel_value_satoshis = Readable::read(reader)?;
let secp_ctx = Secp256k1::signing_only();
let holder_channel_pubkeys =
- InMemoryChannelKeys::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
+ InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
&payment_key, &delayed_payment_base_key,
&htlc_base_key);
let keys_id = Readable::read(reader)?;
- Ok(InMemoryChannelKeys {
+ Ok(InMemorySigner {
funding_key,
revocation_base_key,
payment_key,
unique_start.input(&self.seed);
unique_start
}
- /// Derive an old set of ChannelKeys for per-channel secrets based on a key derivation
+ /// Derive an old set of Sign for per-channel secrets based on a key derivation
/// parameters.
/// Key derivation parameters are accessible through a per-channel secrets
- /// ChannelKeys::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
+ /// Sign::channel_keys_id and is provided inside DynamicOuputP2WSH in case of
/// onchain output detection for which a corresponding delayed_payment_key must be derived.
- pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemoryChannelKeys {
+ pub fn derive_channel_keys(&self, channel_value_satoshis: u64, params: &[u8; 32]) -> InMemorySigner {
let chan_id = byte_utils::slice_to_be64(¶ms[0..8]);
assert!(chan_id <= std::u32::MAX as u64); // Otherwise the params field wasn't created by us
let mut unique_start = Sha256::engine();
let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key);
let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
- InMemoryChannelKeys::new(
+ InMemorySigner::new(
&self.secp_ctx,
funding_key,
revocation_base_key,
/// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
///
/// May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used
- /// this KeysManager or one of the `InMemoryChannelKeys` created by this KeysManager.
+ /// this KeysManager or one of the `InMemorySigner` created by this KeysManager.
pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
let mut input = Vec::new();
let mut input_value = 0;
};
transaction_utils::maybe_add_change_output(&mut spend_tx, input_value, witness_weight, feerate_sat_per_1000_weight, change_destination_script)?;
- let mut keys_cache: Option<(InMemoryChannelKeys, [u8; 32])> = None;
+ let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
let mut input_idx = 0;
for outp in descriptors {
match outp {
}
impl KeysInterface for KeysManager {
- type ChanKeySigner = InMemoryChannelKeys;
+ type Signer = InMemorySigner;
fn get_node_secret(&self) -> SecretKey {
self.node_secret.clone()
self.shutdown_pubkey.clone()
}
- fn get_channel_keys(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::ChanKeySigner {
+ fn get_channel_signer(&self, _inbound: bool, channel_value_satoshis: u64) -> Self::Signer {
let child_ix = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
assert!(child_ix <= std::u32::MAX as usize);
let mut id = [0; 32];
Sha256::from_engine(sha).into_inner()
}
- fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::ChanKeySigner, DecodeError> {
- InMemoryChannelKeys::read(&mut std::io::Cursor::new(reader))
+ fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
+ InMemorySigner::read(&mut std::io::Cursor::new(reader))
}
}
use bitcoin::hash_types::{BlockHash, Txid};
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent};
-use chain::keysinterface::ChannelKeys;
+use chain::keysinterface::Sign;
use chain::transaction::OutPoint;
pub mod chaininterface;
/// [`ChannelMonitor`]: channelmonitor/struct.ChannelMonitor.html
/// [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
/// [`PermanentFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure
-pub trait Watch: Send + Sync {
- /// Keys needed by monitors for creating and signing transactions.
- type Keys: ChannelKeys;
-
+pub trait Watch<ChannelSigner: Sign>: Send + Sync {
/// Watches a channel identified by `funding_txo` using `monitor`.
///
/// Implementations are responsible for watching the chain for the funding transaction along
/// [`get_outputs_to_watch`]: channelmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch
/// [`block_connected`]: channelmonitor/struct.ChannelMonitor.html#method.block_connected
/// [`block_disconnected`]: channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
- fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<Self::Keys>) -> Result<(), ChannelMonitorUpdateErr>;
+ fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
/// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
///
// licenses.
//! Various utilities for building scripts and deriving keys related to channels. These are
-//! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing
-//! by hand.
+//! largely of interest for those implementing chain::keysinterface::Sign message signing by hand.
use bitcoin::blockdata::script::{Script,Builder};
use bitcoin::blockdata::opcodes;
use ln::msgs;
use ln::msgs::{ChannelMessageHandler, ErrorAction, RoutingMessageHandler};
use routing::router::get_route;
-use util::enforcing_trait_impls::EnforcingChannelKeys;
+use util::enforcing_trait_impls::EnforcingSigner;
use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
use util::errors::APIError;
use util::ser::{ReadableArgs, Writeable};
let monitor = monitors.get(&outpoint).unwrap();
let mut w = test_utils::TestVecWriter(Vec::new());
monitor.write(&mut w).unwrap();
- let new_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let new_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
assert!(new_monitor == *monitor);
let chain_mon = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER};
use chain::transaction::{OutPoint, TransactionData};
-use chain::keysinterface::{ChannelKeys, KeysInterface};
+use chain::keysinterface::{Sign, KeysInterface};
use util::transaction_utils;
use util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
use util::logger::Logger;
//
// Holder designates channel data owned for the benefice of the user client.
// Counterparty designates channel data owned by the another channel participant entity.
-pub(super) struct Channel<ChanSigner: ChannelKeys> {
+pub(super) struct Channel<Signer: Sign> {
config: ChannelConfig,
user_id: u64,
latest_monitor_update_id: u64,
- #[cfg(not(test))]
- holder_keys: ChanSigner,
- #[cfg(test)]
- pub(super) holder_keys: ChanSigner,
+ holder_signer: Signer,
shutdown_pubkey: PublicKey,
destination_script: Script,
};
}
-impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
+impl<Signer: Sign> Channel<Signer> {
// Convert constants + channel value to limits:
fn get_holder_max_htlc_value_in_flight_msat(channel_value_satoshis: u64) -> u64 {
channel_value_satoshis * 1000 / 10 //TODO
}
// Constructors:
- pub fn new_outbound<K: Deref, F: Deref>(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, config: &UserConfig) -> Result<Channel<ChanSigner>, APIError>
- where K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ pub fn new_outbound<K: Deref, F: Deref>(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, config: &UserConfig) -> Result<Channel<Signer>, APIError>
+ where K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
{
let holder_selected_contest_delay = config.own_channel_config.our_to_self_delay;
- let chan_keys = keys_provider.get_channel_keys(false, channel_value_satoshis);
- let pubkeys = chan_keys.pubkeys().clone();
+ let holder_signer = keys_provider.get_channel_signer(false, channel_value_satoshis);
+ let pubkeys = holder_signer.pubkeys().clone();
if channel_value_satoshis >= MAX_FUNDING_SATOSHIS {
return Err(APIError::APIMisuseError{err: format!("funding_value must be smaller than {}, it was {}", MAX_FUNDING_SATOSHIS, channel_value_satoshis)});
return Err(APIError::APIMisuseError {err: format!("Configured with an unreasonable our_to_self_delay ({}) putting user funds at risks", holder_selected_contest_delay)});
}
let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
- if Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_satoshis) < Channel::<ChanSigner>::derive_holder_dust_limit_satoshis(background_feerate) {
+ if Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(channel_value_satoshis) < Channel::<Signer>::derive_holder_dust_limit_satoshis(background_feerate) {
return Err(APIError::FeeRateTooHigh{err: format!("Not enough reserve above dust limit can be found at current fee rate({})", background_feerate), feerate: background_feerate});
}
latest_monitor_update_id: 0,
- holder_keys: chan_keys,
+ holder_signer,
shutdown_pubkey: keys_provider.get_shutdown_pubkey(),
destination_script: keys_provider.get_destination_script(),
feerate_per_kw: feerate,
counterparty_dust_limit_satoshis: 0,
- holder_dust_limit_satoshis: Channel::<ChanSigner>::derive_holder_dust_limit_satoshis(background_feerate),
+ holder_dust_limit_satoshis: Channel::<Signer>::derive_holder_dust_limit_satoshis(background_feerate),
counterparty_max_htlc_value_in_flight_msat: 0,
counterparty_selected_channel_reserve_satoshis: 0,
counterparty_htlc_minimum_msat: 0,
/// Creates a new channel from a remote sides' request for one.
/// Assumes chain_hash has already been checked and corresponds with what we expect!
- pub fn new_from_req<K: Deref, F: Deref>(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel, user_id: u64, config: &UserConfig) -> Result<Channel<ChanSigner>, ChannelError>
- where K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ pub fn new_from_req<K: Deref, F: Deref>(fee_estimator: &F, keys_provider: &K, counterparty_node_id: PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel, user_id: u64, config: &UserConfig) -> Result<Channel<Signer>, ChannelError>
+ where K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator
{
- let chan_keys = keys_provider.get_channel_keys(true, msg.funding_satoshis);
- let pubkeys = chan_keys.pubkeys().clone();
+ let holder_signer = keys_provider.get_channel_signer(true, msg.funding_satoshis);
+ let pubkeys = holder_signer.pubkeys().clone();
let counterparty_pubkeys = ChannelPublicKeys {
funding_pubkey: msg.funding_pubkey,
revocation_basepoint: msg.revocation_basepoint,
if msg.htlc_minimum_msat >= full_channel_value_msat {
return Err(ChannelError::Close(format!("Minimum htlc value ({}) was larger than full channel value ({})", msg.htlc_minimum_msat, full_channel_value_msat)));
}
- Channel::<ChanSigner>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
+ Channel::<Signer>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
let max_counterparty_selected_contest_delay = u16::min(config.peer_channel_config_limits.their_to_self_delay, MAX_LOCAL_BREAKDOWN_TIMEOUT);
if msg.to_self_delay > max_counterparty_selected_contest_delay {
let background_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
- let holder_dust_limit_satoshis = Channel::<ChanSigner>::derive_holder_dust_limit_satoshis(background_feerate);
- let holder_selected_channel_reserve_satoshis = Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(msg.funding_satoshis);
+ let holder_dust_limit_satoshis = Channel::<Signer>::derive_holder_dust_limit_satoshis(background_feerate);
+ let holder_selected_channel_reserve_satoshis = Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(msg.funding_satoshis);
if holder_selected_channel_reserve_satoshis < holder_dust_limit_satoshis {
return Err(ChannelError::Close(format!("Suitable channel reserve not found. remote_channel_reserve was ({}). dust_limit_satoshis is ({}).", holder_selected_channel_reserve_satoshis, holder_dust_limit_satoshis)));
}
latest_monitor_update_id: 0,
- holder_keys: chan_keys,
+ holder_signer,
shutdown_pubkey: keys_provider.get_shutdown_pubkey(),
destination_script: keys_provider.get_destination_script(),
};
debug_assert!(broadcaster_max_commitment_tx_output.0 <= value_to_self_msat as u64 || value_to_self_msat / 1000 >= self.counterparty_selected_channel_reserve_satoshis as i64);
broadcaster_max_commitment_tx_output.0 = cmp::max(broadcaster_max_commitment_tx_output.0, value_to_self_msat as u64);
- debug_assert!(broadcaster_max_commitment_tx_output.1 <= value_to_remote_msat as u64 || value_to_remote_msat / 1000 >= Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) as i64);
+ debug_assert!(broadcaster_max_commitment_tx_output.1 <= value_to_remote_msat as u64 || value_to_remote_msat / 1000 >= Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) as i64);
broadcaster_max_commitment_tx_output.1 = cmp::max(broadcaster_max_commitment_tx_output.1, value_to_remote_msat as u64);
}
/// The result is a transaction which we can revoke broadcastership of (ie a "local" transaction)
/// TODO Some magic rust shit to compile-time check this?
fn build_holder_transaction_keys(&self, commitment_number: u64) -> Result<TxCreationKeys, ChannelError> {
- let per_commitment_point = self.holder_keys.get_per_commitment_point(commitment_number, &self.secp_ctx);
+ let per_commitment_point = self.holder_signer.get_per_commitment_point(commitment_number, &self.secp_ctx);
let delayed_payment_base = &self.get_holder_pubkeys().delayed_payment_basepoint;
let htlc_basepoint = &self.get_holder_pubkeys().htlc_basepoint;
let counterparty_pubkeys = self.get_counterparty_pubkeys();
if msg.channel_reserve_satoshis < self.holder_dust_limit_satoshis {
return Err(ChannelError::Close(format!("Peer never wants payout outputs? channel_reserve_satoshis was ({}). dust_limit is ({})", msg.channel_reserve_satoshis, self.holder_dust_limit_satoshis)));
}
- let remote_reserve = Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
+ let remote_reserve = Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
if msg.dust_limit_satoshis > remote_reserve {
return Err(ChannelError::Close(format!("Dust limit ({}) is bigger than our channel reserve ({})", msg.dust_limit_satoshis, remote_reserve)));
}
let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction();
log_trace!(logger, "Initial counterparty ID {} tx {}", counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
- let counterparty_signature = self.holder_keys.sign_counterparty_commitment(&counterparty_initial_commitment_tx, &self.secp_ctx)
+ let counterparty_signature = self.holder_signer.sign_counterparty_commitment(&counterparty_initial_commitment_tx, &self.secp_ctx)
.map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0;
// We sign "counterparty" commitment transaction, allowing them to broadcast the tx if they wish.
&self.get_counterparty_pubkeys().funding_pubkey
}
- pub fn funding_created<L: Deref>(&mut self, msg: &msgs::FundingCreated, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor<ChanSigner>), ChannelError> where L::Target: Logger {
+ pub fn funding_created<L: Deref>(&mut self, msg: &msgs::FundingCreated, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor<Signer>), ChannelError> where L::Target: Logger {
if self.is_outbound() {
return Err(ChannelError::Close("Received funding_created for an outbound channel?".to_owned()));
}
self.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
// This is an externally observable change before we finish all our checks. In particular
// funding_created_signature may fail.
- self.holder_keys.ready_channel(&self.channel_transaction_parameters);
+ self.holder_signer.ready_channel(&self.channel_transaction_parameters);
let (counterparty_initial_commitment_txid, initial_commitment_tx, signature) = match self.funding_created_signature(&msg.signature, logger) {
Ok(res) => res,
let funding_redeemscript = self.get_funding_redeemscript();
let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
- let mut channel_monitor = ChannelMonitor::new(self.holder_keys.clone(),
+ let mut channel_monitor = ChannelMonitor::new(self.holder_signer.clone(),
&self.shutdown_pubkey, self.get_holder_selected_contest_delay(),
&self.destination_script, (funding_txo, funding_txo_script.clone()),
&self.channel_transaction_parameters,
/// Handles a funding_signed message from the remote end.
/// If this call is successful, broadcast the funding transaction (and not before!)
- pub fn funding_signed<L: Deref>(&mut self, msg: &msgs::FundingSigned, logger: &L) -> Result<ChannelMonitor<ChanSigner>, ChannelError> where L::Target: Logger {
+ pub fn funding_signed<L: Deref>(&mut self, msg: &msgs::FundingSigned, logger: &L) -> Result<ChannelMonitor<Signer>, ChannelError> where L::Target: Logger {
if !self.is_outbound() {
return Err(ChannelError::Close("Received funding_signed for an inbound channel?".to_owned()));
}
log_trace!(logger, "Initial counterparty ID {} tx {}", counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
- let holder_keys = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
- let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &holder_keys, true, false, self.feerate_per_kw, logger).0;
+ let holder_signer = self.build_holder_transaction_keys(self.cur_holder_commitment_transaction_number)?;
+ let initial_commitment_tx = self.build_commitment_transaction(self.cur_holder_commitment_transaction_number, &holder_signer, true, false, self.feerate_per_kw, logger).0;
{
let trusted_tx = initial_commitment_tx.trust();
let initial_commitment_bitcoin_tx = trusted_tx.built_transaction();
let funding_txo = self.get_funding_txo().unwrap();
let funding_txo_script = funding_redeemscript.to_v0_p2wsh();
let obscure_factor = get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound());
- let mut channel_monitor = ChannelMonitor::new(self.holder_keys.clone(),
+ let mut channel_monitor = ChannelMonitor::new(self.holder_signer.clone(),
&self.shutdown_pubkey, self.get_holder_selected_contest_delay(),
&self.destination_script, (funding_txo, funding_txo_script),
&self.channel_transaction_parameters,
if inbound_htlc_count + 1 > OUR_MAX_HTLCS as u32 {
return Err(ChannelError::Close(format!("Remote tried to push more than our max accepted HTLCs ({})", OUR_MAX_HTLCS)));
}
- let holder_max_htlc_value_in_flight_msat = Channel::<ChanSigner>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis);
+ let holder_max_htlc_value_in_flight_msat = Channel::<Signer>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis);
if htlc_inbound_value_msat + msg.amount_msat > holder_max_htlc_value_in_flight_msat {
return Err(ChannelError::Close(format!("Remote HTLC add would put them over our max HTLC value ({})", holder_max_htlc_value_in_flight_msat)));
}
};
let chan_reserve_msat =
- Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) * 1000;
+ Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis) * 1000;
if pending_remote_value_msat - msg.amount_msat - remote_commit_tx_fee_msat < chan_reserve_msat {
return Err(ChannelError::Close("Remote HTLC add would put them under remote reserve value".to_owned()));
}
let total_fee = feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
//If channel fee was updated by funder confirm funder can afford the new fee rate when applied to the current local commitment transaction
if update_fee {
- let counterparty_reserve_we_require = Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
+ let counterparty_reserve_we_require = Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
if self.channel_value_satoshis - self.value_to_self_msat / 1000 < total_fee + counterparty_reserve_we_require {
return Err((None, ChannelError::Close("Funding remote cannot afford proposed new fee".to_owned())));
}
self.counterparty_funding_pubkey()
);
- let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number - 1, &self.secp_ctx);
- let per_commitment_secret = self.holder_keys.release_commitment_secret(self.cur_holder_commitment_transaction_number + 1);
+ let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number - 1, &self.secp_ctx);
+ let per_commitment_secret = self.holder_signer.release_commitment_secret(self.cur_holder_commitment_transaction_number + 1);
// Update state now that we've passed all the can-fail calls...
let mut need_commitment = false;
let funding_locked = if self.monitor_pending_funding_locked {
assert!(!self.is_outbound(), "Funding transaction broadcast without FundingBroadcastSafe!");
self.monitor_pending_funding_locked = false;
- let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+ let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
Some(msgs::FundingLocked {
channel_id: self.channel_id(),
next_per_commitment_point,
if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
return Err(ChannelError::Close("Peer sent update_fee when we needed a channel_reestablish".to_owned()));
}
- Channel::<ChanSigner>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
+ Channel::<Signer>::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
self.pending_update_fee = Some(msg.feerate_per_kw);
self.update_time_counter += 1;
Ok(())
}
fn get_last_revoke_and_ack(&self) -> msgs::RevokeAndACK {
- let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
- let per_commitment_secret = self.holder_keys.release_commitment_secret(self.cur_holder_commitment_transaction_number + 2);
+ let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+ let per_commitment_secret = self.holder_signer.release_commitment_secret(self.cur_holder_commitment_transaction_number + 2);
msgs::RevokeAndACK {
channel_id: self.channel_id,
per_commitment_secret,
if msg.next_remote_commitment_number > 0 {
match msg.data_loss_protect {
OptionalField::Present(ref data_loss) => {
- let expected_point = self.holder_keys.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1, &self.secp_ctx);
+ let expected_point = self.holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1, &self.secp_ctx);
let given_secret = SecretKey::from_slice(&data_loss.your_last_per_commitment_secret)
.map_err(|_| ChannelError::Close("Peer sent a garbage channel_reestablish with unparseable secret key".to_owned()))?;
if expected_point != PublicKey::from_secret_key(&self.secp_ctx, &given_secret) {
}
// We have OurFundingLocked set!
- let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+ let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
return Ok((Some(msgs::FundingLocked {
channel_id: self.channel_id(),
next_per_commitment_point,
let resend_funding_locked = if msg.next_local_commitment_number == 1 && INITIAL_COMMITMENT_NUMBER - self.cur_holder_commitment_transaction_number == 1 {
// We should never have to worry about MonitorUpdateFailed resending FundingLocked
- let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+ let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
Some(msgs::FundingLocked {
channel_id: self.channel_id(),
next_per_commitment_point,
let proposed_total_fee_satoshis = proposed_feerate as u64 * tx_weight / 1000;
let (closing_tx, total_fee_satoshis) = self.build_closing_transaction(proposed_total_fee_satoshis, false);
- let sig = self.holder_keys
+ let sig = self.holder_signer
.sign_closing_transaction(&closing_tx, &self.secp_ctx)
.ok();
assert!(closing_tx.get_weight() as u64 <= tx_weight);
($new_feerate: expr) => {
let tx_weight = self.get_closing_transaction_weight(Some(&self.get_closing_scriptpubkey()), Some(self.counterparty_shutdown_scriptpubkey.as_ref().unwrap()));
let (closing_tx, used_total_fee) = self.build_closing_transaction($new_feerate as u64 * tx_weight / 1000, false);
- let sig = self.holder_keys
+ let sig = self.holder_signer
.sign_closing_transaction(&closing_tx, &self.secp_ctx)
.map_err(|_| ChannelError::Close("External signer refused to sign closing transaction".to_owned()))?;
assert!(closing_tx.get_weight() as u64 <= tx_weight);
propose_new_feerate!(min_feerate);
}
- let sig = self.holder_keys
+ let sig = self.holder_signer
.sign_closing_transaction(&closing_tx, &self.secp_ctx)
.map_err(|_| ChannelError::Close("External signer refused to sign closing transaction".to_owned()))?;
self.build_signed_closing_transaction(&mut closing_tx, &msg.signature, &sig);
// channel might have been used to route very small values (either by honest users or as DoS).
self.channel_value_satoshis * 9 / 10,
- Channel::<ChanSigner>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis)
+ Channel::<Signer>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis)
);
}
}
#[cfg(test)]
- pub fn get_keys(&self) -> &ChanSigner {
- &self.holder_keys
+ pub fn get_signer(&self) -> &Signer {
+ &self.holder_signer
}
#[cfg(test)]
//a protocol oversight, but I assume I'm just missing something.
if need_commitment_update {
if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) == 0 {
- let next_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+ let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
return Ok((Some(msgs::FundingLocked {
channel_id: self.channel_id,
next_per_commitment_point,
panic!("Tried to send an open_channel for a channel that has already advanced");
}
- let first_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+ let first_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
let keys = self.get_holder_pubkeys();
msgs::OpenChannel {
funding_satoshis: self.channel_value_satoshis,
push_msat: self.channel_value_satoshis * 1000 - self.value_to_self_msat,
dust_limit_satoshis: self.holder_dust_limit_satoshis,
- max_htlc_value_in_flight_msat: Channel::<ChanSigner>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis),
- channel_reserve_satoshis: Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis),
+ max_htlc_value_in_flight_msat: Channel::<Signer>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis),
+ channel_reserve_satoshis: Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis),
htlc_minimum_msat: self.holder_htlc_minimum_msat,
feerate_per_kw: self.feerate_per_kw as u32,
to_self_delay: self.get_holder_selected_contest_delay(),
panic!("Tried to send an accept_channel for a channel that has already advanced");
}
- let first_per_commitment_point = self.holder_keys.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
+ let first_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
let keys = self.get_holder_pubkeys();
msgs::AcceptChannel {
temporary_channel_id: self.channel_id,
dust_limit_satoshis: self.holder_dust_limit_satoshis,
- max_htlc_value_in_flight_msat: Channel::<ChanSigner>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis),
- channel_reserve_satoshis: Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis),
+ max_htlc_value_in_flight_msat: Channel::<Signer>::get_holder_max_htlc_value_in_flight_msat(self.channel_value_satoshis),
+ channel_reserve_satoshis: Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis),
htlc_minimum_msat: self.holder_htlc_minimum_msat,
minimum_depth: self.minimum_depth,
to_self_delay: self.get_holder_selected_contest_delay(),
fn get_outbound_funding_created_signature<L: Deref>(&mut self, logger: &L) -> Result<Signature, ChannelError> where L::Target: Logger {
let counterparty_keys = self.build_remote_transaction_keys()?;
let counterparty_initial_commitment_tx = self.build_commitment_transaction(self.cur_counterparty_commitment_transaction_number, &counterparty_keys, false, false, self.feerate_per_kw, logger).0;
- Ok(self.holder_keys.sign_counterparty_commitment(&counterparty_initial_commitment_tx, &self.secp_ctx)
+ Ok(self.holder_signer.sign_counterparty_commitment(&counterparty_initial_commitment_tx, &self.secp_ctx)
.map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?.0)
}
}
self.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
- self.holder_keys.ready_channel(&self.channel_transaction_parameters);
+ self.holder_signer.ready_channel(&self.channel_transaction_parameters);
let signature = match self.get_outbound_funding_created_signature(logger) {
Ok(res) => res,
excess_data: Vec::new(),
};
- let sig = self.holder_keys.sign_channel_announcement(&msg, &self.secp_ctx)
+ let sig = self.holder_signer.sign_channel_announcement(&msg, &self.secp_ctx)
.map_err(|_| ChannelError::Ignore("Signer rejected channel_announcement".to_owned()))?;
Ok((msg, sig))
if !self.is_outbound() {
// Check that we won't violate the remote channel reserve by adding this HTLC.
let counterparty_balance_msat = self.channel_value_satoshis * 1000 - self.value_to_self_msat;
- let holder_selected_chan_reserve_msat = Channel::<ChanSigner>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
+ let holder_selected_chan_reserve_msat = Channel::<Signer>::get_holder_selected_channel_reserve_satoshis(self.channel_value_satoshis);
let htlc_candidate = HTLCCandidate::new(amount_msat, HTLCInitiator::LocalOffered);
let counterparty_commit_tx_fee_msat = self.next_remote_commit_tx_fee_msat(htlc_candidate, None);
if counterparty_balance_msat < holder_selected_chan_reserve_msat + counterparty_commit_tx_fee_msat {
htlcs.push(htlc);
}
- let res = self.holder_keys.sign_counterparty_commitment(&counterparty_commitment_tx.0, &self.secp_ctx)
+ let res = self.holder_signer.sign_counterparty_commitment(&counterparty_commitment_tx.0, &self.secp_ctx)
.map_err(|_| ChannelError::Close("Failed to get signatures for new commitment_signed".to_owned()))?;
signature = res.0;
htlc_signatures = res.1;
}
}
-impl<ChanSigner: ChannelKeys> Writeable for Channel<ChanSigner> {
+impl<Signer: Sign> Writeable for Channel<Signer> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
// Note that we write out as if remove_uncommitted_htlcs_and_mark_paused had just been
// called but include holding cell updates (and obviously we don't modify self).
self.latest_monitor_update_id.write(writer)?;
let mut key_data = VecWriter(Vec::new());
- self.holder_keys.write(&mut key_data)?;
+ self.holder_signer.write(&mut key_data)?;
assert!(key_data.0.len() < std::usize::MAX);
assert!(key_data.0.len() < std::u32::MAX as usize);
(key_data.0.len() as u32).write(writer)?;
}
const MAX_ALLOC_SIZE: usize = 64*1024;
-impl<'a, ChanSigner: ChannelKeys, K: Deref> ReadableArgs<&'a K> for Channel<ChanSigner>
- where K::Target: KeysInterface<ChanKeySigner = ChanSigner> {
+impl<'a, Signer: Sign, K: Deref> ReadableArgs<&'a K> for Channel<Signer>
+ where K::Target: KeysInterface<Signer = Signer> {
fn read<R : ::std::io::Read>(reader: &mut R, keys_source: &'a K) -> Result<Self, DecodeError> {
let _ver: u8 = Readable::read(reader)?;
let min_ver: u8 = Readable::read(reader)?;
reader.read_exact(read_slice)?;
keys_data.extend_from_slice(read_slice);
}
- let holder_keys = keys_source.read_chan_signer(&keys_data)?;
+ let holder_signer = keys_source.read_chan_signer(&keys_data)?;
let shutdown_pubkey = Readable::read(reader)?;
let destination_script = Readable::read(reader)?;
latest_monitor_update_id,
- holder_keys,
+ holder_signer,
shutdown_pubkey,
destination_script,
use bitcoin::hashes::hex::FromHex;
use hex;
use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
- use ln::channel::{Channel,ChannelKeys,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,HTLCCandidate,HTLCInitiator,TxCreationKeys};
+ use ln::channel::{Channel,Sign,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,HTLCCandidate,HTLCInitiator,TxCreationKeys};
use ln::channel::MAX_FUNDING_SATOSHIS;
use ln::features::InitFeatures;
use ln::msgs::{OptionalField, DataLossProtect, DecodeError};
use ln::chan_utils;
use ln::chan_utils::{ChannelPublicKeys, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT};
use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
- use chain::keysinterface::{InMemoryChannelKeys, KeysInterface};
+ use chain::keysinterface::{InMemorySigner, KeysInterface};
use chain::transaction::OutPoint;
use util::config::UserConfig;
- use util::enforcing_trait_impls::EnforcingChannelKeys;
+ use util::enforcing_trait_impls::EnforcingSigner;
use util::test_utils;
use util::logger::Logger;
use bitcoin::secp256k1::{Secp256k1, Message, Signature, All};
}
struct Keys {
- chan_keys: InMemoryChannelKeys,
+ signer: InMemorySigner,
}
impl KeysInterface for Keys {
- type ChanKeySigner = InMemoryChannelKeys;
+ type Signer = InMemorySigner;
fn get_node_secret(&self) -> SecretKey { panic!(); }
fn get_destination_script(&self) -> Script {
PublicKey::from_secret_key(&secp_ctx, &channel_close_key)
}
- fn get_channel_keys(&self, _inbound: bool, _channel_value_satoshis: u64) -> InMemoryChannelKeys {
- self.chan_keys.clone()
+ fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> InMemorySigner {
+ self.signer.clone()
}
fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
- fn read_chan_signer(&self, _data: &[u8]) -> Result<Self::ChanKeySigner, DecodeError> { panic!(); }
+ fn read_chan_signer(&self, _data: &[u8]) -> Result<Self::Signer, DecodeError> { panic!(); }
}
fn public_from_secret_hex(secp_ctx: &Secp256k1<All>, hex: &str) -> PublicKey {
let node_a_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
let config = UserConfig::default();
- let node_a_chan = Channel::<EnforcingChannelKeys>::new_outbound(&&fee_est, &&keys_provider, node_a_node_id, 10000000, 100000, 42, &config).unwrap();
+ let node_a_chan = Channel::<EnforcingSigner>::new_outbound(&&fee_est, &&keys_provider, node_a_node_id, 10000000, 100000, 42, &config).unwrap();
// Now change the fee so we can check that the fee in the open_channel message is the
// same as the old fee.
// Create Node A's channel pointing to Node B's pubkey
let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
let config = UserConfig::default();
- let mut node_a_chan = Channel::<EnforcingChannelKeys>::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap();
+ let mut node_a_chan = Channel::<EnforcingSigner>::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap();
// Create Node B's channel by receiving Node A's open_channel message
// Make sure A's dust limit is as we expect.
let open_channel_msg = node_a_chan.get_open_channel(genesis_block(network).header.block_hash());
assert_eq!(open_channel_msg.dust_limit_satoshis, 1560);
let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
- let node_b_chan = Channel::<EnforcingChannelKeys>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap();
+ let node_b_chan = Channel::<EnforcingSigner>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap();
// Node B --> Node A: accept channel, explicitly setting B's dust limit.
let mut accept_channel_msg = node_b_chan.get_accept_channel();
let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
let config = UserConfig::default();
- let mut chan = Channel::<EnforcingChannelKeys>::new_outbound(&&fee_est, &&keys_provider, node_id, 10000000, 100000, 42, &config).unwrap();
+ let mut chan = Channel::<EnforcingSigner>::new_outbound(&&fee_est, &&keys_provider, node_id, 10000000, 100000, 42, &config).unwrap();
let commitment_tx_fee_0_htlcs = chan.commit_tx_fee_msat(0);
let commitment_tx_fee_1_htlc = chan.commit_tx_fee_msat(1);
// Create Node A's channel pointing to Node B's pubkey
let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
let config = UserConfig::default();
- let mut node_a_chan = Channel::<EnforcingChannelKeys>::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap();
+ let mut node_a_chan = Channel::<EnforcingSigner>::new_outbound(&&feeest, &&keys_provider, node_b_node_id, 10000000, 100000, 42, &config).unwrap();
// Create Node B's channel by receiving Node A's open_channel message
let open_channel_msg = node_a_chan.get_open_channel(genesis_block(network).header.block_hash());
let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
- let mut node_b_chan = Channel::<EnforcingChannelKeys>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap();
+ let mut node_b_chan = Channel::<EnforcingSigner>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, InitFeatures::known(), &open_channel_msg, 7, &config).unwrap();
// Node B --> Node A: accept channel
let accept_channel_msg = node_b_chan.get_accept_channel();
let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
let secp_ctx = Secp256k1::new();
- let mut chan_keys = InMemoryChannelKeys::new(
+ let mut signer = InMemorySigner::new(
&secp_ctx,
SecretKey::from_slice(&hex::decode("30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749").unwrap()[..]).unwrap(),
SecretKey::from_slice(&hex::decode("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(),
[0; 32]
);
- assert_eq!(chan_keys.pubkeys().funding_pubkey.serialize()[..],
+ assert_eq!(signer.pubkeys().funding_pubkey.serialize()[..],
hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]);
- let keys_provider = Keys { chan_keys: chan_keys.clone() };
+ let keys_provider = Keys { signer: signer.clone() };
let counterparty_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
let mut config = UserConfig::default();
config.channel_options.announced_channel = false;
- let mut chan = Channel::<InMemoryChannelKeys>::new_outbound(&&feeest, &&keys_provider, counterparty_node_id, 10_000_000, 100000, 42, &config).unwrap(); // Nothing uses their network key in this test
+ let mut chan = Channel::<InMemorySigner>::new_outbound(&&feeest, &&keys_provider, counterparty_node_id, 10_000_000, 100000, 42, &config).unwrap(); // Nothing uses their network key in this test
chan.holder_dust_limit_satoshis = 546;
let funding_info = OutPoint{ txid: Txid::from_hex("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(), index: 0 };
selected_contest_delay: 144
});
chan.channel_transaction_parameters.funding_outpoint = Some(funding_info);
- chan_keys.ready_channel(&chan.channel_transaction_parameters);
+ signer.ready_channel(&chan.channel_transaction_parameters);
assert_eq!(counterparty_pubkeys.payment_point.serialize()[..],
hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]);
// We can't just use build_holder_transaction_keys here as the per_commitment_secret is not
// derived from a commitment_seed, so instead we copy it here and call
// build_commitment_transaction.
- let delayed_payment_base = &chan.holder_keys.pubkeys().delayed_payment_basepoint;
+ let delayed_payment_base = &chan.holder_signer.pubkeys().delayed_payment_basepoint;
let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
- let htlc_basepoint = &chan.holder_keys.pubkeys().htlc_basepoint;
+ let htlc_basepoint = &chan.holder_signer.pubkeys().htlc_basepoint;
let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint).unwrap();
macro_rules! test_commitment {
commitment_tx.clone(),
counterparty_signature,
counterparty_htlc_sigs,
- &chan.holder_keys.pubkeys().funding_pubkey,
+ &chan.holder_signer.pubkeys().funding_pubkey,
chan.counterparty_funding_pubkey()
);
- let (holder_sig, htlc_sigs) = chan_keys.sign_holder_commitment_and_htlcs(&holder_commitment_tx, &secp_ctx).unwrap();
+ let (holder_sig, htlc_sigs) = signer.sign_holder_commitment_and_htlcs(&holder_commitment_tx, &secp_ctx).unwrap();
assert_eq!(Signature::from_der(&hex::decode($sig_hex).unwrap()[..]).unwrap(), holder_sig, "holder_sig");
let funding_redeemscript = chan.get_funding_redeemscript();
use ln::msgs::NetAddress;
use ln::onion_utils;
use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
-use chain::keysinterface::{ChannelKeys, KeysInterface, KeysManager, InMemoryChannelKeys};
+use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner};
use util::config::UserConfig;
use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
use util::{byte_utils, events};
}
// Note this is only exposed in cfg(test):
-pub(super) struct ChannelHolder<ChanSigner: ChannelKeys> {
- pub(super) by_id: HashMap<[u8; 32], Channel<ChanSigner>>,
+pub(super) struct ChannelHolder<Signer: Sign> {
+ pub(super) by_id: HashMap<[u8; 32], Channel<Signer>>,
pub(super) short_to_id: HashMap<u64, [u8; 32]>,
/// short channel id -> forward infos. Key of 0 means payments received
/// Note that while this is held in the same mutex as the channels themselves, no consistency
/// issues such as overly long function definitions. Note that the ChannelManager can take any
/// type that implements KeysInterface for its keys manager, but this type alias chooses the
/// concrete type of the KeysManager.
-pub type SimpleArcChannelManager<M, T, F, L> = Arc<ChannelManager<InMemoryChannelKeys, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>>;
+pub type SimpleArcChannelManager<M, T, F, L> = Arc<ChannelManager<InMemorySigner, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>>;
/// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
/// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
/// helps with issues such as long function definitions. Note that the ChannelManager can take any
/// type that implements KeysInterface for its keys manager, but this type alias chooses the
/// concrete type of the KeysManager.
-pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemoryChannelKeys, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
+pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemorySigner, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
/// Manager which keeps track of a number of channels and sends messages to the appropriate
/// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
/// essentially you should default to using a SimpleRefChannelManager, and use a
/// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
/// you're using lightning-net-tokio.
-pub struct ChannelManager<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+pub struct ChannelManager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
secp_ctx: Secp256k1<secp256k1::All>,
#[cfg(any(test, feature = "_test_utils"))]
- pub(super) channel_state: Mutex<ChannelHolder<ChanSigner>>,
+ pub(super) channel_state: Mutex<ChannelHolder<Signer>>,
#[cfg(not(any(test, feature = "_test_utils")))]
- channel_state: Mutex<ChannelHolder<ChanSigner>>,
+ channel_state: Mutex<ChannelHolder<Signer>>,
our_network_key: SecretKey,
/// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
}
}
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<ChanSigner, M, T, K, F, L>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
Ok(())
}
- fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<ChanSigner>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
+ fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
let mut res = Vec::new();
{
let channel_state = self.channel_state.lock().unwrap();
}
}
- fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<ChanSigner>>) {
+ fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<Signer>>) {
macro_rules! return_malformed_err {
($msg: expr, $err_code: expr) => {
{
/// only fails if the channel does not yet have an assigned short_id
/// May be called with channel_state already locked!
- fn get_channel_update(&self, chan: &Channel<ChanSigner>) -> Result<msgs::ChannelUpdate, LightningError> {
+ fn get_channel_update(&self, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
let short_channel_id = match chan.get_short_channel_id() {
None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
Some(id) => id,
}
}
- fn get_announcement_sigs(&self, chan: &Channel<ChanSigner>) -> Option<msgs::AnnouncementSignatures> {
+ fn get_announcement_sigs(&self, chan: &Channel<Signer>) -> Option<msgs::AnnouncementSignatures> {
if !chan.should_announce() {
log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
return None
/// to fail and take the channel_state lock for each iteration (as we take ownership and may
/// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
/// still-available channels.
- fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
+ fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
//TODO: There is a timing attack here where if a node fails an HTLC back to us they can
//identify whether we sent it or not based on the (I presume) very different runtime
//between the branches here. We should make this async and move it into the forward HTLCs
} else { false }
}
- fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<ChanSigner>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
+ fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
//TODO: Delay the claimed_funds relaying just like we do outbound relay!
let channel_state = &mut **channel_state_lock;
let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
} else { unreachable!(); }
}
- fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
+ fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
match source {
HTLCSource::OutboundRoute { .. } => {
mem::drop(channel_state_lock);
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
}
- let create_pending_htlc_status = |chan: &Channel<ChanSigner>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
+ let create_pending_htlc_status = |chan: &Channel<Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
// Ensure error_code has the UPDATE flag set, since by default we send a
// channel update along as part of failing the HTLC.
assert!((error_code & 0x1000) != 0);
}
}
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<Signer, M, T, K, F, L>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
}
}
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<Signer, M, T, K, F, L>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
}
}
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<ChanSigner, M, T, K, F, L>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
}
}
-impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
- ChannelMessageHandler for ChannelManager<ChanSigner, M, T, K, F, L>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
+ ChannelMessageHandler for ChannelManager<Signer, M, T, K, F, L>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
}
}
-impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<ChanSigner, M, T, K, F, L>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<Signer, M, T, K, F, L>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
/// 4) Reconnect blocks on your ChannelMonitors.
/// 5) Move the ChannelMonitors into your local chain::Watch.
/// 6) Disconnect/connect blocks on the ChannelManager.
-pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
/// this struct.
///
/// (C-not exported) because we have no HashMap bindings
- pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<ChanSigner>>,
+ pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<Signer>>,
}
-impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
- ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+ ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
/// HashMap for you. This is primarily useful for C bindings where it is not practical to
/// populate a HashMap directly from C.
pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
- mut channel_monitors: Vec<&'a mut ChannelMonitor<ChanSigner>>) -> Self {
+ mut channel_monitors: Vec<&'a mut ChannelMonitor<Signer>>) -> Self {
Self {
keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config,
channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
// Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
// SipmleArcChannelManager type:
-impl<'a, ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
- ReadableArgs<ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<ChanSigner, M, T, K, F, L>>)
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+ ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<Signer, M, T, K, F, L>>)
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
- fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result<Self, DecodeError> {
- let (blockhash, chan_manager) = <(BlockHash, ChannelManager<ChanSigner, M, T, K, F, L>)>::read(reader, args)?;
+ fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
+ let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
Ok((blockhash, Arc::new(chan_manager)))
}
}
-impl<'a, ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
- ReadableArgs<ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>> for (BlockHash, ChannelManager<ChanSigner, M, T, K, F, L>)
- where M::Target: chain::Watch<Keys=ChanSigner>,
+impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
+ ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, ChannelManager<Signer, M, T, K, F, L>)
+ where M::Target: chain::Watch<Signer>,
T::Target: BroadcasterInterface,
- K::Target: KeysInterface<ChanKeySigner = ChanSigner>,
+ K::Target: KeysInterface<Signer = Signer>,
F::Target: FeeEstimator,
L::Target: Logger,
{
- fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L>) -> Result<Self, DecodeError> {
+ fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
let _ver: u8 = Readable::read(reader)?;
let min_ver: u8 = Readable::read(reader)?;
if min_ver > SERIALIZATION_VERSION {
let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
for _ in 0..channel_count {
- let mut channel: Channel<ChanSigner> = Channel::read(reader, &args.keys_manager)?;
+ let mut channel: Channel<Signer> = Channel::read(reader, &args.keys_manager)?;
if channel.last_block_connected != Default::default() && channel.last_block_connected != last_block_hash {
return Err(DecodeError::InvalidValue);
}
use ln::features::InitFeatures;
use ln::msgs;
use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
-use util::enforcing_trait_impls::EnforcingChannelKeys;
+use util::enforcing_trait_impls::EnforcingSigner;
use util::test_utils;
use util::test_utils::TestChainMonitor;
use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
pub tx_broadcaster: &'c test_utils::TestBroadcaster,
pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
pub keys_manager: &'b test_utils::TestKeysInterface,
- pub node: &'a ChannelManager<EnforcingChannelKeys, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
+ pub node: &'a ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
pub net_graph_msg_handler: NetGraphMsgHandler<&'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
pub node_seed: [u8; 32],
pub network_payment_count: Rc<RefCell<u8>>,
for (_, old_monitor) in old_monitors.iter() {
let mut w = test_utils::TestVecWriter(Vec::new());
old_monitor.write(&mut w).unwrap();
- let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap();
deserialized_monitors.push(deserialized_monitor);
}
let mut w = test_utils::TestVecWriter(Vec::new());
self.node.write(&mut w).unwrap();
- <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs {
+ <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs {
default_config: UserConfig::default(),
keys_manager: self.keys_manager,
fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: 253 },
nodes
}
-pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingChannelKeys, &'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> {
+pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingSigner, &'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> {
let mut chanmgrs = Vec::new();
for i in 0..node_count {
let mut default_config = UserConfig::default();
chanmgrs
}
-pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<EnforcingChannelKeys, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
+pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
let mut nodes = Vec::new();
let chan_count = Rc::new(RefCell::new(0));
let payment_count = Rc::new(RefCell::new(0));
use chain::channelmonitor;
use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
use chain::transaction::OutPoint;
-use chain::keysinterface::{ChannelKeys, KeysInterface};
+use chain::keysinterface::{Sign, KeysInterface};
use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
use ln::channel::{Channel, ChannelError};
use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use ln::msgs;
use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
-use util::enforcing_trait_impls::EnforcingChannelKeys;
+use util::enforcing_trait_impls::EnforcingSigner;
use util::{byte_utils, test_utils};
use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
use util::errors::APIError;
// Instantiate channel parameters where we push the maximum msats given our
// funding satoshis
let channel_value_sat = 31337; // same as funding satoshis
- let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
+ let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
// Have node0 initiate a channel to node1 with aforementioned parameters
const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
- // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
+ // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
// needed to sign the new commitment tx and (2) sign the new commitment tx.
let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
let chan_lock = nodes[0].node.channel_state.lock().unwrap();
let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
- let chan_keys = local_chan.get_keys();
- let pubkeys = chan_keys.pubkeys();
+ let chan_signer = local_chan.get_signer();
+ let pubkeys = chan_signer.pubkeys();
(pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
- chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
- chan_keys.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
+ chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
+ chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
};
let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
let chan_lock = nodes[1].node.channel_state.lock().unwrap();
let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
- let chan_keys = remote_chan.get_keys();
- let pubkeys = chan_keys.pubkeys();
+ let chan_signer = remote_chan.get_signer();
+ let pubkeys = chan_signer.pubkeys();
(pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
- chan_keys.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
+ chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
};
// Assemble the set of keys we can use for signatures for our commitment_signed message.
let res = {
let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
- let local_chan_keys = local_chan.get_keys();
+ let local_chan_signer = local_chan.get_signer();
let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
commitment_number,
95000,
&mut vec![(accepted_htlc_info, ())],
&local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
);
- local_chan_keys.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
+ local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
};
let commit_signed_msg = msgs::CommitmentSigned {
nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
- let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
- let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
+ let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
+ let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
let as_network_key = nodes[0].node.get_our_node_id();
let bs_network_key = nodes[1].node.get_our_node_id();
macro_rules! sign_msg {
($unsigned_msg: expr) => {
let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
- let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
- let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
+ let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
+ let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
chan_announcement = msgs::ChannelAnnouncement {
let fee_estimator: test_utils::TestFeeEstimator;
let persister: test_utils::TestPersister;
let new_chain_monitor: test_utils::TestChainMonitor;
- let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+ let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
nodes[0].chain_monitor = &new_chain_monitor;
let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
- let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
&mut chan_0_monitor_read, keys_manager).unwrap();
assert!(chan_0_monitor_read.is_empty());
let (_, nodes_0_deserialized_tmp) = {
let mut channel_monitors = HashMap::new();
channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
- <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+ <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
default_config: config,
keys_manager,
fee_estimator: &fee_estimator,
let persister: test_utils::TestPersister;
let logger: test_utils::TestLogger;
let new_chain_monitor: test_utils::TestChainMonitor;
- let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+ let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
// Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
nodes[0].chain_monitor = &new_chain_monitor;
let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
- let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
&mut chan_0_monitor_read, keys_manager).unwrap();
assert!(chan_0_monitor_read.is_empty());
let (_, nodes_0_deserialized_tmp) = {
let mut channel_monitors = HashMap::new();
channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
- <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+ <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
default_config: config,
keys_manager,
fee_estimator: &fee_estimator,
let fee_estimator: test_utils::TestFeeEstimator;
let persister: test_utils::TestPersister;
let new_chain_monitor: test_utils::TestChainMonitor;
- let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+ let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
nodes[0].chain_monitor = &new_chain_monitor;
let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
- let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
&mut chan_0_monitor_read, keys_manager).unwrap();
assert!(chan_0_monitor_read.is_empty());
let (_, nodes_0_deserialized_tmp) = {
let mut channel_monitors = HashMap::new();
channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
- <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+ <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
default_config: UserConfig::default(),
keys_manager,
fee_estimator: &fee_estimator,
let fee_estimator: test_utils::TestFeeEstimator;
let persister: test_utils::TestPersister;
let new_chain_monitor: test_utils::TestChainMonitor;
- let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+ let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
let mut node_0_stale_monitors = Vec::new();
for serialized in node_0_stale_monitors_serialized.iter() {
let mut read = &serialized[..];
- let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, keys_manager).unwrap();
+ let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
assert!(read.is_empty());
node_0_stale_monitors.push(monitor);
}
let mut node_0_monitors = Vec::new();
for serialized in node_0_monitors_serialized.iter() {
let mut read = &serialized[..];
- let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, keys_manager).unwrap();
+ let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
assert!(read.is_empty());
node_0_monitors.push(monitor);
}
let mut nodes_0_read = &nodes_0_serialized[..];
if let Err(msgs::DecodeError::InvalidValue) =
- <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+ <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
default_config: UserConfig::default(),
keys_manager,
fee_estimator: &fee_estimator,
let mut nodes_0_read = &nodes_0_serialized[..];
let (_, nodes_0_deserialized_tmp) =
- <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
+ <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
default_config: UserConfig::default(),
keys_manager,
fee_estimator: &fee_estimator,
// Restore node A from previous state
logger = test_utils::TestLogger::with_id(format!("node {}", 0));
- let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
+ let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
chain_source = test_utils::TestChainSource::new(Network::Testnet);
tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
node_state_0 = {
let mut channel_monitors = HashMap::new();
channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
- <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
+ <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
keys_manager: keys_manager,
fee_estimator: &fee_estimator,
chain_monitor: &monitor,
// commitment transaction, we would have happily carried on and provided them the next
// commitment transaction based on one RAA forward. This would probably eventually have led to
// channel closure, but it would not have resulted in funds loss. Still, our
- // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
+ // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
// check simply that the channel is closed in response to such an RAA, but don't check whether
// we decide to punish our counterparty for revoking their funds (as we don't currently
// implement that).
let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
let mut guard = nodes[0].node.channel_state.lock().unwrap();
- let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
+ let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
// Must revoke without gaps
let monitor = monitors.get(&outpoint).unwrap();
let mut w = test_utils::TestVecWriter(Vec::new());
monitor.write(&mut w).unwrap();
- let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
assert!(new_monitor == *monitor);
let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
let monitor = monitors.get(&outpoint).unwrap();
let mut w = test_utils::TestVecWriter(Vec::new());
monitor.write(&mut w).unwrap();
- let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
assert!(new_monitor == *monitor);
let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
let monitor = monitors.get(&outpoint).unwrap();
let mut w = test_utils::TestVecWriter(Vec::new());
monitor.write(&mut w).unwrap();
- let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
assert!(new_monitor == *monitor);
let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
use ln::chan_utils::{TxCreationKeys, ChannelTransactionParameters, HolderCommitmentTransaction};
use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
use chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest};
-use chain::keysinterface::{ChannelKeys, KeysInterface};
+use chain::keysinterface::{Sign, KeysInterface};
use util::logger::Logger;
use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter};
use util::byte_utils;
/// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
/// do RBF bumping if possible.
-pub struct OnchainTxHandler<ChanSigner: ChannelKeys> {
+pub struct OnchainTxHandler<ChannelSigner: Sign> {
destination_script: Script,
holder_commitment: HolderCommitmentTransaction,
// holder_htlc_sigs and prev_holder_htlc_sigs are in the order as they appear in the commitment
prev_holder_commitment: Option<HolderCommitmentTransaction>,
prev_holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
- key_storage: ChanSigner,
+ signer: ChannelSigner,
pub(crate) channel_transaction_parameters: ChannelTransactionParameters,
// Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
secp_ctx: Secp256k1<secp256k1::All>,
}
-impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
+impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
self.destination_script.write(writer)?;
self.holder_commitment.write(writer)?;
self.channel_transaction_parameters.write(writer)?;
let mut key_data = VecWriter(Vec::new());
- self.key_storage.write(&mut key_data)?;
+ self.signer.write(&mut key_data)?;
assert!(key_data.0.len() < std::usize::MAX);
assert!(key_data.0.len() < std::u32::MAX as usize);
(key_data.0.len() as u32).write(writer)?;
}
}
-impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::ChanKeySigner> {
+impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
let destination_script = Readable::read(reader)?;
reader.read_exact(read_slice)?;
keys_data.extend_from_slice(read_slice);
}
- let key_storage = keys_manager.read_chan_signer(&keys_data)?;
+ let signer = keys_manager.read_chan_signer(&keys_data)?;
let pending_claim_requests_len: u64 = Readable::read(reader)?;
let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
holder_htlc_sigs,
prev_holder_commitment,
prev_holder_htlc_sigs,
- key_storage,
+ signer,
channel_transaction_parameters: channel_parameters,
claimable_outpoints,
pending_claim_requests,
}
}
-impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
- pub(crate) fn new(destination_script: Script, keys: ChanSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction) -> Self {
-
- let key_storage = keys;
-
+impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
+ pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction) -> Self {
OnchainTxHandler {
destination_script,
holder_commitment,
holder_htlc_sigs: None,
prev_holder_commitment: None,
prev_holder_htlc_sigs: None,
- key_storage,
+ signer,
channel_transaction_parameters: channel_parameters,
pending_claim_requests: HashMap::new(),
claimable_outpoints: HashMap::new(),
for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
match per_outp_material {
&InputMaterial::Revoked { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref per_commitment_key, ref input_descriptor, ref amount, ref htlc, ref on_counterparty_tx_csv } => {
- if let Ok(chan_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, counterparty_delayed_payment_base_key, counterparty_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) {
+ if let Ok(tx_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, counterparty_delayed_payment_base_key, counterparty_htlc_base_key, &self.signer.pubkeys().revocation_basepoint, &self.signer.pubkeys().htlc_basepoint) {
let witness_script = if let Some(ref htlc) = *htlc {
- chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key)
+ chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &tx_keys.broadcaster_htlc_key, &tx_keys.countersignatory_htlc_key, &tx_keys.revocation_key)
} else {
- chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, *on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key)
+ chan_utils::get_revokeable_redeemscript(&tx_keys.revocation_key, *on_counterparty_tx_csv, &tx_keys.broadcaster_delayed_payment_key)
};
- let sig = self.key_storage.sign_justice_transaction(&bumped_tx, i, *amount, &per_commitment_key, htlc, &self.secp_ctx).expect("sign justice tx");
+ let sig = self.signer.sign_justice_transaction(&bumped_tx, i, *amount, &per_commitment_key, htlc, &self.secp_ctx).expect("sign justice tx");
bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
if htlc.is_some() {
- bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
+ bumped_tx.input[i].witness.push(tx_keys.revocation_key.clone().serialize().to_vec());
} else {
bumped_tx.input[i].witness.push(vec!(1));
}
}
},
&InputMaterial::CounterpartyHTLC { ref per_commitment_point, ref counterparty_delayed_payment_base_key, ref counterparty_htlc_base_key, ref preimage, ref htlc } => {
- if let Ok(chan_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, counterparty_delayed_payment_base_key, counterparty_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) {
- let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
+ if let Ok(tx_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, counterparty_delayed_payment_base_key, counterparty_htlc_base_key, &self.signer.pubkeys().revocation_basepoint, &self.signer.pubkeys().htlc_basepoint) {
+ let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &tx_keys.broadcaster_htlc_key, &tx_keys.countersignatory_htlc_key, &tx_keys.revocation_key);
if !preimage.is_some() { bumped_tx.lock_time = htlc.cltv_expiry }; // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
- let sig = self.key_storage.sign_counterparty_htlc_transaction(&bumped_tx, i, &htlc.amount_msat / 1000, &per_commitment_point, htlc, &self.secp_ctx).expect("sign counterparty HTLC tx");
+ let sig = self.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &htlc.amount_msat / 1000, &per_commitment_point, htlc, &self.secp_ctx).expect("sign counterparty HTLC tx");
bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
if let &Some(preimage) = preimage {
// ChannelMonitor replica, so we handle that case here.
fn sign_latest_holder_htlcs(&mut self) {
if self.holder_htlc_sigs.is_none() {
- let (_sig, sigs) = self.key_storage.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
+ let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, sigs));
}
}
fn sign_prev_holder_htlcs(&mut self) {
if self.prev_holder_htlc_sigs.is_none() {
if let Some(ref holder_commitment) = self.prev_holder_commitment {
- let (_sig, sigs) = self.key_storage.sign_holder_commitment_and_htlcs(holder_commitment, &self.secp_ctx).expect("sign previous holder commitment");
+ let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(holder_commitment, &self.secp_ctx).expect("sign previous holder commitment");
self.prev_holder_htlc_sigs = Some(Self::extract_holder_sigs(holder_commitment, sigs));
}
}
// before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
// to monitor before.
pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
- let (sig, htlc_sigs) = self.key_storage.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("signing holder commitment");
+ let (sig, htlc_sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("signing holder commitment");
self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
}
#[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
- let (sig, htlc_sigs) = self.key_storage.unsafe_sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
+ let (sig, htlc_sigs) = self.signer.unsafe_sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
}
use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, HolderCommitmentTransaction, CommitmentTransaction, ChannelTransactionParameters, TrustedCommitmentTransaction};
use ln::{chan_utils, msgs};
-use chain::keysinterface::{ChannelKeys, InMemoryChannelKeys};
+use chain::keysinterface::{Sign, InMemorySigner};
use std::cmp;
use std::sync::{Mutex, Arc};
/// Initial value for revoked commitment downward counter
pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48;
-/// An implementation of ChannelKeys that enforces some policy checks. The current checks
+/// An implementation of Sign that enforces some policy checks. The current checks
/// are an incomplete set. They include:
///
/// - When signing, the holder transaction has not been revoked
/// Eventually we will probably want to expose a variant of this which would essentially
/// be what you'd want to run on a hardware wallet.
#[derive(Clone)]
-pub struct EnforcingChannelKeys {
- pub inner: InMemoryChannelKeys,
+pub struct EnforcingSigner {
+ pub inner: InMemorySigner,
/// The last counterparty commitment number we signed, backwards counting
pub last_commitment_number: Arc<Mutex<Option<u64>>>,
/// The last holder commitment number we revoked, backwards counting
pub disable_revocation_policy_check: bool,
}
-impl EnforcingChannelKeys {
- /// Construct an EnforcingChannelKeys
- pub fn new(inner: InMemoryChannelKeys) -> Self {
+impl EnforcingSigner {
+ /// Construct an EnforcingSigner
+ pub fn new(inner: InMemorySigner) -> Self {
Self {
inner,
last_commitment_number: Arc::new(Mutex::new(None)),
}
}
- /// Construct an EnforcingChannelKeys with externally managed storage
+ /// Construct an EnforcingSigner with externally managed storage
///
/// Since there are multiple copies of this struct for each channel, some coordination is needed
/// so that all copies are aware of revocations. A pointer to this state is provided here, usually
/// by an implementation of KeysInterface.
- pub fn new_with_revoked(inner: InMemoryChannelKeys, revoked_commitment: Arc<Mutex<u64>>, disable_revocation_policy_check: bool) -> Self {
+ pub fn new_with_revoked(inner: InMemorySigner, revoked_commitment: Arc<Mutex<u64>>, disable_revocation_policy_check: bool) -> Self {
Self {
inner,
last_commitment_number: Arc::new(Mutex::new(None)),
}
}
-impl ChannelKeys for EnforcingChannelKeys {
+impl Sign for EnforcingSigner {
fn get_per_commitment_point<T: secp256k1::Signing + secp256k1::Verification>(&self, idx: u64, secp_ctx: &Secp256k1<T>) -> PublicKey {
self.inner.get_per_commitment_point(idx, secp_ctx)
}
}
-impl Writeable for EnforcingChannelKeys {
+impl Writeable for EnforcingSigner {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
self.inner.write(writer)?;
let last = *self.last_commitment_number.lock().unwrap();
}
}
-impl Readable for EnforcingChannelKeys {
+impl Readable for EnforcingSigner {
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let inner = Readable::read(reader)?;
let last_commitment_number = Readable::read(reader)?;
- Ok(EnforcingChannelKeys {
+ Ok(EnforcingSigner {
inner,
last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)),
}
}
-impl EnforcingChannelKeys {
+impl EnforcingSigner {
fn verify_counterparty_commitment_tx<'a, T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &'a CommitmentTransaction, secp_ctx: &Secp256k1<T>) -> TrustedCommitmentTransaction<'a> {
commitment_tx.verify(&self.inner.get_channel_parameters().as_counterparty_broadcastable(),
self.inner.counterparty_pubkeys(), self.inner.pubkeys(), secp_ctx)
use ln::features::{ChannelFeatures, InitFeatures};
use ln::msgs;
use ln::msgs::OptionalField;
-use util::enforcing_trait_impls::{EnforcingChannelKeys, INITIAL_REVOKED_COMMITMENT_NUMBER};
+use util::enforcing_trait_impls::{EnforcingSigner, INITIAL_REVOKED_COMMITMENT_NUMBER};
use util::events;
use util::logger::{Logger, Level, Record};
use util::ser::{Readable, ReadableArgs, Writer, Writeable};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::{cmp, mem};
use std::collections::{HashMap, HashSet};
-use chain::keysinterface::InMemoryChannelKeys;
+use chain::keysinterface::InMemorySigner;
pub struct TestVecWriter(pub Vec<u8>);
impl Writer for TestVecWriter {
pub struct OnlyReadsKeysInterface {}
impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
- type ChanKeySigner = EnforcingChannelKeys;
+ type Signer = EnforcingSigner;
fn get_node_secret(&self) -> SecretKey { unreachable!(); }
fn get_destination_script(&self) -> Script { unreachable!(); }
fn get_shutdown_pubkey(&self) -> PublicKey { unreachable!(); }
- fn get_channel_keys(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingChannelKeys { unreachable!(); }
+ fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
fn get_secure_random_bytes(&self) -> [u8; 32] { unreachable!(); }
- fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::ChanKeySigner, msgs::DecodeError> {
- EnforcingChannelKeys::read(&mut std::io::Cursor::new(reader))
+ fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
+ EnforcingSigner::read(&mut std::io::Cursor::new(reader))
}
}
pub struct TestChainMonitor<'a> {
- pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
+ pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64)>>,
- pub chain_monitor: chainmonitor::ChainMonitor<EnforcingChannelKeys, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a channelmonitor::Persist<EnforcingChannelKeys>>,
+ pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a channelmonitor::Persist<EnforcingSigner>>,
pub keys_manager: &'a TestKeysInterface,
pub update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
// If this is set to Some(), after the next return, we'll always return this until update_ret
pub next_update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
}
impl<'a> TestChainMonitor<'a> {
- pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a channelmonitor::Persist<EnforcingChannelKeys>, keys_manager: &'a TestKeysInterface) -> Self {
+ pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a channelmonitor::Persist<EnforcingSigner>, keys_manager: &'a TestKeysInterface) -> Self {
Self {
added_monitors: Mutex::new(Vec::new()),
latest_monitor_update_id: Mutex::new(HashMap::new()),
}
}
}
-impl<'a> chain::Watch for TestChainMonitor<'a> {
- type Keys = EnforcingChannelKeys;
-
- fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
+ fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
// At every point where we get a monitor update, we should be able to send a useful monitor
// to a watchtower and disk...
let mut w = TestVecWriter(Vec::new());
monitor.write(&mut w).unwrap();
- let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
assert!(new_monitor == monitor);
self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
let monitor = monitors.get(&funding_txo).unwrap();
w.0.clear();
monitor.write(&mut w).unwrap();
- let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
+ let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
&mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
assert!(new_monitor == *monitor);
self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
*self.update_ret.lock().unwrap() = ret;
}
}
-impl channelmonitor::Persist<EnforcingChannelKeys> for TestPersister {
- fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+impl channelmonitor::Persist<EnforcingSigner> for TestPersister {
+ fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
self.update_ret.lock().unwrap().clone()
}
- fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
+ fn update_persisted_channel(&self, _funding_txo: OutPoint, _update: &channelmonitor::ChannelMonitorUpdate, _data: &channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
self.update_ret.lock().unwrap().clone()
}
}
}
impl keysinterface::KeysInterface for TestKeysInterface {
- type ChanKeySigner = EnforcingChannelKeys;
+ type Signer = EnforcingSigner;
fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
- fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
- let keys = self.backing.get_channel_keys(inbound, channel_value_satoshis);
+ fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
+ let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
- EnforcingChannelKeys::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check)
+ EnforcingSigner::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check)
}
fn get_secure_random_bytes(&self) -> [u8; 32] {
self.backing.get_secure_random_bytes()
}
- fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::ChanKeySigner, msgs::DecodeError> {
+ fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
let mut reader = std::io::Cursor::new(buffer);
- let inner: InMemoryChannelKeys = Readable::read(&mut reader)?;
+ let inner: InMemorySigner = Readable::read(&mut reader)?;
let revoked_commitment = self.make_revoked_commitment_cell(inner.commitment_seed);
let last_commitment_number = Readable::read(&mut reader)?;
- Ok(EnforcingChannelKeys {
+ Ok(EnforcingSigner {
inner,
last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
revoked_commitment,
revoked_commitments: Mutex::new(HashMap::new()),
}
}
- pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingChannelKeys {
+ pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
let revoked_commitment = self.make_revoked_commitment_cell(keys.commitment_seed);
- EnforcingChannelKeys::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check)
+ EnforcingSigner::new_with_revoked(keys, revoked_commitment, self.disable_revocation_policy_check)
}
fn make_revoked_commitment_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<u64>> {