+ if for_local_storage {
+ writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
+ for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
+ writer.write_all(&payment_hash.0[..])?;
+ writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
+ }
+ } else {
+ writer.write_all(&byte_utils::be64_to_array(0))?;
+ }
+
+ macro_rules! serialize_local_tx {
+ ($local_tx: expr) => {
+ $local_tx.tx.write(writer)?;
+ writer.write_all(&$local_tx.revocation_key.serialize())?;
+ writer.write_all(&$local_tx.a_htlc_key.serialize())?;
+ writer.write_all(&$local_tx.b_htlc_key.serialize())?;
+ writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
+ writer.write_all(&$local_tx.per_commitment_point.serialize())?;
+
+ writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
+ writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
+ for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
+ serialize_htlc_in_commitment!(htlc_output);
+ if let &Some(ref their_sig) = sig {
+ 1u8.write(writer)?;
+ writer.write_all(&their_sig.serialize_compact())?;
+ } else {
+ 0u8.write(writer)?;
+ }
+ write_option!(htlc_source);
+ }
+ }
+ }
+
+ if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
+ writer.write_all(&[1; 1])?;
+ serialize_local_tx!(prev_local_tx);
+ } else {
+ writer.write_all(&[0; 1])?;
+ }
+
+ if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
+ writer.write_all(&[1; 1])?;
+ serialize_local_tx!(cur_local_tx);
+ } else {
+ writer.write_all(&[0; 1])?;
+ }
+
+ if for_local_storage {
+ writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
+ } else {
+ writer.write_all(&byte_utils::be48_to_array(0))?;
+ }
+
+ writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
+ for payment_preimage in self.payment_preimages.values() {
+ writer.write_all(&payment_preimage.0[..])?;
+ }
+
+ self.last_block_hash.write(writer)?;
+ self.destination_script.write(writer)?;
+ if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
+ writer.write_all(&[1; 1])?;
+ to_remote_script.write(writer)?;
+ local_key.write(writer)?;
+ } else {
+ writer.write_all(&[0; 1])?;
+ }
+
+ writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
+ for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
+ ancestor_claim_txid.write(writer)?;
+ claim_tx_data.write(writer)?;
+ }
+
+ writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
+ for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
+ outp.write(writer)?;
+ claim_and_height.0.write(writer)?;
+ claim_and_height.1.write(writer)?;
+ }
+
+ writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
+ for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
+ writer.write_all(&byte_utils::be32_to_array(**target))?;
+ writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
+ for ev in events.iter() {
+ match *ev {
+ OnchainEvent::Claim { ref claim_request } => {
+ writer.write_all(&[0; 1])?;
+ claim_request.write(writer)?;
+ },
+ OnchainEvent::HTLCUpdate { ref htlc_update } => {
+ writer.write_all(&[1; 1])?;
+ htlc_update.0.write(writer)?;
+ htlc_update.1.write(writer)?;
+ },
+ OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
+ writer.write_all(&[2; 1])?;
+ outpoint.write(writer)?;
+ input_material.write(writer)?;
+ }
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Writes this monitor into the given writer, suitable for writing to disk.
+ ///
+ /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
+ /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
+ /// the "reorg path" (ie not just starting at the same height but starting at the highest
+ /// common block that appears on your best chain as well as on the chain which contains the
+ /// last block hash returned) upon deserializing the object!
+ pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
+ self.write(writer, true)
+ }
+
+ /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
+ ///
+ /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
+ /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
+ /// the "reorg path" (ie not just starting at the same height but starting at the highest
+ /// common block that appears on your best chain as well as on the chain which contains the
+ /// last block hash returned) upon deserializing the object!
+ pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
+ self.write(writer, false)
+ }
+}
+
+impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
+ pub(super) fn new(keys: ChanSigner, funding_key: &SecretKey, revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor<ChanSigner> {
+ ChannelMonitor {
+ commitment_transaction_number_obscure_factor: 0,
+
+ key_storage: Storage::Local {
+ keys,
+ funding_key: funding_key.clone(),
+ revocation_base_key: revocation_base_key.clone(),
+ htlc_base_key: htlc_base_key.clone(),
+ delayed_payment_base_key: delayed_payment_base_key.clone(),
+ payment_base_key: payment_base_key.clone(),
+ shutdown_pubkey: shutdown_pubkey.clone(),
+ funding_info: None,
+ current_remote_commitment_txid: None,
+ prev_remote_commitment_txid: None,
+ },
+ their_htlc_base_key: None,
+ their_delayed_payment_base_key: None,
+ funding_redeemscript: None,
+ channel_value_satoshis: None,
+ their_cur_revocation_points: None,
+
+ our_to_self_delay: our_to_self_delay,
+ their_to_self_delay: None,
+
+ old_secrets: [([0; 32], 1 << 48); 49],
+ remote_claimable_outpoints: HashMap::new(),
+ remote_commitment_txn_on_chain: HashMap::new(),
+ remote_hash_commitment_number: HashMap::new(),
+
+ prev_local_signed_commitment_tx: None,
+ current_local_signed_commitment_tx: None,
+ current_remote_commitment_number: 1 << 48,
+
+ payment_preimages: HashMap::new(),
+ destination_script: destination_script,
+ to_remote_rescue: None,
+
+ pending_claim_requests: HashMap::new(),
+
+ claimable_outpoints: HashMap::new(),
+
+ onchain_events_waiting_threshold_conf: HashMap::new(),
+
+ last_block_hash: Default::default(),
+ secp_ctx: Secp256k1::new(),
+ logger,
+ }
+ }
+
+ fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
+ let mut tx_weight = 2; // count segwit flags
+ for inp in inputs {
+ // We use expected weight (and not actual) as signatures and time lock delays may vary
+ tx_weight += match inp {
+ // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
+ &InputDescriptors::RevokedOfferedHTLC => {
+ 1 + 1 + 73 + 1 + 33 + 1 + 133
+ },
+ // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
+ &InputDescriptors::RevokedReceivedHTLC => {
+ 1 + 1 + 73 + 1 + 33 + 1 + 139
+ },
+ // number_of_witness_elements + sig_length + remotehtlc_sig + preimage_length + preimage + witness_script_length + witness_script
+ &InputDescriptors::OfferedHTLC => {
+ 1 + 1 + 73 + 1 + 32 + 1 + 133
+ },
+ // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
+ &InputDescriptors::ReceivedHTLC => {
+ 1 + 1 + 73 + 1 + 1 + 1 + 139
+ },
+ // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
+ &InputDescriptors::RevokedOutput => {
+ 1 + 1 + 73 + 1 + 1 + 1 + 77
+ },
+ };
+ }
+ tx_weight
+ }
+
+ fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
+ if timelock_expiration <= current_height || timelock_expiration - current_height <= 3 {
+ return current_height + 1
+ } else if timelock_expiration - current_height <= 15 {
+ return current_height + 3
+ }
+ current_height + 15
+ }
+
+ #[inline]
+ fn place_secret(idx: u64) -> u8 {
+ for i in 0..48 {
+ if idx & (1 << i) == (1 << i) {
+ return i
+ }
+ }
+ 48
+ }
+
+ #[inline]
+ fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
+ let mut res: [u8; 32] = secret;
+ for i in 0..bits {
+ let bitpos = bits - 1 - i;
+ if idx & (1 << bitpos) == (1 << bitpos) {
+ res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
+ res = Sha256::hash(&res).into_inner();
+ }
+ }
+ res
+ }
+
+ /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
+ /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
+ /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
+ pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
+ let pos = ChannelMonitor::<ChanSigner>::place_secret(idx);
+ for i in 0..pos {
+ let (old_secret, old_idx) = self.old_secrets[i as usize];
+ if ChannelMonitor::<ChanSigner>::derive_secret(secret, pos, old_idx) != old_secret {
+ return Err(MonitorUpdateError("Previous secret did not match new one"));
+ }
+ }
+ if self.get_min_seen_secret() <= idx {
+ return Ok(());
+ }
+ self.old_secrets[pos as usize] = (secret, idx);
+
+ // Prune HTLCs from the previous remote commitment tx so we don't generate failure/fulfill
+ // events for now-revoked/fulfilled HTLCs.
+ // TODO: We should probably consider whether we're really getting the next secret here.
+ if let Storage::Local { ref mut prev_remote_commitment_txid, .. } = self.key_storage {
+ if let Some(txid) = prev_remote_commitment_txid.take() {
+ for &mut (_, ref mut source) in self.remote_claimable_outpoints.get_mut(&txid).unwrap() {
+ *source = None;