-
Notifications
You must be signed in to change notification settings - Fork 104
Add directory fallback behavior #1695
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,16 @@ | ||
| //! OHTTP relay selection and key bootstrapping for the payjoin-cli. | ||
| //! OHTTP relay and payjoin directory selection / key bootstrapping for the payjoin-cli. | ||
| //! | ||
| //! [`RelayManager`] tracks relays that have failed, excluding them from | ||
| //! future selections for the lifetime of the [`RelayManager`]. | ||
| //! [`MailroomManager`] tracks relays and directories that have failed, | ||
| //! excluding them from future selections for the lifetime of the [`MailroomManager`]. | ||
| //! | ||
| //! `unwrap_ohttp_keys_or_else_fetch` returns user-supplied keys when present, | ||
| //! otherwise selects a relay at random from the configured list, | ||
| //! excluding relays that [`RelayManager`] has marked as failed, | ||
| //! to avoid a fixed contact pattern at the network layer. | ||
| //! `unwrap_ohttp_keys_or_else_fetch_from_directory` returns user-supplied keys | ||
| //! when present, otherwise selects a relay at random from the configured list | ||
| //! (excluding failed relays) to fetch OHTTP keys from the given directory. | ||
| //! | ||
| //! `fetch_ohttp_keys_from_directory` retries on relay failures (e.g. connection | ||
| //! errors) by selecting another relay. Once a directory is chosen for a session | ||
| //! it must not change — the directory is embedded in the BIP21 URI at session | ||
| //! creation and recovered from the session event log on resume. | ||
| use std::sync::{Arc, Mutex}; | ||
|
|
||
| use anyhow::{anyhow, Result}; | ||
|
|
@@ -15,20 +19,33 @@ use payjoin::Url; | |
| use super::Config; | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub struct RelayManager { | ||
| pub struct MailroomManager { | ||
| config: Config, | ||
| failed_relays: Arc<Mutex<Vec<Url>>>, | ||
| failed_directories: Arc<Mutex<Vec<Url>>>, | ||
| } | ||
|
|
||
| impl RelayManager { | ||
| impl MailroomManager { | ||
|
DanGould marked this conversation as resolved.
|
||
| pub fn new(config: Config) -> Self { | ||
| RelayManager { config, failed_relays: Arc::new(Mutex::new(Vec::new())) } | ||
| MailroomManager { | ||
| config, | ||
| failed_relays: Arc::new(Mutex::new(Vec::new())), | ||
| failed_directories: Arc::new(Mutex::new(Vec::new())), | ||
| } | ||
| } | ||
|
|
||
| pub fn add_failed_relay(&self, relay: Url) { | ||
| self.failed_relays.lock().expect("Lock should not be poisoned").push(relay); | ||
| } | ||
|
|
||
| pub fn clear_failed_relays(&self) { | ||
| self.failed_relays.lock().expect("Lock should not be poisoned").clear(); | ||
| } | ||
|
|
||
| pub fn add_failed_directory(&self, directory: Url) { | ||
| self.failed_directories.lock().expect("Lock should not be poisoned").push(directory); | ||
| } | ||
|
|
||
| pub fn choose_relay(&self) -> Result<Url> { | ||
| use payjoin::bitcoin::secp256k1::rand::prelude::SliceRandom; | ||
| let relays = &self.config.v2()?.ohttp_relays; | ||
|
|
@@ -46,16 +63,35 @@ impl RelayManager { | |
| .ok_or_else(|| anyhow!("Failed to select from remaining relays")) | ||
| } | ||
|
|
||
| pub(crate) async fn unwrap_ohttp_keys_or_else_fetch(&self) -> Result<ValidatedOhttpKeys> { | ||
| pub fn choose_directory(&self) -> Result<Url> { | ||
| use payjoin::bitcoin::secp256k1::rand::prelude::SliceRandom; | ||
| let directories = &self.config.v2()?.pj_directories; | ||
| let failed_directories = | ||
| self.failed_directories.lock().expect("Lock should not be poisoned"); | ||
| let remaining_directories: Vec<_> = | ||
| directories.iter().filter(|d| !failed_directories.contains(d)).cloned().collect(); | ||
|
|
||
| if remaining_directories.is_empty() { | ||
| return Err(anyhow!("No valid directories available")); | ||
| } | ||
|
|
||
| remaining_directories | ||
| .choose(&mut payjoin::bitcoin::key::rand::thread_rng()) | ||
| .cloned() | ||
| .ok_or_else(|| anyhow!("Failed to select from remaining directories")) | ||
| } | ||
|
Comment on lines
+66
to
+82
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. NBD, I duplicate first as well, just noticing: could be DRY'd up with the choose_relay function |
||
|
|
||
| pub(crate) async fn unwrap_ohttp_keys_or_else_fetch_from_directory( | ||
| &self, | ||
| directory: &Url, | ||
| ) -> Result<ValidatedOhttpKeys> { | ||
| if let Some(ohttp_keys) = self.config.v2()?.ohttp_keys.clone() { | ||
| return Ok(ValidatedOhttpKeys { ohttp_keys }); | ||
| } | ||
| self.fetch_ohttp_keys().await | ||
| self.fetch_ohttp_keys_from_directory(directory).await | ||
| } | ||
|
|
||
| async fn fetch_ohttp_keys(&self) -> Result<ValidatedOhttpKeys> { | ||
| let payjoin_directory = &self.config.v2()?.pj_directory; | ||
|
|
||
| async fn fetch_ohttp_keys_from_directory(&self, directory: &Url) -> Result<ValidatedOhttpKeys> { | ||
| loop { | ||
| let selected_relay = self.choose_relay()?; | ||
|
|
||
|
|
@@ -66,27 +102,27 @@ impl RelayManager { | |
| let cert_der = std::fs::read(cert_path)?; | ||
| payjoin::io::fetch_ohttp_keys_with_cert( | ||
| selected_relay.as_str(), | ||
| payjoin_directory.as_str(), | ||
| directory.as_str(), | ||
| &cert_der, | ||
| ) | ||
| .await | ||
| } else { | ||
| payjoin::io::fetch_ohttp_keys( | ||
| selected_relay.as_str(), | ||
| payjoin_directory.as_str(), | ||
| ) | ||
| .await | ||
| payjoin::io::fetch_ohttp_keys(selected_relay.as_str(), directory.as_str()) | ||
| .await | ||
| } | ||
| } | ||
| #[cfg(not(feature = "_manual-tls"))] | ||
| payjoin::io::fetch_ohttp_keys(selected_relay.as_str(), payjoin_directory.as_str()) | ||
| .await | ||
| payjoin::io::fetch_ohttp_keys(selected_relay.as_str(), directory.as_str()).await | ||
| }; | ||
|
|
||
| match ohttp_keys { | ||
| Ok(keys) => return Ok(ValidatedOhttpKeys { ohttp_keys: keys }), | ||
| Err(payjoin::io::Error::UnexpectedStatusCode(e)) => { | ||
| return Err(payjoin::io::Error::UnexpectedStatusCode(e).into()); | ||
| tracing::debug!( | ||
| "Directory {directory} returned unexpected status via relay {selected_relay}: {e:?}" | ||
| ); | ||
| self.add_failed_directory(directory.clone()); | ||
| return Err(anyhow!("Directory {directory} returned unexpected status: {e}")); | ||
| } | ||
| Err(e) => { | ||
| tracing::debug!("Failed to connect to relay: {selected_relay}, {e:?}"); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Really seems like a function deserving its own documentation. A good time to refactor this ~tech debt out would be #1035.
I had to check, but it looks like this will fail if all directories do when
choose_directory()?throws, I think. Originally I was concerned this might loop forever, but it looks like it will close.