author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
20,244
05.04.2019 15:34:27
14,400
06e0438c1fa62c72b06b6c6a4cf2fa237bc1a69e
Update for early beta 4
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -155,7 +155,7 @@ dependencies = [\nname = \"althea_rs\"\nversion = \"0.1.10\"\ndependencies = [\n- \"rita 0.3.17\",\n+ \"rita 0.3.18\",\n]\n[[package]]\n@@ -2014,7 +2014,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.3.17\"\n+version = \"0.3.18\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "[package]\nname = \"rita\"\n-version = \"0.3.17\"\n+version = \"0.3.18\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/own_info.rs", "new_path": "rita/src/rita_common/dashboard/own_info.rs", "diff": "@@ -6,7 +6,7 @@ use clarity::Address;\nuse failure::Error;\nuse num256::{Int256, Uint256};\n-pub static READABLE_VERSION: &str = \"Beta 3 RC9\";\n+pub static READABLE_VERSION: &str = \"Beta 4 RC1\";\n#[derive(Serialize)]\npub struct OwnInfo {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Update for early beta 4
20,244
08.04.2019 06:51:02
14,400
712d3f4f20a8e6eee725b3faad806f46b3d2be7e
Up base value for exit bandwidth class This change seems to mostly have had the affect of limiting everyone to 100mbps but not really much effect on getting users there.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -497,9 +497,9 @@ pub fn enforce_exit_clients(\n&ip,\n)\n} else {\n- // set to 100mbps garunteed bandwidth and 1gbps\n+ // set to 500mbps garunteed bandwidth and 1gbps\n// absolute max\n- KI.set_class_limit(\"wg_exit\", 100_000, 1_000_000, &ip)\n+ KI.set_class_limit(\"wg_exit\", 500_000, 1_000_000, &ip)\n};\nif res.is_err() {\npanic!(\"Failed to limit {} with {:?}\", ip, res);\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Up base value for exit bandwidth class This change seems to mostly have had the affect of limiting everyone to 100mbps but not really much effect on getting users there.
20,244
09.04.2019 09:06:13
14,400
92cde3b94b7f616e713a2b7435cdb64c45a2f902
Oracalize low balance warnings
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/oracle/mod.rs", "new_path": "rita/src/rita_common/oracle/mod.rs", "diff": "@@ -257,6 +257,7 @@ struct PriceUpdate {\nclient: u32,\ngateway: u32,\nmax: u32,\n+ warning: u128,\n}\n/// This is a very simple and early version of an automated pricing system\n@@ -300,6 +301,8 @@ fn update_our_price() {\npayment.local_fee = new_prices.client;\n}\npayment.max_fee = new_prices.max;\n+ payment.balance_warning_level =\n+ new_prices.warning.into();\ntrace!(\"Successfully updated prices\");\n}\n@@ -329,9 +332,9 @@ fn update_our_price() {\n/// A very simple function placed here for convinence that indicates\n/// if the system should go into low balance mode\npub fn low_balance() -> bool {\n- let balance = SETTING.get_payment().balance.clone();\n- // TODO this needs to be configured/oracalized\n- const THRESHOLD: u128 = 10_000_000_000_000_000;\n+ let payment_settings = SETTING.get_payment();\n+ let balance = payment_settings.balance.clone();\n+ let balance_warning_level = payment_settings.balance_warning_level.clone();\n- balance < THRESHOLD.into()\n+ balance < balance_warning_level\n}\n" }, { "change_type": "MODIFY", "old_path": "settings/src/payment.rs", "new_path": "settings/src/payment.rs", "diff": "@@ -34,6 +34,10 @@ fn default_price_oracle() -> bool {\ntrue\n}\n+fn default_balance_warning_level() -> Uint256 {\n+ (10_000_000_000_000_000u64).into()\n+}\n+\nfn default_oracle_url() -> String {\n\"https://updates.altheamesh.com/prices\".to_string()\n}\n@@ -75,6 +79,9 @@ pub struct PaymentSettings {\n/// The amount of 'grace' to give a long term neighbor\n#[serde(default = \"default_close_fraction\")]\npub close_fraction: Int256,\n+ /// The level of balance which will trigger a warning\n+ #[serde(default = \"default_balance_warning_level\")]\n+ pub balance_warning_level: Uint256,\n/// The amount of billing cycles a node can fall behind without being subjected to the threshold\npub buffer_period: u32,\n/// Our own eth private key we do not store address, instead it is derived from here\n@@ -115,6 +122,7 @@ impl Default for PaymentSettings {\n// computed as 10x the pay threshold\nclose_threshold: (-8_400_000_000_000_000i64).into(),\nclose_fraction: 100.into(),\n+ balance_warning_level: (10_000_000_000_000_000u64).into(),\nbuffer_period: 3,\neth_private_key: None,\neth_address: None,\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Oracalize low balance warnings
20,244
09.04.2019 07:43:33
14,400
258a73f08d7c6c648ef1b842dd97a306eac305ab
Fix typo in debtkeeper module comment
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/debt_keeper/mod.rs", "new_path": "rita/src/rita_common/debt_keeper/mod.rs", "diff": "//! While traffic watcher keeps an eye on how much traffic flows and what that is worth debtkeeper\n-//! maintains the long term memory of who owes whow what so that it may later be quiered and paid\n+//! maintains the long term memory of who owes who what so that it may later be quiered and paid\n//! by payment manager in the current implementation or guac in the more final one\n//!\n//! You may be wondering what's up with debt buffers actions and incoming payments, why can't we\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Fix typo in debtkeeper module comment
20,244
16.04.2019 07:30:46
14,400
e4f01735b1a94a07d2ec3229893df5dc67ae4bad
Remove exit discount Shouldn't be needed anymore
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "@@ -325,12 +325,9 @@ pub fn watch<T: Read + Write>(\nlet mut traffic_vec = Vec::new();\nfor (from, amount) in debts {\n- // Provides a 10% discount to encourage convergence\n- let discounted_amount = ((amount as f64) * 0.95) as i128;\n- trace!(\"discounted {} to {}\", amount, discounted_amount);\ntraffic_vec.push(Traffic {\nfrom: from,\n- amount: discounted_amount.into(),\n+ amount: amount.into(),\n})\n}\nlet update = debt_keeper::TrafficUpdate {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Remove exit discount Shouldn't be needed anymore
20,244
16.04.2019 07:50:12
14,400
1553a98e7f2dc6c7f14ee6c5fdba73f8cdc8f379
Fix some nits in rita_exit
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/geoip.rs", "new_path": "rita/src/rita_exit/database/geoip.rs", "diff": "@@ -55,7 +55,7 @@ pub fn get_gateway_ip_bulk(mesh_ip_list: Vec<IpAddr>) -> Result<Vec<IpPair>, Err\nif ip.prefix() == 128 && route.installed && IpAddr::V6(ip.ip()) == mesh_ip {\nmatch KI.get_wg_remote_ip(&route.iface) {\nOk(remote_ip) => results.push(IpPair {\n- mesh_ip: mesh_ip,\n+ mesh_ip,\ngateway_ip: remote_ip,\n}),\nErr(e) => error!(\"Failure looking up remote ip {:?}\", e),\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/sms.rs", "new_path": "rita/src/rita_exit/database/sms.rs", "diff": "@@ -30,7 +30,7 @@ fn check_text(number: String, code: String, api_key: String) -> Result<bool, Err\nlet res = client\n.get(\"https://api.authy.com/protected/json/phones/verification/check\")\n.form(&SmsCheck {\n- api_key: api_key,\n+ api_key,\nverification_code: code,\nphone_number: number.national().to_string(),\ncountry_code: number.code().value().to_string(),\n@@ -57,7 +57,7 @@ fn send_text(number: String, api_key: String) -> Result<(), Error> {\nlet res = client\n.post(\"https://api.authy.com/protected/json/phones/verification/start\")\n.form(&SmsRequest {\n- api_key: api_key,\n+ api_key,\nvia: \"sms\".to_string(),\nphone_number: number.national().to_string(),\ncountry_code: number.code().value().to_string(),\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "//!\n//! Also handles enforcement of nonpayment, since there's no need for a complicated TunnelManager for exits\n-use ::actix::prelude::*;\n-use althea_types::WgKey;\n-\n-use althea_kernel_interface::wg_iface_counter::WgUsage;\n-use althea_kernel_interface::KI;\n-\n-use althea_types::Identity;\n-\n-use babel_monitor::Babel;\n-\nuse crate::rita_common::debt_keeper;\nuse crate::rita_common::debt_keeper::DebtKeeper;\nuse crate::rita_common::debt_keeper::Traffic;\n-\nuse crate::rita_exit::rita_loop::EXIT_LOOP_SPEED;\n-\n-use std::collections::HashMap;\n-use std::io::{Read, Write};\n-use std::net::{IpAddr, SocketAddr, TcpStream};\n-\n-use ipnetwork::IpNetwork;\n-\nuse crate::SETTING;\n+use ::actix::prelude::{Actor, Context, Handler, Message, Supervised, SystemService};\n+use althea_kernel_interface::wg_iface_counter::WgUsage;\n+use althea_kernel_interface::KI;\n+use althea_types::Identity;\n+use althea_types::WgKey;\n+use babel_monitor::Babel;\n+use ipnetwork::IpNetwork;\nuse settings::exit::RitaExitSettings;\nuse settings::RitaCommonSettings;\n+use std::collections::HashMap;\n+use std::io::{Read, Write};\n+use std::net::{IpAddr, SocketAddr, TcpStream};\n+use std::time::Duration;\n+use std::time::Instant;\nuse failure::Error;\npub struct TrafficWatcher {\n+ last_run: Instant,\nlast_seen_bytes: HashMap<WgKey, WgUsage>,\n}\n@@ -59,6 +54,7 @@ impl SystemService for TrafficWatcher {\nimpl Default for TrafficWatcher {\nfn default() -> TrafficWatcher {\nTrafficWatcher {\n+ last_run: Instant::now(),\nlast_seen_bytes: HashMap::new(),\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Fix some nits in rita_exit
20,244
16.04.2019 09:26:25
14,400
ddcf4b8e2983d7e78e7c8c1f0c22f3cd243e3f19
Clean up for Client traffic watcher fprtt was computed and generally not being used awkwardly in the middle of the client billing, that's been lifted out into it's own function in rita_loop as well as the route finding operation.
[ { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "@@ -442,6 +442,29 @@ impl<T: Read + Write> Babel<T> {\n}\nOk(false)\n}\n+\n+ /// Returns the installed route to a given destination\n+ pub fn get_installed_route(\n+ &mut self,\n+ mesh_ip: &IpAddr,\n+ routes: &VecDeque<Route>,\n+ ) -> Result<Route, Error> {\n+ let mut exit_route = None;\n+ for route in routes.iter() {\n+ // Only ip6\n+ if let IpNetwork::V6(ref ip) = route.prefix {\n+ // Only host addresses and installed routes\n+ if ip.prefix() == 128 && route.installed && IpAddr::V6(ip.ip()) == *mesh_ip {\n+ exit_route = Some(route);\n+ break;\n+ }\n+ }\n+ }\n+ if exit_route.is_none() {\n+ bail!(\"No installed route to that destination!\");\n+ }\n+ Ok(exit_route.unwrap().clone())\n+ }\n}\n#[cfg(test)]\nmod tests {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/rita_loop/mod.rs", "new_path": "rita/src/rita_client/rita_loop/mod.rs", "diff": "//! This loop manages exit signup based on the settings configuration state and deploys an exit vpn\n//! tunnel if the signup was successful on the selected exit.\n-use std::time::{Duration, Instant};\n-\n+use crate::rita_client::exit_manager::ExitManager;\n+use crate::SETTING;\nuse actix::{\nActor, ActorContext, Addr, Arbiter, AsyncContext, Context, Handler, Message, Supervised,\nSystemService,\n};\n-use futures::future::Future;\n-\n-use crate::rita_client::exit_manager::ExitManager;\n-\n+use althea_types::RTTimestamps;\nuse failure::Error;\n+use futures::future::Future;\n+use reqwest;\n+use settings::client::RitaClientSettings;\n+use std::time::{Duration, Instant};\n#[derive(Default)]\npub struct RitaLoop;\n@@ -80,3 +81,39 @@ impl Handler<Tick> for RitaLoop {\nOk(())\n}\n}\n+\n+pub fn _compute_verification_rtt() -> Result<RTTimestamps, Error> {\n+ let exit = match SETTING.get_exit_client().get_current_exit() {\n+ Some(current_exit) => current_exit.clone(),\n+ None => {\n+ return Err(format_err!(\n+ \"No current exit even though an exit route is present\"\n+ ));\n+ }\n+ };\n+\n+ let client = reqwest::Client::builder()\n+ .timeout(Duration::from_secs(1))\n+ .build()?;\n+\n+ let timestamps: RTTimestamps = client\n+ .get(&format!(\n+ \"http://[{}]:{}/rtt\",\n+ exit.id.mesh_ip, exit.registration_port\n+ ))\n+ .send()?\n+ .json()?;\n+\n+ let exit_rx = timestamps.exit_rx;\n+ let exit_tx = timestamps.exit_tx;\n+ let client_tx = Instant::now();\n+ let client_rx = Instant::now();\n+\n+ let inner_rtt = client_rx.duration_since(client_tx) - exit_tx.duration_since(exit_rx)?;\n+ let inner_rtt_millis =\n+ inner_rtt.as_secs() as f32 * 1000.0 + inner_rtt.subsec_nanos() as f32 / 1_000_000.0;\n+ // secs -> millis nanos -> millis\n+\n+ info!(\"Computed RTTs: inner {}ms\", inner_rtt_millis);\n+ Ok(timestamps)\n+}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/traffic_watcher/mod.rs", "new_path": "rita/src/rita_client/traffic_watcher/mod.rs", "diff": "//! different in that mesh nodes are paid by forwarding traffic, but exits have to return traffic and\n//! must get paid for doing so.\n-use ::actix::prelude::*;\n-use failure::Error;\n-use ipnetwork::IpNetwork;\n-use reqwest;\n-\n-use std::io::{Read, Write};\n-use std::net::{IpAddr, SocketAddr, TcpStream};\n-use std::time::{Duration, SystemTime};\n-\nuse crate::rita_client::rita_loop::CLIENT_LOOP_SPEED;\nuse crate::rita_common::debt_keeper::{DebtKeeper, Traffic, TrafficUpdate};\nuse crate::KI;\nuse crate::SETTING;\n-use althea_types::{Identity, RTTimestamps};\n+use ::actix::prelude::{Actor, Context, Handler, Message, Supervised, SystemService};\n+use althea_types::Identity;\nuse babel_monitor::Babel;\n-use settings::client::RitaClientSettings;\n+use babel_monitor::Route;\n+use failure::Error;\nuse settings::RitaCommonSettings;\n+use std::net::{IpAddr, SocketAddr, TcpStream};\n+\n+/// Returns the babel route to a given mesh ip with the properly capped price\n+fn find_exit_route_capped(exit_mesh_ip: IpAddr) -> Result<Route, Error> {\n+ let stream = TcpStream::connect::<SocketAddr>(\n+ format!(\"[::1]:{}\", SETTING.get_network().babel_port).parse()?,\n+ )?;\n+ let mut babel = Babel::new(stream);\n+\n+ babel.start_connection()?;\n+ trace!(\"Getting routes\");\n+ let routes = babel.parse_routes()?;\n+ trace!(\"Got routes: {:?}\", routes);\n+\n+ let max_fee = SETTING.get_payment().max_fee;\n+ let mut exit_route = babel.get_installed_route(&exit_mesh_ip, &routes)?;\n+ if exit_route.price > max_fee {\n+ let mut capped_route = exit_route.clone();\n+ capped_route.price = max_fee;\n+ exit_route = capped_route;\n+ }\n+ Ok(exit_route)\n+}\npub struct TrafficWatcher {\nlast_read_input: u64,\n@@ -62,56 +78,18 @@ impl Handler<Watch> for TrafficWatcher {\ntype Result = Result<(), Error>;\nfn handle(&mut self, msg: Watch, _: &mut Context<Self>) -> Self::Result {\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port).parse()?,\n- )?;\n-\n- watch(self, Babel::new(stream), &msg.exit_id, msg.exit_price)\n+ watch(self, &msg.exit_id, msg.exit_price)\n}\n}\n/// This traffic watcher watches how much traffic we send to the exit, and how much the exit sends\n/// back to us.\n-pub fn watch<T: Read + Write>(\n- history: &mut TrafficWatcher,\n- mut babel: Babel<T>,\n- exit: &Identity,\n- exit_price: u64,\n-) -> Result<(), Error> {\n+pub fn watch(history: &mut TrafficWatcher, exit: &Identity, exit_price: u64) -> Result<(), Error> {\n// the number of bytes provided under the free tier, (kbps * seconds) * 125 = bytes\nlet free_tier_threshold: u64 =\nu64::from(SETTING.get_payment().free_tier_throughput) * CLIENT_LOOP_SPEED * 125u64;\n- babel.start_connection()?;\n-\n- trace!(\"Getting routes\");\n- let routes = babel.parse_routes()?;\n- trace!(\"Got routes: {:?}\", routes);\n- let babel_neighs = babel.parse_neighs()?;\n- trace!(\"Got neighs: {:?}\", babel_neighs);\n-\n- let max_fee = SETTING.get_payment().max_fee;\n- let mut exit_route = None;\n- for route in routes.iter() {\n- // Only ip6\n- if let IpNetwork::V6(ref ip) = route.prefix {\n- // Only host addresses and installed routes\n- if ip.prefix() == 128 && route.installed && IpAddr::V6(ip.ip()) == exit.mesh_ip {\n- if route.price > max_fee {\n- let mut capped_route = route.clone();\n- capped_route.price = max_fee;\n- exit_route = Some(capped_route);\n- } else {\n- exit_route = Some(route.clone());\n- }\n- break;\n- }\n- }\n- }\n- if exit_route.is_none() {\n- bail!(\"No route to exit, therefore we can't be sending traffic to it\");\n- }\n- let exit_route = exit_route.unwrap();\n+ let exit_route = find_exit_route_capped(exit.mesh_ip)?;\nlet counter = match KI.read_wg_counters(\"wg_exit\") {\nOk(res) => {\n@@ -154,42 +132,11 @@ pub fn watch<T: Read + Write>(\n// the price we pay to send traffic through the exit\ninfo!(\"exit price {}\", exit_price);\n- let client = reqwest::Client::builder()\n- .timeout(Duration::from_secs(5))\n- .build()?;\n-\n// price to get traffic to the exit as a u64 to make the type rules for math easy\nlet exit_route_price: i128 = exit_route.price.into();\n// the total price for the exit returning traffic to us, in the future we should ask\n// the exit for this because TODO assumes symetric route\nlet exit_dest_price: i128 = exit_route_price + i128::from(exit_price);\n- let client_tx = SystemTime::now();\n- let RTTimestamps { exit_rx, exit_tx } = client\n- .get(&format!(\n- \"http://[{}]:{}/rtt\",\n- exit.mesh_ip,\n- match SETTING.get_exit_client().get_current_exit() {\n- Some(current_exit) => current_exit.registration_port,\n- None => {\n- return Err(format_err!(\n- \"No current exit even though an exit route is present\"\n- ));\n- }\n- }\n- ))\n- .send()?\n- .json()?;\n- let client_rx = SystemTime::now();\n-\n- let inner_rtt = client_rx.duration_since(client_tx)? - exit_tx.duration_since(exit_rx)?;\n- let inner_rtt_millis =\n- inner_rtt.as_secs() as f32 * 1000.0 + inner_rtt.subsec_nanos() as f32 / 1_000_000.0;\n- // secs -> millis nanos -> millis\n-\n- info!(\n- \"RTTs: per-hop {}ms, inner {}ms\",\n- exit_route.full_path_rtt, inner_rtt_millis\n- );\ninfo!(\"Exit destination price {}\", exit_dest_price);\ntrace!(\"Exit ip: {:?}\", exit.mesh_ip);\n@@ -232,36 +179,3 @@ pub fn watch<T: Read + Write>(\nOk(())\n}\n-\n-#[cfg(test)]\n-mod tests {\n- use env_logger;\n-\n- use super::*;\n- use althea_types::WgKey;\n- use arrayvec::ArrayString;\n- use clarity::Address;\n- use std::str::FromStr;\n-\n- #[test]\n- #[ignore]\n- fn debug_babel_socket_client() {\n- env_logger::init();\n- let bm_stream = TcpStream::connect::<SocketAddr>(\"[::1]:9001\".parse().unwrap()).unwrap();\n- watch(\n- &mut TrafficWatcher {\n- last_read_input: 0u64,\n- last_read_output: 0u64,\n- },\n- Babel::new(bm_stream),\n- &Identity::new(\n- \"0.0.0.0\".parse().unwrap(),\n- Address::from_str(\"abababababababababab\").unwrap(),\n- WgKey::from_str(\"abc0abc1abc2abc3abc4abc5abc6abc7abc8abc=\").unwrap(),\n- Some(ArrayString::<[u8; 32]>::new()),\n- ),\n- 5,\n- )\n- .unwrap();\n- }\n-}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Clean up for Client traffic watcher fprtt was computed and generally not being used awkwardly in the middle of the client billing, that's been lifted out into it's own function in rita_loop as well as the route finding operation.
20,244
16.04.2019 12:00:55
14,400
6c782a294c7f9f5c4685b9f825d7fcd25f3fe329
Remove local throttling stuff We've decided to drop the feature for now
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/exit_manager/mod.rs", "new_path": "rita/src/rita_client/exit_manager/mod.rs", "diff": "@@ -421,18 +421,6 @@ impl Handler<Tick> for ExitManager {\n}\n}\n- // Self limit bandwidth consumption if we have a low balance\n- // let free_tier_throughput = SETTING.get_payment().free_tier_throughput;\n- // if self.last_exit.is_some() && low_balance() && !self.local_limiting {\n- // warn!(\"Balance is low! sending notification and limiting usage\");\n- // let _ = KI.set_classless_limit(\"wg_exit\", free_tier_throughput);\n- // self.local_limiting = true;\n- // } else if self.last_exit.is_some() && !low_balance() && self.local_limiting {\n- // info!(\"Balance is above the payment level, removing local limits\");\n- // let _ = KI.delete_qdisc(\"wg_exit\");\n- // self.local_limiting = false;\n- // }\n-\n// code that manages requesting details to exits\nlet servers = { SETTING.get_exits().clone() };\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Remove local throttling stuff We've decided to drop the feature for now
20,244
16.04.2019 16:52:29
14,400
93371331884cb4109cd1ffd8d7ab2b9d13900a56
Add comment about trust dns actor kill
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/mod.rs", "new_path": "rita/src/rita_common/rita_loop/mod.rs", "diff": "@@ -208,7 +208,6 @@ impl Handler<Tick> for RitaLoop {\n}\n/// Manages gateway functionaltiy and maintains the was_gateway parameter\n-/// for Rita loop\nfn manage_gateway(mut was_gateway: bool) -> bool {\n// Resolves the gateway client corner case\n// Background info here https://forum.altheamesh.com/t/the-gateway-client-corner-case/35\n@@ -220,15 +219,15 @@ fn manage_gateway(mut was_gateway: bool) -> bool {\nNone => false,\n};\n- trace!(\"We are a Gateway: {}\", gateway);\n+ info!(\"We are a Gateway: {}\", gateway);\nSETTING.get_network_mut().is_gateway = gateway;\nif SETTING.get_network().is_gateway {\nif was_gateway {\n+ // trust_dns will fail to resolve if you plugin the wan port after Rita has started\n+ // this may be fixed in a future update of Trustdns\nlet resolver_addr: Addr<ResolverWrapper> = System::current().registry().get();\nresolver_addr.do_send(KillActor);\n-\n- was_gateway = true\n}\nmatch KI.get_resolv_servers() {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add comment about trust dns actor kill
20,244
17.04.2019 13:13:15
14,400
c2221bc92326966894147d48196504b5114b88cd
Breaking version update for billing changes Older versions will not bill interoperably so this is a breaking change
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -155,7 +155,7 @@ dependencies = [\nname = \"althea_rs\"\nversion = \"0.1.10\"\ndependencies = [\n- \"rita 0.3.18\",\n+ \"rita 0.4.0\",\n]\n[[package]]\n@@ -2014,7 +2014,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.3.18\"\n+version = \"0.4.0\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "[package]\nname = \"rita\"\n-version = \"0.3.18\"\n+version = \"0.4.0\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/own_info.rs", "new_path": "rita/src/rita_common/dashboard/own_info.rs", "diff": "@@ -6,7 +6,7 @@ use clarity::Address;\nuse failure::Error;\nuse num256::{Int256, Uint256};\n-pub static READABLE_VERSION: &str = \"Beta 4 RC1\";\n+pub static READABLE_VERSION: &str = \"Beta 4 RC2\";\n#[derive(Serialize)]\npub struct OwnInfo {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Breaking version update for billing changes Older versions will not bill interoperably so this is a breaking change
20,244
19.04.2019 09:51:39
14,400
fcf3eddc97e73c554f87bfa0c23d96ec38c421eb
Timeout for peer dns resolution This was causing the entire actor system to block waiting for DNS resolution
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "//! up tunnels if they respond, likewise if someone calls us their hello goes through network_endpoints\n//! then into TunnelManager to open a tunnel for them.\n-use std::collections::HashMap;\n-use std::net::{IpAddr, SocketAddr, TcpStream};\n-use std::path::Path;\n-use std::time::{Duration, Instant};\n-\n-use ::actix::actors::resolver;\n-use ::actix::prelude::*;\n-\n-use futures::Future;\n-\n-use althea_types::Identity;\n-use althea_types::LocalIdentity;\n-\n-use crate::KI;\n-\n-use babel_monitor::Babel;\n-\nuse crate::rita_common;\nuse crate::rita_common::hello_handler::Hello;\nuse crate::rita_common::peer_listener::Peer;\n-\n+use crate::KI;\nuse crate::SETTING;\n-use settings::RitaCommonSettings;\n-\n-use failure::Error;\n-\n#[cfg(test)]\nuse ::actix::actors::mocker::Mocker;\n+use ::actix::actors::resolver;\n+use ::actix::prelude::{Actor, Arbiter, Context, Handler, Message, Supervised, SystemService};\n+use althea_types::Identity;\n+use althea_types::LocalIdentity;\n+use babel_monitor::Babel;\n+use failure::Error;\n+use futures::Future;\n+use settings::RitaCommonSettings;\n+use std::collections::HashMap;\nuse std::fmt;\nuse std::io::{Read, Write};\n-\n+use std::net::{IpAddr, SocketAddr, TcpStream};\n+use std::path::Path;\n+use std::time::{Duration, Instant};\n#[cfg(test)]\ntype HelloHandler = Mocker<rita_common::hello_handler::HelloHandler>;\n-\n#[cfg(not(test))]\ntype HelloHandler = rita_common::hello_handler::HelloHandler;\n-\n#[cfg(test)]\ntype Resolver = Mocker<resolver::Resolver>;\n-\n#[cfg(not(test))]\ntype Resolver = resolver::Resolver;\n@@ -600,6 +587,7 @@ impl TunnelManager {\nlet res = Resolver::from_registry()\n.send(resolver::Resolve::host(their_hostname.clone()))\n+ .timeout(Duration::from_secs(1))\n.then(move |res| match res {\nOk(Ok(dnsresult)) => {\nlet port = SETTING.get_network().rita_hello_port;\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Timeout for peer dns resolution This was causing the entire actor system to block waiting for DNS resolution
20,244
19.04.2019 12:26:59
14,400
6bf2407bf6ad803c98650daa73b8506113f57a69
Add timeouts to all major arbiter spawns
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/exit_manager/mod.rs", "new_path": "rita/src/rita_client/exit_manager/mod.rs", "diff": "@@ -408,6 +408,7 @@ impl Handler<Tick> for ExitManager {\nexit_id,\nexit_price,\n})\n+ .timeout(Duration::from_secs(4))\n.then(|res| match res {\nOk(val) => Ok(val),\nErr(e) => {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/rita_loop/mod.rs", "new_path": "rita/src/rita_client/rita_loop/mod.rs", "diff": "@@ -68,10 +68,15 @@ impl Handler<Tick> for RitaLoop {\nlet start = Instant::now();\ntrace!(\"Client Tick!\");\n- Arbiter::spawn(ExitManager::from_registry().send(Tick {}).then(|res| {\n+ Arbiter::spawn(\n+ ExitManager::from_registry()\n+ .send(Tick {})\n+ .timeout(Duration::from_secs(4))\n+ .then(|res| {\ntrace!(\"exit manager said {:?}\", res);\nOk(())\n- }));\n+ }),\n+ );\ninfo!(\n\"Rita Client loop completed in {}s {}ms\",\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "//! so long as we have not published it to a full node, once the payment is on\n//! the blockchain it's up to the reciever to validate that it's correct\n-use ::actix::prelude::*;\n+use crate::rita_common::debt_keeper;\n+use crate::rita_common::debt_keeper::DebtKeeper;\n+use crate::rita_common::debt_keeper::PaymentFailed;\n+use crate::rita_common::rita_loop::get_web3_server;\n+use crate::SETTING;\n+use ::actix::prelude::{Actor, Arbiter, Context, Handler, Message, Supervised, SystemService};\nuse ::actix_web::client;\nuse ::actix_web::client::Connection;\n-\n+use althea_types::PaymentTx;\n+use clarity::Transaction;\n+use failure::Error;\nuse futures::future::Either;\nuse futures::{future, Future};\n-\n+use settings::RitaCommonSettings;\nuse std::net::SocketAddr;\n-\n+use std::time::Duration;\nuse tokio::net::TcpStream as TokioTcpStream;\n-\n-use althea_types::PaymentTx;\n-\n-use clarity::Transaction;\n-\n-use crate::SETTING;\n-use settings::RitaCommonSettings;\n-\n-use crate::rita_common::debt_keeper;\n-use crate::rita_common::debt_keeper::DebtKeeper;\n-use crate::rita_common::debt_keeper::PaymentFailed;\n-use crate::rita_common::rita_loop::get_web3_server;\n-\nuse web3::client::Web3;\n-use failure::Error;\n-\npub struct PaymentController();\nimpl Actor for PaymentController {\n@@ -187,6 +179,7 @@ impl PaymentController {\n.json(&pmt)\n.expect(\"Failed to serialize payment!\")\n.send()\n+ .timeout(Duration::from_secs(4))\n.then(|neigh_ack| match neigh_ack {\n// return emtpy result, we're using messages anyways\nOk(msg) => {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/mod.rs", "new_path": "rita/src/rita_common/rita_loop/mod.rs", "diff": "@@ -48,6 +48,7 @@ use settings::RitaCommonSettings;\n// the speed in seconds for the common loop\npub const COMMON_LOOP_SPEED: u64 = 5;\n+pub const COMMON_LOOP_TIMEOUT: Duration = Duration::from_secs(4);\npub struct RitaLoop {\nwas_gateway: bool,\n@@ -113,6 +114,7 @@ impl Handler<Tick> for RitaLoop {\nArbiter::spawn(\nTunnelManager::from_registry()\n.send(GetNeighbors)\n+ .timeout(COMMON_LOOP_TIMEOUT)\n.then(move |res| {\nlet res = res.unwrap().unwrap();\n@@ -127,6 +129,7 @@ impl Handler<Tick> for RitaLoop {\nTrafficWatcher::from_registry()\n.send(Watch::new(res))\n+ .timeout(COMMON_LOOP_TIMEOUT)\n.then(move |_res| {\ninfo!(\n\"TrafficWatcher completed in {}s {}ms\",\n@@ -155,6 +158,7 @@ impl Handler<Tick> for RitaLoop {\n.send(TriggerGC(Duration::from_secs(\nSETTING.get_network().tunnel_timeout_seconds,\n)))\n+ .timeout(COMMON_LOOP_TIMEOUT)\n.then(move |res| {\ninfo!(\n\"TunnelManager GC pass completed in {}s {}ms, with result {:?}\",\n@@ -172,6 +176,7 @@ impl Handler<Tick> for RitaLoop {\nArbiter::spawn(\nPeerListener::from_registry()\n.send(Tick {})\n+ .timeout(COMMON_LOOP_TIMEOUT)\n.then(move |res| {\ninfo!(\n\"PeerListener tick completed in {}s {}ms, with result {:?}\",\n@@ -189,6 +194,7 @@ impl Handler<Tick> for RitaLoop {\nArbiter::spawn(\nPeerListener::from_registry()\n.send(GetPeers {})\n+ .timeout(COMMON_LOOP_TIMEOUT)\n.and_then(move |peers| {\n// GetPeers never fails so unwrap is safe\nlet peers = peers.unwrap();\n@@ -198,7 +204,9 @@ impl Handler<Tick> for RitaLoop {\nstart.elapsed().as_secs(),\nstart.elapsed().subsec_millis(),\n);\n- TunnelManager::from_registry().send(PeersToContact::new(peers))\n+ TunnelManager::from_registry()\n+ .send(PeersToContact::new(peers))\n+ .timeout(COMMON_LOOP_TIMEOUT)\n})\n.then(|_| Ok(())),\n);\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -44,7 +44,7 @@ use settings::RitaCommonSettings;\nuse std::collections::HashMap;\nuse std::net::IpAddr;\nuse std::time::Instant;\n-use std::time::{SystemTime, UNIX_EPOCH};\n+use std::time::{Duration, SystemTime, UNIX_EPOCH};\nmod database_tools;\npub mod db_client;\n@@ -472,6 +472,7 @@ pub fn enforce_exit_clients(\nBox::new(\nDebtKeeper::from_registry()\n.send(GetDebtsList)\n+ .timeout(Duration::from_secs(4))\n.and_then(move |debts_list| match debts_list {\nOk(list) => {\nlet mut clients_by_id = HashMap::new();\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add timeouts to all major arbiter spawns
20,244
19.04.2019 13:19:06
14,400
0b0083f57b89bb8d73ef31921b05abb598b00d39
Add log message for was_gateway This logic is bugging me, I'm going to roll this out and see if anyone ever actually executes this code.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/mod.rs", "new_path": "rita/src/rita_common/rita_loop/mod.rs", "diff": "@@ -232,10 +232,13 @@ fn manage_gateway(mut was_gateway: bool) -> bool {\nif SETTING.get_network().is_gateway {\nif was_gateway {\n+ // TODO I don't think this has been running for months\n+ info!(\"Killed trust dns actor!\");\n// trust_dns will fail to resolve if you plugin the wan port after Rita has started\n// this may be fixed in a future update of Trustdns\nlet resolver_addr: Addr<ResolverWrapper> = System::current().registry().get();\nresolver_addr.do_send(KillActor);\n+ was_gateway = false;\n}\nmatch KI.get_resolv_servers() {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add log message for was_gateway This logic is bugging me, I'm going to roll this out and see if anyone ever actually executes this code.
20,244
19.04.2019 18:54:23
14,400
f4fb8a2d58791df2a9c672b6231ccd6f61859135
Babel does not allow uintmax for local fees This adds some recovery code for this error case as well as prevents a fee that high from being set in the first place
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/babel.rs", "new_path": "rita/src/rita_common/dashboard/babel.rs", "diff": "@@ -31,6 +31,11 @@ pub fn set_local_fee(path: Path<u32>) -> Result<HttpResponse, Error> {\ndebug!(\"/local_fee/{} POST hit\", new_fee);\nlet mut ret = HashMap::<String, String>::new();\n+ if new_fee > 999_999_999 {\n+ // required because of https://github.com/althea-mesh/babeld/issues/28\n+ bail!(\"Price is too high due to babel bug!\");\n+ }\n+\nlet stream = match TcpStream::connect::<SocketAddr>(\nformat!(\"[::1]:{}\", SETTING.get_network().babel_port)\n.parse()\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/traffic_watcher/mod.rs", "new_path": "rita/src/rita_common/traffic_watcher/mod.rs", "diff": "@@ -103,7 +103,15 @@ pub fn get_babel_info<T: Read + Write>(\nlet routes = babel.parse_routes()?;\ntrace!(\"Got routes: {:?}\", routes);\nlet mut destinations = HashMap::new();\n- let local_fee = babel.get_local_fee().unwrap();\n+ let local_fee = match babel.get_local_fee() {\n+ Ok(fee) => fee,\n+ Err(e) => {\n+ error!(\"Babel fee not set properly! this is a bad sign! {:?}\", e);\n+ let configured_fee = SETTING.get_payment().local_fee;\n+ babel.set_local_fee(configured_fee)?;\n+ configured_fee\n+ }\n+ };\nlet max_fee = SETTING.get_payment().max_fee;\nfor route in &routes {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "@@ -84,12 +84,19 @@ fn get_babel_info<T: Read + Write>(\nlet routes = babel.parse_routes()?;\ninfo!(\"Got routes: {:?}\", routes);\n+ let local_fee = match babel.get_local_fee() {\n+ Ok(fee) => fee,\n+ Err(e) => {\n+ error!(\"Babel fee not set properly! this is a bad sign! {:?}\", e);\n+ let configured_fee = SETTING.get_payment().local_fee;\n+ babel.set_local_fee(configured_fee)?;\n+ configured_fee\n+ }\n+ };\n+\n// insert ourselves as a destination, don't think this is actually needed\nlet mut destinations = HashMap::new();\n- destinations.insert(\n- our_id.wg_public_key,\n- u64::from(babel.get_local_fee().unwrap()),\n- );\n+ destinations.insert(our_id.wg_public_key, u64::from(local_fee));\nlet max_fee = SETTING.get_payment().max_fee;\nfor route in &routes {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Babel does not allow uintmax for local fees This adds some recovery code for this error case as well as prevents a fee that high from being set in the first place
20,244
20.04.2019 09:07:44
14,400
74e193e7521a5ee39b7cbc2de9f510e350d415cc
Don't override the entry value during parsing Using the variable 'entry' twice in the match statements here defeated the point of some of this logging. I'm seeing a parsing error from production logs but I can't figure out what value from babel is actually causing it.
[ { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "@@ -304,20 +304,20 @@ impl<T: Read + Write> Babel<T> {\nfound_route = true;\nlet route = Route {\nid: match find_babel_val(\"route\", entry) {\n- Ok(entry) => entry,\n+ Ok(value) => value,\nErr(_) => continue,\n},\niface: match find_babel_val(\"if\", entry) {\n- Ok(entry) => entry,\n+ Ok(value) => value,\nErr(_) => continue,\n},\nxroute: false,\ninstalled: match find_babel_val(\"installed\", entry) {\n- Ok(entry) => entry.contains(\"yes\"),\n+ Ok(value) => value.contains(\"yes\"),\nErr(_) => continue,\n},\nneigh_ip: match find_babel_val(\"via\", entry) {\n- Ok(entry) => match entry.parse() {\n+ Ok(value) => match value.parse() {\nOk(parsed_data) => parsed_data,\nErr(e) => {\nwarn!(\"Error parsing neigh_ip for route {:?} from {}\", e, entry);\n@@ -327,7 +327,7 @@ impl<T: Read + Write> Babel<T> {\nErr(_) => continue,\n},\nprefix: match find_babel_val(\"prefix\", entry) {\n- Ok(entry) => match entry.parse() {\n+ Ok(value) => match value.parse() {\nOk(parsed_data) => parsed_data,\nErr(e) => {\nwarn!(\"Error parsing prefix for route {:?} from {}\", e, entry);\n@@ -337,7 +337,7 @@ impl<T: Read + Write> Babel<T> {\nErr(_) => continue,\n},\nmetric: match find_babel_val(\"metric\", entry) {\n- Ok(entry) => match entry.parse() {\n+ Ok(value) => match value.parse() {\nOk(parsed_data) => parsed_data,\nErr(e) => {\nwarn!(\"Error parsing metric for route {:?} from {}\", e, entry);\n@@ -347,7 +347,7 @@ impl<T: Read + Write> Babel<T> {\nErr(_) => continue,\n},\nrefmetric: match find_babel_val(\"refmetric\", entry) {\n- Ok(entry) => match entry.parse() {\n+ Ok(value) => match value.parse() {\nOk(parsed_data) => parsed_data,\nErr(e) => {\nwarn!(\"Error parsing refmetric {:?} from {}\", e, entry);\n@@ -357,7 +357,7 @@ impl<T: Read + Write> Babel<T> {\nErr(_) => continue,\n},\nfull_path_rtt: match find_babel_val(\"full-path-rtt\", entry) {\n- Ok(entry) => match entry.parse() {\n+ Ok(value) => match value.parse() {\nOk(parsed_data) => parsed_data,\nErr(e) => {\nwarn!(\"Error parsing full_path_rtt {:?} from {}\", e, entry);\n@@ -367,7 +367,7 @@ impl<T: Read + Write> Babel<T> {\nErr(_) => continue,\n},\nprice: match find_babel_val(\"price\", entry) {\n- Ok(entry) => match entry.parse() {\n+ Ok(value) => match value.parse() {\nOk(parsed_data) => parsed_data,\nErr(e) => {\nwarn!(\"Error parsing price {:?} from {}\", e, entry);\n@@ -377,7 +377,7 @@ impl<T: Read + Write> Babel<T> {\nErr(_) => continue,\n},\nfee: match find_babel_val(\"fee\", entry) {\n- Ok(entry) => match entry.parse() {\n+ Ok(value) => match value.parse() {\nOk(parsed_data) => parsed_data,\nErr(e) => {\nwarn!(\"Error parsing fee {:?} from {}\", e, entry);\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Don't override the entry value during parsing Using the variable 'entry' twice in the match statements here defeated the point of some of this logging. I'm seeing a parsing error from production logs but I can't figure out what value from babel is actually causing it.
20,244
20.04.2019 16:24:27
14,400
b2ba4a438d4881a0ddbe59966e191a97d82e2673
Port toggling requires a rita restart When we toggle ports like this our old listen handle gets lost easier to restart than to figure out how to re-aquire it
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/interfaces.rs", "new_path": "rita/src/rita_client/dashboard/interfaces.rs", "diff": "@@ -343,7 +343,15 @@ pub fn ethernet_transform_mode(\n// We edited disk contents, force global sync\nKI.fs_sync()?;\n- trace!(\"Successsfully transformed ethernet mode\");\n+ trace!(\"Successsfully transformed ethernet mode, rebooting\");\n+\n+ // it's now safe to restart the process, return an error if that fails somehow\n+ // do not remove this, we lose the multicast listeners on other mesh ports when\n+ // we toggle network modes, this means we will clean up valid tunnels 15 minutes\n+ // after the toggle unless we do this\n+ if let Err(e) = KI.run_command(\"/etc/init.d/rita\", &[\"restart\"]) {\n+ return Err(e);\n+ }\nOk(())\n}\n@@ -485,6 +493,14 @@ pub fn wlan_transform_mode(ifname: &str, a: InterfaceMode, b: InterfaceMode) ->\n// We edited disk contents, force global sync\nKI.fs_sync()?;\n+ // it's now safe to restart the process, return an error if that fails somehow\n+ // do not remove this, we lose the multicast listeners on other mesh ports when\n+ // we toggle network modes, this means we will clean up valid tunnels 15 minutes\n+ // after the toggle unless we do this\n+ if let Err(e) = KI.run_command(\"/etc/init.d/rita\", &[\"restart\"]) {\n+ return Err(e);\n+ }\n+\nOk(())\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Port toggling requires a rita restart When we toggle ports like this our old listen handle gets lost easier to restart than to figure out how to re-aquire it
20,244
22.04.2019 07:10:58
14,400
fd55366560ac010c6128979a661b2cae1b1a742e
System alloc is now the default So all of this is no longer required
[ { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "@@ -67,4 +67,3 @@ phonenumber = \"0.2\"\n[features]\ndefault = []\ndevelopment = []\n-system_alloc = []\n" }, { "change_type": "MODIFY", "old_path": "rita/src/client.rs", "new_path": "rita/src/client.rs", "diff": "//! This file initilizes the dashboard endpoints for the client as well as the common and client\n//! specific actors.\n-#![cfg_attr(feature = \"system_alloc\", feature(alloc_system, allocator_api))]\n#![warn(clippy::all)]\n#![allow(clippy::pedantic)]\n-#[cfg(feature = \"system_alloc\")]\n-extern crate alloc_system;\n-\n-#[cfg(feature = \"system_alloc\")]\n-use alloc_system::System;\n-\n-#[cfg(feature = \"system_alloc\")]\n-#[global_allocator]\n-static A: System = System;\n-\n#[macro_use]\nextern crate failure;\n#[macro_use]\n" }, { "change_type": "MODIFY", "old_path": "rita/src/exit.rs", "new_path": "rita/src/exit.rs", "diff": "//! This file initilizes the dashboard endpoints for the exit as well as the common and exit\n//! specific actors.\n-#![cfg_attr(feature = \"system_alloc\", feature(alloc_system, allocator_api))]\n#![warn(clippy::all)]\n#![allow(clippy::pedantic)]\n-#[cfg(feature = \"system_alloc\")]\n-extern crate alloc_system;\n-\n-#[cfg(feature = \"system_alloc\")]\n-use alloc_system::System;\n-\n-#[cfg(feature = \"system_alloc\")]\n-#[global_allocator]\n-static A: System = System;\n-\n#[macro_use]\nextern crate failure;\n#[macro_use]\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
System alloc is now the default So all of this is no longer required
20,244
24.04.2019 11:10:59
14,400
1081868c6550b49d48b6dd5db3be67cc0a0ae92d
Better logging for hello's and tunnels Just saw some strange tunnel behavior on the prod exit, changing log messages to get a better look at it next time.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/network_endpoints/mod.rs", "new_path": "rita/src/rita_common/network_endpoints/mod.rs", "diff": "@@ -88,8 +88,8 @@ pub fn hello_response(\n.parse::<SocketAddr>()\n.unwrap();\n- trace!(\"Got Hello from {:?}\", req.1.connection_info().remote());\n- trace!(\"opening tunnel in hello_response for {:?}\", their_id);\n+ info!(\"Got Hello from {:?}\", req.1.connection_info().remote());\n+ info!(\"opening tunnel in hello_response for {:?}\", their_id);\nlet peer = Peer {\ncontact_socket: socket,\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -682,7 +682,7 @@ impl TunnelManager {\nfor tunnel in tunnels.iter_mut() {\nif tunnel.listen_ifidx == peer.ifidx && tunnel.ip == peer.contact_socket.ip() {\ntrace!(\"We already have a tunnel for {:?}\", tunnel);\n- info!(\n+ trace!(\n\"Bumping timestamp after {}s for tunnel: {:?}\",\ntunnel.last_contact.elapsed().as_secs(),\ntunnel\n@@ -712,7 +712,7 @@ impl TunnelManager {\n} else {\n// In the case that we have a tunnel and they don't we drop our existing one\n// and agree on the new parameters in this message\n- trace!(\n+ info!(\n\"We have a tunnel but our peer {:?} does not! Handling\",\npeer.contact_socket.ip()\n);\n@@ -747,7 +747,7 @@ impl TunnelManager {\nreturn_bool = true;\n}\n}\n- trace!(\n+ info!(\n\"no tunnel found for {:?}%{:?} creating\",\npeer.contact_socket.ip(),\npeer.ifidx,\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Better logging for hello's and tunnels Just saw some strange tunnel behavior on the prod exit, changing log messages to get a better look at it next time.
20,244
25.04.2019 14:37:46
14,400
43aeba09265ed23aa4acd16555afe8c2ca2ab00a
Use opt level z Also adds a travis check to make sure it doesn't sneak back in
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -43,6 +43,8 @@ matrix:\nscript:\n- rustup component add rustfmt-preview\n- cargo fmt --all -- --check\n+ # to stop opt level 3 from sneaking in\n+ - \"grep -q 'opt-level = \\\"z\\\"' Cargo.toml\"\n- script: ./integration-tests/rita.sh\nenv: INITIAL_POLL_INTERVAL=5 BACKOFF_FACTOR=\"1.5\" VERBOSE=1 POSTGRES_USER=postgres POSTGRES_BIN=/usr/lib/postgresql/9.6/bin/postgres POSTGRES_DATABASE=/var/ramfs/postgresql/9.6/main POSTGRES_CONFIG=/etc/postgresql/9.6/main/postgresql.conf\n- script: ./integration-tests/rita.sh\n" }, { "change_type": "MODIFY", "old_path": "Cargo.toml", "new_path": "Cargo.toml", "diff": "@@ -14,7 +14,7 @@ rita = { path = \"./rita\" }\nmembers = [\"althea_kernel_interface\", \"bounty_hunter\", \"settings\", \"clu\", \"exit_db\"]\n[profile.release]\n-opt-level = 3\n+opt-level = \"z\"\nlto = true\ncodegen-units = 1\nincremental = false\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Use opt level z Also adds a travis check to make sure it doesn't sneak back in
20,244
25.04.2019 18:04:23
14,400
abee931e9cabc4484f4004baa6984bcb5b152953
Bump for Beta 4 rc5
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -173,7 +173,7 @@ dependencies = [\nname = \"althea_rs\"\nversion = \"0.1.10\"\ndependencies = [\n- \"rita 0.4.0\",\n+ \"rita 0.4.1\",\n]\n[[package]]\n@@ -2062,7 +2062,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.4.0\"\n+version = \"0.4.1\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "[package]\nname = \"rita\"\n-version = \"0.4.0\"\n+version = \"0.4.1\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/own_info.rs", "new_path": "rita/src/rita_common/dashboard/own_info.rs", "diff": "@@ -6,7 +6,7 @@ use clarity::Address;\nuse failure::Error;\nuse num256::{Int256, Uint256};\n-pub static READABLE_VERSION: &str = \"Beta 4 RC4\";\n+pub static READABLE_VERSION: &str = \"Beta 4 RC5\";\n#[derive(Serialize)]\npub struct OwnInfo {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Bump for Beta 4 rc5
20,244
26.04.2019 10:01:57
14,400
64de363abe7e9b1f1886353de16ffd44e5445b7c
Enable cron on startup This is a temporary change to make sure that anyone updated will be rescued from the last updates cron issues
[ { "change_type": "ADD", "old_path": null, "new_path": "althea_kernel_interface/src/check_cron.rs", "diff": "+use super::KernelInterface;\n+use failure::Error;\n+use std::process::{Command, Stdio};\n+\n+impl dyn KernelInterface {\n+ /// Checks if the cron service is running and starts it if it's not\n+ pub fn check_cron(&self) -> Result<(), Error> {\n+ Command::new(\"/etc/init.d/cron\")\n+ .args(&[\"enable\"])\n+ .stdout(Stdio::piped())\n+ .output()?;\n+ Command::new(\"/etc/init.d/cron\")\n+ .args(&[\"start\"])\n+ .stdout(Stdio::piped())\n+ .output()?;\n+\n+ Ok(())\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "althea_kernel_interface/src/lib.rs", "new_path": "althea_kernel_interface/src/lib.rs", "diff": "@@ -13,6 +13,7 @@ use std::time::Instant;\nuse std::str;\n+mod check_cron;\nmod counter;\nmod create_wg_key;\nmod delete_tunnel;\n" }, { "change_type": "MODIFY", "old_path": "rita/src/client.rs", "new_path": "rita/src/client.rs", "diff": "@@ -173,6 +173,14 @@ fn main() {\nprintln!(\"Running this on production is unsupported and not safe!\");\n}\n+ // If we are an an OpenWRT device try and rescue it from update issues\n+ // TODO remove in Beta 6\n+ if KI.is_openwrt() {\n+ if KI.check_cron().is_err() {\n+ error!(\"Failed to setup cron!\");\n+ }\n+ }\n+\nlet args: Args = Docopt::new((*USAGE).as_str())\n.and_then(|d| d.deserialize())\n.unwrap_or_else(|e| e.exit());\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Enable cron on startup This is a temporary change to make sure that anyone updated will be rescued from the last updates cron issues
20,244
26.04.2019 10:02:51
14,400
f82749d692e991ec19fb2bf143c9680f8e9c6720
Bump for Beta 4 rc6
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -173,7 +173,7 @@ dependencies = [\nname = \"althea_rs\"\nversion = \"0.1.10\"\ndependencies = [\n- \"rita 0.4.1\",\n+ \"rita 0.4.2\",\n]\n[[package]]\n@@ -2062,7 +2062,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.4.1\"\n+version = \"0.4.2\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "[package]\nname = \"rita\"\n-version = \"0.4.1\"\n+version = \"0.4.2\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/own_info.rs", "new_path": "rita/src/rita_common/dashboard/own_info.rs", "diff": "@@ -6,7 +6,7 @@ use clarity::Address;\nuse failure::Error;\nuse num256::{Int256, Uint256};\n-pub static READABLE_VERSION: &str = \"Beta 4 RC5\";\n+pub static READABLE_VERSION: &str = \"Beta 4 RC6\";\n#[derive(Serialize)]\npub struct OwnInfo {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Bump for Beta 4 rc6
20,244
26.04.2019 10:56:50
14,400
fb0c3ad248d983080b40e5534ea7de2d2fb03f31
Add Cargo geiger and audit to CI
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -8,7 +8,7 @@ before_install:\n- sudo add-apt-repository universe\n- sudo apt-get -qq update\n- sudo apt-get install -y libsqlite3-dev postgresql-client-11 postgresql-server-dev-11 libpq-dev iperf3 python3-pip bridge-utils wireguard linux-source linux-headers-$(uname -r) curl git libssl-dev pkg-config build-essential ipset python3-setuptools python3-wheel\n- - command -v cross 1>/dev/null || cargo install cross\n+ - cargo install cross --force\n- psql -c 'create database test;' -U postgres\nenv:\n@@ -45,6 +45,8 @@ matrix:\n- cargo fmt --all -- --check\n# to stop opt level 3 from sneaking in\n- \"grep -q 'opt-level = \\\"z\\\"' Cargo.toml\"\n+ - \"cargo install cargo-audit --force && cargo audit\"\n+ - \"cargo install cargo-geiger --force && cargo geiger\"\n- script: ./integration-tests/rita.sh\nenv: INITIAL_POLL_INTERVAL=5 BACKOFF_FACTOR=\"1.5\" VERBOSE=1 POSTGRES_USER=postgres POSTGRES_BIN=/usr/lib/postgresql/9.6/bin/postgres POSTGRES_DATABASE=/var/ramfs/postgresql/9.6/main POSTGRES_CONFIG=/etc/postgresql/9.6/main/postgresql.conf\n- script: ./integration-tests/rita.sh\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add Cargo geiger and audit to CI
20,244
28.04.2019 17:12:34
14,400
8f4ef2159e481605e1a7d8b430bde5305f119d57
Add timeout to the main rita loop In this case I'm concerned about the syncronous actions on the exit extending beyond the desired time period. Since the database connector doesn't apparently have the concept of a timeout.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "@@ -18,6 +18,7 @@ use actix::prelude::{\nuse diesel::query_dsl::RunQueryDsl;\nuse exit_db::models;\nuse failure::Error;\n+use futures::future::Future;\nuse settings::exit::RitaExitSettings;\nuse std::collections::HashMap;\nuse std::net::IpAddr;\n@@ -38,8 +39,14 @@ impl Actor for RitaLoop {\nfn started(&mut self, ctx: &mut Context<Self>) {\ninfo!(\"exit loop started\");\nctx.run_interval(Duration::from_secs(EXIT_LOOP_SPEED), |_act, ctx| {\n+ // we add a timeout on the loop future here as a hacky way to timeout\n+ // the databse connection since diesel doesn't provide such a feature\nlet addr: Addr<Self> = ctx.address();\n- addr.do_send(Tick);\n+ let fut = addr\n+ .send(Tick)\n+ .timeout(Duration::from_secs(4))\n+ .then(|_result| Ok(()) as Result<(), ()>);\n+ Arbiter::spawn(fut);\n});\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add timeout to the main rita loop In this case I'm concerned about the syncronous actions on the exit extending beyond the desired time period. Since the database connector doesn't apparently have the concept of a timeout.
20,244
29.04.2019 13:46:21
14,400
98daaef10076623c5b49f121eb1c20547d6bf266
Update babel monitor to correct fee error 'fee' is a correct hex value for a route id, therefore we would fail to parse values in the case that the route id contained 'fee' becuase contains() was used rather than ==
[ { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "@@ -39,7 +39,7 @@ use crate::BabelMonitorError::*;\nfn find_babel_val(val: &str, line: &str) -> Result<String, Error> {\nlet mut iter = line.split(\" \");\nwhile let Some(entry) = iter.next() {\n- if entry.to_string().contains(val) {\n+ if entry.to_string() == val {\nmatch iter.next() {\nSome(v) => return Ok(v.to_string()),\nNone => continue,\n@@ -492,6 +492,8 @@ add route 14f06d8 prefix 10.28.20.151/32 from 0.0.0.0/0 installed yes id ba:27:e\nmetric 817 price 4008 fee 4008 refmetric 0 full-path-rtt 18.674 via fe80::e9d0:498f:6c61:be29 if wlan0 \\n\\\nadd route 14f0548 prefix 10.28.244.138/32 from 0.0.0.0/0 installed yes id ba:27:eb:ff:fe:d1:3e:ba \\\nmetric 958 price 2048 fee 2048 refmetric 0 full-path-rtt 56.805 via fe80::e914:2335:a76:bda3 if wlan0\\n\\\n+add route 241fee0 prefix fdc5:5bcb:24ac:b35a:4b7f:146a:a2a1:bdc4/128 from ::/0 installed no id \\\n+e6:95:6e:ff:fe:44:c4:12 metric 328 price 426000 fee 354600 refmetric 217 full-path-rtt 39.874 via fe80::6459:f009:c4b4:9971 if wg36\nok\\n\";\nstatic PREAMBLE: &'static str =\n@@ -506,6 +508,11 @@ ok\\n\";\nba:27:eb:ff:fe:c1:2d:d5 metric 1306 price 4008 refmetric 0 full-path-rtt 18.674 via \\\nfe80::e9d0:498f:6c61:be29 if wlan0\";\n+ static PROBLEM_ROUTE_LINE: &'static str =\n+ \"add route 241fee0 prefix fdc5:5bcb:24ac:b35a:4b7f:146a:a2a1:bdc4/128 \\\n+ from ::/0 installed no id e6:95:6e:ff:fe:44:c4:12 metric 331 price 426000 fee 354600 refmetric 220 full-path-rtt \\\n+ 38.286 via fe80::6459:f009:c4b4:9971 if wg36\";\n+\nstatic NEIGH_LINE: &'static str =\n\"add neighbour 14f05f0 address fe80::e9d0:498f:6c61:be29 if wlan0 reach ffff rxcost \\\n256 txcost 256 rtt 29.264 rttcost 1050 cost 1306\";\n@@ -546,6 +553,27 @@ ok\\n\";\nfind_babel_val(\"via\", ROUTE_LINE).unwrap(),\n\"fe80::e9d0:498f:6c61:be29\"\n);\n+ assert_eq!(\n+ find_babel_val(\"route\", PROBLEM_ROUTE_LINE).unwrap(),\n+ \"241fee0\"\n+ );\n+ assert_eq!(\n+ find_babel_val(\"fee\", PROBLEM_ROUTE_LINE).unwrap(),\n+ \"354600\"\n+ );\n+ assert_eq!(\n+ find_babel_val(\"price\", PROBLEM_ROUTE_LINE).unwrap(),\n+ \"426000\"\n+ );\n+ assert_eq!(find_babel_val(\"if\", PROBLEM_ROUTE_LINE).unwrap(), \"wg36\");\n+ assert_eq!(\n+ find_babel_val(\"prefix\", PROBLEM_ROUTE_LINE).unwrap(),\n+ \"fdc5:5bcb:24ac:b35a:4b7f:146a:a2a1:bdc4/128\"\n+ );\n+ assert_eq!(\n+ find_babel_val(\"full-path-rtt\", PROBLEM_ROUTE_LINE).unwrap(),\n+ \"38.286\"\n+ );\nassert_eq!(find_babel_val(\"reach\", NEIGH_LINE).unwrap(), \"ffff\");\nassert_eq!(find_babel_val(\"rxcost\", NEIGH_LINE).unwrap(), \"256\");\nassert_eq!(find_babel_val(\"rtt\", NEIGH_LINE).unwrap(), \"29.264\");\n@@ -574,7 +602,7 @@ ok\\n\";\nlet mut b = Babel::new(s);\nlet routes = b.parse_routes().unwrap();\n- assert_eq!(routes.len(), 4);\n+ assert_eq!(routes.len(), 5);\nlet route = routes.get(0).unwrap();\nassert_eq!(route.price, 3072);\n@@ -600,7 +628,7 @@ ok\\n\";\nb.start_connection().unwrap();\nlet routes = b.parse_routes().unwrap();\n- assert_eq!(routes.len(), 4);\n+ assert_eq!(routes.len(), 5);\nlet route = routes.get(0).unwrap();\nassert_eq!(route.price, 3072);\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Update babel monitor to correct fee error 'fee' is a correct hex value for a route id, therefore we would fail to parse values in the case that the route id contained 'fee' becuase contains() was used rather than ==
20,244
30.04.2019 11:25:23
14,400
50091c5fa8d0658258aa35989d1694baa5030901
Better logging for payments and oracle
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/oracle/mod.rs", "new_path": "rita/src/rita_common/oracle/mod.rs", "diff": "@@ -84,7 +84,7 @@ impl Handler<Update> for Oracle {\nlet oracle_enabled = payment_settings.price_oracle_enabled;\ndrop(payment_settings);\n- trace!(\"About to make web3 requests to {}\", full_node);\n+ info!(\"About to make web3 requests to {}\", full_node);\nupdate_balance(our_address, &web3);\nupdate_nonce(our_address, &web3);\nupdate_gas_price(&web3);\n@@ -105,7 +105,7 @@ fn update_balance(our_address: Address, web3: &Web3) {\n.eth_get_balance(our_address)\n.then(|balance| match balance {\nOk(value) => {\n- trace!(\"Got response from balance request {:?}\", value);\n+ info!(\"Got response from balance request {:?}\", value);\nlet our_balance = &mut SETTING.get_payment_mut().balance;\n// if our balance is not zero and the response we get from the full node\n// is zero either we very carefully emptied our wallet or it's that annoying Geth bug\n@@ -134,7 +134,7 @@ fn get_net_version(web3: &Web3) {\nlet res = web3.net_version()\n.then(|net_version| match net_version {\nOk(value) => {\n- trace!(\"Got response from net_version request {:?}\", value);\n+ info!(\"Got response from net_version request {:?}\", value);\nmatch value.parse::<u64>() {\nOk(net_id_num) => {\nlet mut payment_settings = SETTING.get_payment_mut();\n@@ -176,7 +176,7 @@ fn update_nonce(our_address: Address, web3: &Web3) {\n.eth_get_transaction_count(our_address)\n.then(|transaction_count| match transaction_count {\nOk(value) => {\n- trace!(\"Got response from nonce request {:?}\", value);\n+ info!(\"Got response from nonce request {:?}\", value);\nlet mut payment_settings = SETTING.get_payment_mut();\npayment_settings.nonce = value;\nOk(())\n@@ -202,7 +202,7 @@ fn update_gas_price(web3: &Web3) {\n.eth_gas_price()\n.then(|gas_price| match gas_price {\nOk(value) => {\n- trace!(\"Got response from gas price request {:?}\", value);\n+ info!(\"Got response from gas price request {:?}\", value);\n// Dynamic fee computation\nlet mut payment_settings = SETTING.get_payment_mut();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "@@ -172,7 +172,7 @@ impl PaymentController {\nOk(tx_id) => {\ninfo!(\"Sending bw payment with txid: {:#066x}\", tx_id);\n// add published txid to submission\n- pmt.txid = Some(tx_id);\n+ pmt.txid = Some(tx_id.clone());\nEither::A(\nclient::post(&neighbor_url)\n.with_connection(Connection::from_stream(open_stream))\n@@ -180,10 +180,13 @@ impl PaymentController {\n.expect(\"Failed to serialize payment!\")\n.send()\n.timeout(Duration::from_secs(4))\n- .then(|neigh_ack| match neigh_ack {\n+ .then(move |neigh_ack| match neigh_ack {\n// return emtpy result, we're using messages anyways\nOk(msg) => {\n- trace!(\"Payment successful with {:?}\", msg);\n+ info!(\n+ \"Payment with txid: {:#066x} successful with {:?}\",\n+ tx_id, msg\n+ );\n// this is questionably useful, we will upadte this value on our\n// next full node request, the increment is on the off chance we\n// try to send another payment before we update the nonce again\n@@ -200,6 +203,9 @@ impl PaymentController {\nErr(e) => {\nwarn!(\"Failed to send bandwidth payment {:?}\", e);\n+ // once again this may not be the best idea, we need to increment\n+ // the nonce but it's possible this will only end up making the payment invalid\n+ SETTING.get_payment_mut().nonce += 1u64.into();\nDebtKeeper::from_registry().do_send(PaymentFailed {\nto: pmt.to,\namount: pmt.amount,\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_validator/mod.rs", "new_path": "rita/src/rita_common/payment_validator/mod.rs", "diff": "@@ -127,8 +127,8 @@ pub fn validate_transaction(ts: &ToValidate) {\nlet long_life_ts = ts.clone();\n- let res = web3\n- .eth_get_transaction_by_hash(txid)\n+ let res =\n+ web3.eth_get_transaction_by_hash(txid.clone())\n.then(move |tx_status| match tx_status {\n// first level is our success/failure at talking to the full node\nOk(status) => match status {\n@@ -140,7 +140,10 @@ pub fn validate_transaction(ts: &ToValidate) {\n&& transaction.to == our_address\n{\nif transaction.block_number.is_some() {\n- trace!(\"payment successfully validated!\");\n+ info!(\n+ \"payment {:#066x} from {} successfully validated!\",\n+ txid, from_address\n+ );\nPaymentController::from_registry()\n.do_send(rita_common::payment_controller::PaymentReceived(pmt));\nPaymentValidator::from_registry().do_send(Remove(long_life_ts));\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Better logging for payments and oracle
20,244
30.04.2019 11:48:51
14,400
4acce4604121aff3bb806744444afc35f0cef181
Only modify the nonce when the error message calls for it
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "@@ -203,9 +203,13 @@ impl PaymentController {\nErr(e) => {\nwarn!(\"Failed to send bandwidth payment {:?}\", e);\n- // once again this may not be the best idea, we need to increment\n- // the nonce but it's possible this will only end up making the payment invalid\n+ let error_message = format!(\"{:?}\", e);\n+ if error_message.contains(\"nonce too low\")\n+ || error_message.contains(\"Transaction nonce is too low\")\n+ {\nSETTING.get_payment_mut().nonce += 1u64.into();\n+ }\n+\nDebtKeeper::from_registry().do_send(PaymentFailed {\nto: pmt.to,\namount: pmt.amount,\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Only modify the nonce when the error message calls for it
20,244
30.04.2019 12:24:16
14,400
5ce037c4214a2c11a179b4d4edd1801650fd13b4
Log the full node used when a payment fails
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "@@ -202,7 +202,10 @@ impl PaymentController {\n}\nErr(e) => {\n- warn!(\"Failed to send bandwidth payment {:?}\", e);\n+ warn!(\n+ \"Failed to send bandwidth payment {:?}, using full node {}\",\n+ e, full_node\n+ );\nlet error_message = format!(\"{:?}\", e);\nif error_message.contains(\"nonce too low\")\n|| error_message.contains(\"Transaction nonce is too low\")\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Log the full node used when a payment fails
20,244
30.04.2019 12:38:25
14,400
5e9f2d2c2c77eedfa340e73c9384c58069c914cd
Log even more info about successful payments My specific goal of this is to be able to compare the total of failed payments to successful payments over a period
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "@@ -184,8 +184,8 @@ impl PaymentController {\n// return emtpy result, we're using messages anyways\nOk(msg) => {\ninfo!(\n- \"Payment with txid: {:#066x} successful with {:?}\",\n- tx_id, msg\n+ \"Payment with txid: {:#066x} successful with {:?}, using full node {} and amound {:?}\",\n+ tx_id, msg, full_node, pmt.amount\n);\n// this is questionably useful, we will upadte this value on our\n// next full node request, the increment is on the off chance we\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Log even more info about successful payments My specific goal of this is to be able to compare the total of failed payments to successful payments over a period
20,244
01.05.2019 13:19:50
14,400
67dfed1826a002a0df00b1a0eb0220441febd533
Dramatically simplify DebtKeeper
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/neighbors.rs", "new_path": "rita/src/rita_client/dashboard/neighbors.rs", "diff": "@@ -146,7 +146,7 @@ fn merge_debts_and_neighbors(\n) {\nfor neighbor in neighbors {\nlet id = neighbor.identity.global;\n- debts.entry(id).or_insert_with(|| NodeDebtData::new(0));\n+ debts.entry(id).or_insert_with(NodeDebtData::new);\n}\n}\n" }, { "change_type": "DELETE", "old_path": "rita/src/rita_common/debt_keeper/README.md", "new_path": null, "diff": "-# How DebtKeeper stores stuff\n-There are 3 different buckets which credits/debits to a neighboring node is stored:\n-- Incoming payments\n-- Debt buffer\n-- Debt\n-## Incoming payments\n-Incoming payments represents the payments which a node as received from its neighbours. It is\n-treated differently from credit from traffic counters as _it will never be sent back to the node\n-which sent it_.\n-## Debt buffer\n-Debt buffer represents a \\\"time delayed\\\" view of the debts which another node owes us, enabling\n-small delays in payments caused by misaligned billing cycles or occasional missed payments to\n-not close a connection\n-## Debt\n-Debt represents the amount of stuff we owe others or others owe us _at this moment, taking into\n-account the debt buffering effects_\n-# How DebtKeeper works\n-There are 3 different ways to update the DebtKeeper state:\n-- PaymentReceived\n-- TrafficUpdate\n-- CycleUpdate\n-## PaymentReceived\n-This simply increments the incoming payments value\n-## TrafficUpdate\n-Traffic updates are treated differently depending on if the update is positive or negative.\n-If the update is positive (we pay them), we apply the credit immediately by adding the amount\n-to the Debt value\n-If the update is negative (they pay us), we buffer the debit to give them time to pay it back,\n-by adding the update to the value on the back of the Debt buffer.\n-## CycleUpdate\n-Cycle updates does two things, updating the state of which the debt is stored and also producing\n-a DebtAction based on the result of the update\n-### State update\n-To update the state, first we pop off the front value of the debt buffer to get a \\\"time delayed\\\"\n-debt value from several billing cycles ago.\n-Then we check if the PaymentReceived is enough to pay off the time delayed debt. If there is\n-enough, we can also check if there is any Debt to pay off, and try to pay that off with the\n-payments we received.\n-However, if the PaymentReceived value is not enough to pay off the time delayed debt, we just\n-subtract the difference from the debt.\n-### DebtAction decision\n-- If their debt is below our cutoff, suspend the tunnel\n-- If their debt was below our cutoff, and is now above, reopen the tunnel\n-- If their debt is above our payment threshold, pay them\n-- Else, nothing needs to be done\"\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/debt_keeper/mod.rs", "new_path": "rita/src/rita_common/debt_keeper/mod.rs", "diff": "//! maintains the long term memory of who owes who what so that it may later be quiered and paid\n//! by payment manager in the current implementation or guac in the more final one\n//!\n-//! You may be wondering what's up with debt buffers actions and incoming payments, why can't we\n-//! just have debt? Well this whole module is only slightly more complicated than it needs to be.\n+//! You may be wondering what's up with incoming payments, why can't we just have debt?\n+//! Well this whole module is only slightly more complicated than it needs to be.\n//! Lets say for example that we owe Bob some money, but for reasons unknown Bob pays us, do we\n//! increase the amount we owe Bob? That's probably a vulnerability rabbit hole at the very least.\n//! Hence we need an incoming paymetns parameter to take money out of. This of course implies half\n//! of the excess complexity you see, managing an incoming payments pool versus a incoming debts pool\n-//!\n-//! The debts buffer is pretty safe to eliminate I think, except insomuch as it lets us keep better\n-//! track of state transitions by allowing us to apply new debt as a seperate operation.\n-\n-use ::actix::prelude::*;\n-\n-use std::collections::{HashMap, VecDeque};\n-\n-use althea_types::{Identity, PaymentTx};\n-\n-use num256::{Int256, Uint256};\n-use num_traits::{CheckedSub, Signed};\n-\n-use crate::SETTING;\n-use settings::RitaCommonSettings;\nuse crate::rita_common::payment_controller;\nuse crate::rita_common::payment_controller::PaymentController;\nuse crate::rita_common::tunnel_manager::TunnelAction;\nuse crate::rita_common::tunnel_manager::TunnelManager;\nuse crate::rita_common::tunnel_manager::TunnelStateChange;\n-\n+use crate::SETTING;\n+use ::actix::prelude::{Actor, Context, Handler, Message, Supervised, SystemService};\n+use althea_types::{Identity, PaymentTx};\nuse failure::Error;\n+use num256::{Int256, Uint256};\n+use num_traits::{CheckedSub, Signed};\n+use settings::RitaCommonSettings;\n+use std::collections::HashMap;\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct NodeDebtData {\n@@ -38,29 +29,17 @@ pub struct NodeDebtData {\npub total_payment_sent: Uint256,\npub debt: Int256,\npub incoming_payments: Int256,\n- /// Front = older\n- /// Only pop from front\n- /// Only push to back\n- #[serde(skip_serializing)]\n- pub debt_buffer: VecDeque<Int256>,\npub action: DebtAction,\n}\nimpl NodeDebtData {\n- pub fn new(buffer_period: u32) -> NodeDebtData {\n+ pub fn new() -> NodeDebtData {\nNodeDebtData {\ntotal_payment_received: Uint256::from(0u32),\ntotal_payment_sent: Uint256::from(0u32),\ndebt: Int256::from(0),\nincoming_payments: Int256::from(0),\n- debt_buffer: {\n- let mut buf = VecDeque::new();\n- for _ in 0..buffer_period {\n- buf.push_back(Int256::from(0));\n- }\n- buf\n- },\n- action: DebtAction::None,\n+ action: DebtAction::OpenTunnel,\n}\n}\n}\n@@ -178,7 +157,6 @@ pub enum DebtAction {\nSuspendTunnel,\nOpenTunnel,\nMakePayment { to: Identity, amount: Uint256 },\n- None,\n}\nimpl Handler<SendUpdate> for DebtKeeper {\n@@ -210,7 +188,6 @@ impl Handler<SendUpdate> for DebtKeeper {\namount,\ntxid: None, // not yet published\n})),\n- DebtAction::None => {}\n}\n}\nOk(())\n@@ -226,7 +203,7 @@ impl Default for DebtKeeper {\nimpl DebtKeeper {\npub fn new() -> Self {\nassert!(SETTING.get_payment().pay_threshold >= Int256::from(0));\n- assert!(SETTING.get_payment().close_fraction > Int256::from(0));\n+ assert!(SETTING.get_payment().close_threshold <= Int256::from(0));\nDebtKeeper {\ndebt_data: DebtData::new(),\n@@ -238,66 +215,62 @@ impl DebtKeeper {\n}\nfn get_debt_data_mut(&mut self, ident: &Identity) -> &mut NodeDebtData {\n- let buffer = SETTING.get_payment().buffer_period;\nself.debt_data\n.entry(ident.clone())\n- .or_insert_with(|| NodeDebtData::new(buffer))\n+ .or_insert_with(NodeDebtData::new)\n}\nfn payment_received(&mut self, ident: &Identity, amount: Uint256) -> Result<(), Error> {\n+ let zero = Int256::from(0);\n+ let incoming_amount = amount\n+ .to_int256()\n+ .ok_or_else(|| format_err!(\"Unable to convert amount to 256 bit signed integer\"))?;\nlet debt_data = self.get_debt_data_mut(ident);\n-\n- let old_balance = debt_data.incoming_payments.clone();\n- trace!(\n- \"payment received: old balance for {:?}: {:?}\",\n- ident.mesh_ip,\n- old_balance\n+ println!(\n+ \"payment received: old incoming payments for {:?}: {:?}\",\n+ ident.mesh_ip, debt_data.incoming_payments\n);\n- debt_data.incoming_payments = old_balance.clone()\n- + amount.to_int256().ok_or_else(|| {\n- format_err!(\"Unable to convert amount to 256 bit unsigned integer\")\n- })?;\n+\n+ // just a counter, no convergence importance\ndebt_data.total_payment_received += amount.clone();\n+ // add in the latest amount to the pile before processing\n+ debt_data.incoming_payments += incoming_amount;\n- trace!(\n- \"new balance for {:?}: {:?}\",\n- ident.mesh_ip,\n- debt_data.incoming_payments\n+ let they_owe_us = debt_data.debt < Int256::from(0);\n+ let incoming_greater_than_debt = debt_data.incoming_payments > debt_data.debt.abs();\n+\n+ // somewhat more complicated, we apply incoming to the balance, but don't allow\n+ // the balance to go positive (we owe them) we don't want to get into paying them\n+ // because they overpaid us.\n+ match (they_owe_us, incoming_greater_than_debt) {\n+ (true, true) => {\n+ debt_data.incoming_payments -= debt_data.debt.abs();\n+ debt_data.debt = zero;\n+ }\n+ (true, false) => {\n+ debt_data.debt += debt_data.incoming_payments.clone();\n+ debt_data.incoming_payments = zero;\n+ }\n+ (false, _) => {}\n+ }\n+\n+ println!(\n+ \"new incoming payments for {:?}: {:?}\",\n+ ident.mesh_ip, debt_data.incoming_payments\n);\nOk(())\n}\n- fn traffic_update(&mut self, ident: &Identity, mut amount: Int256) {\n- {\n- trace!(\"traffic update for {} is {}\", ident.mesh_ip, amount);\n+ fn traffic_update(&mut self, ident: &Identity, amount: Int256) {\n+ println!(\"traffic update for {} is {}\", ident.mesh_ip, amount);\nlet debt_data = self.get_debt_data_mut(ident);\n+ assert!(debt_data.incoming_payments >= Int256::from(0));\n- if amount < Int256::from(0) {\n- if debt_data.incoming_payments > -amount.clone() {\n- // can pay off debt fully\n- debt_data.incoming_payments += amount;\n- } else {\n- // pay off part of it\n- amount += debt_data.incoming_payments.clone();\n- debt_data.incoming_payments = Int256::from(0);\n-\n- // Buffer debt in the back of the debt buffer\n- debt_data.debt_buffer[(SETTING.get_payment().buffer_period - 1) as usize] +=\n- amount;\n- }\n- } else {\n- // Immediately apply credit\n+ // we handle the incoming debit or credit versus our existing debit or credit\n+ // very simple\ndebt_data.debt += amount;\n- }\n- trace!(\"debt data for {} is {:?}\", ident.mesh_ip, debt_data);\n- } // borrowck\n- let mut imbalance = Uint256::from(0u32);\n- for (_, v) in self.debt_data.clone() {\n- // Conversion of abs(int256) -> uint256 is guaranteed to be safe.\n- imbalance += v.debt.abs().to_uint256().unwrap();\n- }\n- trace!(\"total debt imbalance: {}\", imbalance);\n+ trace!(\"debt data for {} is {:?}\", ident.mesh_ip, debt_data);\n}\n/// This updates a neighbor's debt and outputs a DebtAction if one is necessary.\n@@ -305,42 +278,14 @@ impl DebtKeeper {\ntrace!(\"debt data: {:?}\", self.debt_data);\nlet debt_data = self.get_debt_data_mut(ident);\n// the debt we started this round with\n- let starting_debt = debt_data.debt.clone();\n-\n- let traffic = debt_data.debt_buffer.pop_front().unwrap();\n- debt_data.debt_buffer.push_back(Int256::from(0));\ntrace!(\n- \"send_update for {:?}: debt: {:?}, payment balance: {:?}, traffic: {:?}\",\n+ \"send_update for {:?}: debt: {:?}, payment balance: {:?}\",\nident.mesh_ip,\n- starting_debt,\n+ debt_data.debt,\ndebt_data.incoming_payments,\n- traffic\n);\n- // TODO signed logic is an accident waiting to happen, refactor to use ABS then\n- // change over to uints\n- if debt_data.incoming_payments > -traffic.clone() {\n- // we have enough to pay off the traffic from just the payment balance\n- debt_data.incoming_payments += traffic.clone();\n-\n- // pay off some debt if we have extra\n- if debt_data.debt > Int256::from(0) {\n- // no need to pay off\n- } else if debt_data.debt < -debt_data.incoming_payments.clone() {\n- // not enough to pay off fully\n- debt_data.debt += debt_data.incoming_payments.clone();\n- debt_data.incoming_payments = Int256::from(0);\n- } else {\n- // pay off debt fully\n- debt_data.incoming_payments += debt_data.debt.clone();\n- debt_data.debt = Int256::from(0);\n- }\n- } else {\n- // rack up debt\n- debt_data.debt += debt_data.incoming_payments.clone() + traffic;\n- debt_data.incoming_payments = Int256::from(0);\n-\n// reduce debt if it's negative to try and trend to zero\n// the edge case this is supposed to handle is if a node ran out of money and then\n// crashed so it doesn't know what it owes the exit and it may come back hours later\n@@ -348,44 +293,36 @@ impl DebtKeeper {\n// to bounce in and out of it, this value is hand tuned to take the average round overrun\n// and bring it below the close treshold once every 3 hours. If the client router has been\n// refilled it should return to full function then\n- if debt_data.debt < Int256::from(0) && cfg!(not(test)) {\n- debt_data.debt += 300_000_000u64.into();\n- }\n- }\n+ // TODO replace with explcit timer system\n+ // if debt_data.debt < Int256::from(0) {\n+ // debt_data.debt += 300_000_000u64.into();\n+ // }\n- // closing has a fudge factor that increases the close treshold as more and more\n- // payments accure, 1/100th of the payment amount grace is the default, this isn't\n- // really needed as the modern system converges smoothly but neither should it really\n- // harm anything as long as earnings are greater than 1%\n- let close_threshold = SETTING.get_payment().close_threshold.clone()\n- - (debt_data\n- .total_payment_received\n- .to_int256()\n- .ok_or_else(|| {\n- format_err!(\"Unable to cast total payment received to signed 256 bit integer\")\n- })?\n- / SETTING.get_payment().close_fraction.clone());\n+ let close_threshold = SETTING.get_payment().close_threshold.clone();\n- if debt_data.debt < close_threshold {\n- trace!(\n+ println!(\n+ \"Debt is {} and close is {}\",\n+ debt_data.debt, close_threshold\n+ );\n+ // negative debt means they owe us so when the debt is more negative than\n+ // the close treshold we should enforce.\n+\n+ let should_close = debt_data.debt < close_threshold;\n+ let should_pay = debt_data.debt > SETTING.get_payment().pay_threshold;\n+ match (should_close, should_pay) {\n+ (true, true) => panic!(\"Close threshold is less than pay threshold!\"),\n+ (true, false) => {\n+ info!(\n\"debt is below close threshold for {}. suspending forwarding\",\nident.mesh_ip\n);\ndebt_data.action = DebtAction::SuspendTunnel;\nOk(DebtAction::SuspendTunnel)\n- } else if (close_threshold < debt_data.debt) && (starting_debt < close_threshold) {\n- trace!(\"debt is above close threshold. resuming forwarding\");\n- debt_data.action = DebtAction::OpenTunnel;\n- Ok(DebtAction::OpenTunnel)\n- } else if debt_data.debt > SETTING.get_payment().pay_threshold {\n+ }\n+ (false, true) => {\nlet d: Uint256 = debt_data.debt.to_uint256().ok_or_else(|| {\nformat_err!(\"Unable to convert debt data into unsigned 256 bit integer\")\n})?;\n- trace!(\n- \"debt is above payment threshold for {}. making payment of {}\",\n- ident.mesh_ip,\n- d\n- );\ndebt_data.total_payment_sent += d.clone();\ndebt_data.debt = Int256::from(0);\n@@ -398,9 +335,11 @@ impl DebtKeeper {\nto: *ident,\namount: d,\n})\n- } else {\n- debt_data.action = DebtAction::None;\n- Ok(DebtAction::None)\n+ }\n+ (false, false) => {\n+ debt_data.action = DebtAction::OpenTunnel;\n+ Ok(DebtAction::OpenTunnel)\n+ }\n}\n}\n}\n@@ -461,8 +400,6 @@ mod tests {\nfn test_single_suspend() {\nSETTING.get_payment_mut().pay_threshold = Int256::from(5);\nSETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 1;\nlet mut d = DebtKeeper::new();\n@@ -477,8 +414,6 @@ mod tests {\nfn test_single_overpay() {\nSETTING.get_payment_mut().pay_threshold = Int256::from(5);\nSETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 1;\nlet mut d = DebtKeeper::new();\n@@ -487,119 +422,13 @@ mod tests {\nd.traffic_update(&ident, Int256::from(-100i64));\nlet _ = d.payment_received(&ident, Uint256::from(1000u64));\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n- }\n-\n- #[test]\n- fn test_buffer_suspend() {\n- SETTING.get_payment_mut().pay_threshold = Int256::from(5i64);\n- SETTING.get_payment_mut().close_threshold = Int256::from(-10i64);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100i64);\n- SETTING.get_payment_mut().buffer_period = 2;\n-\n- let mut d = DebtKeeper::new();\n- let ident = get_test_identity();\n-\n- d.traffic_update(&ident, Int256::from(-100i64));\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::SuspendTunnel);\n- }\n-\n- #[test]\n- fn test_buffer_average() {\n- SETTING.get_payment_mut().pay_threshold = Int256::from(5);\n- SETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 2;\n-\n- let mut d = DebtKeeper::new();\n- let ident = get_test_identity();\n-\n- d.traffic_update(&ident, Int256::from(-100i64));\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n-\n- d.traffic_update(&ident, Int256::from(100));\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n- }\n-\n- #[test]\n- fn test_buffer_repay() {\n- SETTING.get_payment_mut().pay_threshold = Int256::from(5);\n- SETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 2;\n-\n- let mut d = DebtKeeper::new();\n- let ident = get_test_identity();\n-\n- d.traffic_update(&ident, Int256::from(-100i64));\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n-\n- d.payment_received(&ident, Uint256::from(100u64)).unwrap();\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n- }\n-\n- #[test]\n- fn test_buffer_overpay() {\n- SETTING.get_payment_mut().pay_threshold = Int256::from(5);\n- SETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 2;\n-\n- let mut d = DebtKeeper::new();\n- let ident = get_test_identity();\n-\n- d.traffic_update(&ident, Int256::from(-100i64));\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n-\n- d.traffic_update(&ident, Int256::from(-100i64));\n- d.payment_received(&ident, Uint256::from(1000u64)).unwrap();\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n- }\n-\n- #[test]\n- fn test_buffer_debt() {\n- SETTING.get_payment_mut().pay_threshold = Int256::from(5);\n- SETTING.get_payment_mut().close_threshold = Int256::from(-100i64);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 2;\n-\n- let mut d = DebtKeeper::new();\n- let ident = get_test_identity();\n-\n- d.traffic_update(&ident, Int256::from(-50));\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n-\n- // our debt should be -50\n-\n- d.traffic_update(&ident, Int256::from(100));\n-\n- assert_eq!(\n- d.send_update(&ident).unwrap(),\n- DebtAction::MakePayment {\n- amount: Uint256::from(50u32),\n- to: ident,\n- }\n- );\n+ assert_eq!(d.send_update(&ident).unwrap(), DebtAction::OpenTunnel);\n}\n#[test]\nfn test_single_pay() {\nSETTING.get_payment_mut().pay_threshold = Int256::from(5);\nSETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 2;\nlet mut d = DebtKeeper::new();\nlet ident = get_test_identity();\n@@ -615,29 +444,10 @@ mod tests {\n);\n}\n- #[test]\n- fn test_fudge() {\n- SETTING.get_payment_mut().pay_threshold = Int256::from(5);\n- SETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 1;\n-\n- let mut d = DebtKeeper::new();\n- let ident = get_test_identity();\n-\n- d.payment_received(&ident, Uint256::from(100_000u64))\n- .unwrap();\n- d.traffic_update(&ident, Int256::from(-100_100));\n-\n- assert_eq!(d.send_update(&ident).unwrap(), DebtAction::None,);\n- }\n-\n#[test]\nfn test_single_reopen() {\nSETTING.get_payment_mut().pay_threshold = Int256::from(5);\nSETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 1;\nlet mut d = DebtKeeper::new();\nlet ident = get_test_identity();\n@@ -655,8 +465,6 @@ mod tests {\nfn test_multi_pay() {\nSETTING.get_payment_mut().pay_threshold = Int256::from(5);\nSETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100);\n- SETTING.get_payment_mut().buffer_period = 1;\nlet mut d = DebtKeeper::new();\nlet ident = get_test_identity();\n@@ -679,8 +487,6 @@ mod tests {\nfn test_multi_fail() {\nSETTING.get_payment_mut().pay_threshold = Int256::from(5);\nSETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(100_000);\n- SETTING.get_payment_mut().buffer_period = 1;\nlet mut d = DebtKeeper::new();\nlet ident = get_test_identity();\n@@ -699,8 +505,6 @@ mod tests {\nfn test_multi_reopen() {\nSETTING.get_payment_mut().pay_threshold = Int256::from(5);\nSETTING.get_payment_mut().close_threshold = Int256::from(-10);\n- SETTING.get_payment_mut().close_fraction = Int256::from(1_000_000_000);\n- SETTING.get_payment_mut().buffer_period = 1;\nlet mut d = DebtKeeper::new();\nlet ident = get_test_identity();\n" }, { "change_type": "MODIFY", "old_path": "settings/src/payment.rs", "new_path": "settings/src/payment.rs", "diff": "@@ -10,10 +10,6 @@ fn default_max_fee() -> u32 {\n20_000_000u32 // $3/gb at $150 eth\n}\n-fn default_close_fraction() -> Int256 {\n- 100.into()\n-}\n-\nfn default_close_threshold() -> Int256 {\n(-8400000000000000i64).into()\n}\n@@ -76,14 +72,9 @@ pub struct PaymentSettings {\n/// The threshold below which we will kick another node off (not implemented yet)\n#[serde(default = \"default_close_threshold\")]\npub close_threshold: Int256,\n- /// The amount of 'grace' to give a long term neighbor\n- #[serde(default = \"default_close_fraction\")]\n- pub close_fraction: Int256,\n/// The level of balance which will trigger a warning\n#[serde(default = \"default_balance_warning_level\")]\npub balance_warning_level: Uint256,\n- /// The amount of billing cycles a node can fall behind without being subjected to the threshold\n- pub buffer_period: u32,\n/// Our own eth private key we do not store address, instead it is derived from here\npub eth_private_key: Option<PrivateKey>,\n// Our own eth Address, derived from the private key on startup and not stored\n@@ -121,9 +112,7 @@ impl Default for PaymentSettings {\npay_threshold: 840_000_000_000_000i64.into(),\n// computed as 10x the pay threshold\nclose_threshold: (-8_400_000_000_000_000i64).into(),\n- close_fraction: 100.into(),\nbalance_warning_level: (10_000_000_000_000_000u64).into(),\n- buffer_period: 3,\neth_private_key: None,\neth_address: None,\nbalance: 0u64.into(),\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Dramatically simplify DebtKeeper
20,244
01.05.2019 15:02:00
14,400
05dc12bb41e4222d9ffee88fa39196d284f34743
Reduce log spam on the exits
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/debt_keeper/mod.rs", "new_path": "rita/src/rita_common/debt_keeper/mod.rs", "diff": "@@ -226,9 +226,10 @@ impl DebtKeeper {\n.to_int256()\n.ok_or_else(|| format_err!(\"Unable to convert amount to 256 bit signed integer\"))?;\nlet debt_data = self.get_debt_data_mut(ident);\n- println!(\n+ trace!(\n\"payment received: old incoming payments for {:?}: {:?}\",\n- ident.mesh_ip, debt_data.incoming_payments\n+ ident.mesh_ip,\n+ debt_data.incoming_payments\n);\n// just a counter, no convergence importance\n@@ -254,15 +255,16 @@ impl DebtKeeper {\n(false, _) => {}\n}\n- println!(\n+ trace!(\n\"new incoming payments for {:?}: {:?}\",\n- ident.mesh_ip, debt_data.incoming_payments\n+ ident.mesh_ip,\n+ debt_data.incoming_payments\n);\nOk(())\n}\nfn traffic_update(&mut self, ident: &Identity, amount: Int256) {\n- println!(\"traffic update for {} is {}\", ident.mesh_ip, amount);\n+ trace!(\"traffic update for {} is {}\", ident.mesh_ip, amount);\nlet debt_data = self.get_debt_data_mut(ident);\nassert!(debt_data.incoming_payments >= Int256::from(0));\n@@ -300,9 +302,10 @@ impl DebtKeeper {\nlet close_threshold = SETTING.get_payment().close_threshold.clone();\n- println!(\n+ trace!(\n\"Debt is {} and close is {}\",\n- debt_data.debt, close_threshold\n+ debt_data.debt,\n+ close_threshold\n);\n// negative debt means they owe us so when the debt is more negative than\n// the close treshold we should enforce.\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "@@ -186,7 +186,7 @@ impl PaymentController {\n// return emtpy result, we're using messages anyways\nOk(msg) => {\ninfo!(\n- \"Payment with txid: {:#066x} successful with {:?}, using full node {} and amound {:?}\",\n+ \"Payment with txid: {:#066x} successful with {:?}, using full node {} and amount {:?}\",\ntx_id, msg, full_node, pmt.amount\n);\nSETTING.get_payment_mut().nonce += 1u64.into();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -876,8 +876,10 @@ impl Handler<TunnelStateChange> for TunnelManager {\n}\n}\nNone => {\n- // TODO: This should probably return error\n- warn!(\"Couldn't find tunnel for identity {:?}\", msg.identity);\n+ // This is now pretty common since there's no more none action\n+ // and exits have identities for all clients (active or not)\n+ // on hand\n+ trace!(\"Couldn't find tunnel for identity {:?}\", msg.identity);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "@@ -144,9 +144,10 @@ fn counters_logging(counters: &HashMap<WgKey, WgUsage>) {\nlet mut total_in: u64 = 0;\nfor entry in counters.iter() {\n- info!(\n+ trace!(\n\"Exit accounted {} uploaded {} bytes\",\n- entry.0, entry.1.download\n+ entry.0,\n+ entry.1.download\n);\nlet input = entry.1;\ntotal_in += input.download;\n@@ -154,9 +155,10 @@ fn counters_logging(counters: &HashMap<WgKey, WgUsage>) {\ninfo!(\"Total Exit input of {} bytes this round\", total_in);\nlet mut total_out: u64 = 0;\nfor entry in counters.iter() {\n- info!(\n+ trace!(\n\"Exit accounted {} downloaded {} bytes\",\n- entry.0, entry.1.upload\n+ entry.0,\n+ entry.1.upload\n);\nlet output = entry.1;\ntotal_out += output.upload;\n@@ -298,7 +300,7 @@ pub fn watch<T: Read + Write>(\n},\n(Some(id), Some(_dest), None) => warn!(\"Entry for {:?} should have been created\", id),\n// this can be caused by a peer that has not yet formed a babel route\n- (Some(id), None, _) => warn!(\"We have an id {:?} but not destination\", id),\n+ (Some(id), None, _) => trace!(\"We have an id {:?} but not destination\", id),\n// if we have a babel route we should have a peer it's possible we have a mesh client sneaking in?\n(None, Some(dest), _) => warn!(\"We have a destination {:?} but no id\", dest),\n// dead entry?\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Reduce log spam on the exits
20,244
06.05.2019 11:10:36
14,400
190824d359cadbe198670ffb7649d2b5512505b8
Send credits directly to DebtKeeper Credit for payment was proxied for no good reason through payment_controller
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "//! so long as we have not published it to a full node, once the payment is on\n//! the blockchain it's up to the reciever to validate that it's correct\n-use crate::rita_common::debt_keeper;\nuse crate::rita_common::debt_keeper::DebtKeeper;\nuse crate::rita_common::debt_keeper::PaymentFailed;\nuse crate::rita_common::oracle::update_nonce;\n@@ -35,17 +34,6 @@ impl SystemService for PaymentController {\n}\n}\n-#[derive(Message)]\n-pub struct PaymentReceived(pub PaymentTx);\n-\n-impl Handler<PaymentReceived> for PaymentController {\n- type Result = ();\n-\n- fn handle(&mut self, msg: PaymentReceived, _: &mut Context<Self>) -> Self::Result {\n- DebtKeeper::from_registry().do_send(self.payment_received(msg.0).unwrap());\n- }\n-}\n-\n#[derive(Message)]\npub struct MakePayment(pub PaymentTx);\n@@ -74,26 +62,7 @@ impl PaymentController {\nPaymentController {}\n}\n- /// This gets called when a payment from a counterparty has arrived, and updates\n- /// the balance in memory and sends an update to the \"bounty hunter\".\n- pub fn payment_received(\n- &mut self,\n- pmt: PaymentTx,\n- ) -> Result<debt_keeper::PaymentReceived, Error> {\n- trace!(\n- \"payment of {:?} received from {:?}: {:?}\",\n- pmt.amount,\n- pmt.from.mesh_ip,\n- pmt\n- );\n-\n- Ok(debt_keeper::PaymentReceived {\n- from: pmt.from,\n- amount: pmt.amount.clone(),\n- })\n- }\n-\n- /// This is called by the other modules in Rita to make payments. It sends a\n+ /// This is called by debt_keeper to make payments. It sends a\n/// PaymentTx to the `mesh_ip` in its `to` field.\npub fn make_payment(&mut self, mut pmt: PaymentTx) -> Result<(), Error> {\nlet payment_settings = SETTING.get_payment();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_validator/mod.rs", "new_path": "rita/src/rita_common/payment_validator/mod.rs", "diff": "//! off to debt keeper to be removed from the owed balance. Payments may time out after a\n//! configured period.\n-use ::actix::prelude::*;\n-\n-use althea_types::PaymentTx;\n-\n-use std::time::{Duration, Instant};\n-\n-use web3::client::Web3;\n-\n-use settings::RitaCommonSettings;\n-\nuse crate::rita_common;\n-use crate::rita_common::payment_controller::PaymentController;\n+use crate::rita_common::debt_keeper::DebtKeeper;\nuse crate::rita_common::rita_loop::get_web3_server;\n-\n-use std::collections::HashSet;\n-\n-use futures::Future;\n-\nuse crate::SETTING;\n+use ::actix::{Actor, Arbiter, Context, Handler, Message, Supervised, SystemService};\n+use althea_types::PaymentTx;\n+use futures::Future;\n+use rita_common::debt_keeper::PaymentReceived;\n+use settings::RitaCommonSettings;\n+use std::collections::HashSet;\n+use std::time::{Duration, Instant};\n+use web3::client::Web3;\n// Discard payments after 30 minutes of failing to find txid\nconst PAYMENT_TIMEOUT: Duration = Duration::from_secs(1800u64);\n@@ -144,8 +137,10 @@ pub fn validate_transaction(ts: &ToValidate) {\n\"payment {:#066x} from {} successfully validated!\",\ntxid, from_address\n);\n- PaymentController::from_registry()\n- .do_send(rita_common::payment_controller::PaymentReceived(pmt));\n+ DebtKeeper::from_registry().do_send(PaymentReceived {\n+ from: pmt.from,\n+ amount: pmt.amount,\n+ });\nPaymentValidator::from_registry().do_send(Remove(long_life_ts));\n} else {\ntrace!(\"transaction is vaild but not in a block yet\");\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Send credits directly to DebtKeeper Credit for payment was proxied for no good reason through payment_controller
20,244
22.04.2019 16:15:19
14,400
4cf307c88672cd796f512954d0d1769e43831e4d
Add bandwidth and payments tracking features This adds the UsageTracker module, which will track both bandwidth usage and payments for graphing by the dashboard. Currently it is not persistant.
[ { "change_type": "MODIFY", "old_path": "rita/src/client.rs", "new_path": "rita/src/client.rs", "diff": "@@ -57,6 +57,7 @@ use crate::rita_client::dashboard::neighbors::*;\nuse crate::rita_client::dashboard::notifications::*;\nuse crate::rita_client::dashboard::system_chain::*;\nuse crate::rita_client::dashboard::update::*;\n+use crate::rita_client::dashboard::usage::*;\nuse crate::rita_client::dashboard::wifi::*;\nuse crate::rita_common::dashboard::babel::*;\n@@ -67,6 +68,7 @@ use crate::rita_common::dashboard::nickname::*;\nuse crate::rita_common::dashboard::own_info::*;\nuse crate::rita_common::dashboard::pricing::*;\nuse crate::rita_common::dashboard::settings::*;\n+use crate::rita_common::dashboard::usage::*;\nuse crate::rita_common::dashboard::wallet::*;\nuse crate::rita_common::network_endpoints::*;\n@@ -310,6 +312,9 @@ fn main() {\nMethod::POST,\nset_low_balance_notification,\n)\n+ .route(\"/usage/relay\", Method::GET, get_relay_usage)\n+ .route(\"/usage/client\", Method::GET, get_client_usage)\n+ .route(\"/usage/payments\", Method::GET, get_payments)\n.route(\"/router/update\", Method::POST, update_router)\n.route(\"/wipe\", Method::POST, wipe)\n.route(\"/crash_actors\", Method::POST, crash_actors)\n" }, { "change_type": "MODIFY", "old_path": "rita/src/exit.rs", "new_path": "rita/src/exit.rs", "diff": "@@ -53,6 +53,7 @@ use crate::rita_common::dashboard::nickname::*;\nuse crate::rita_common::dashboard::own_info::*;\nuse crate::rita_common::dashboard::pricing::*;\nuse crate::rita_common::dashboard::settings::*;\n+use crate::rita_common::dashboard::usage::*;\nuse crate::rita_common::dashboard::wallet::*;\nuse crate::rita_common::network_endpoints::*;\n@@ -262,6 +263,7 @@ fn main() {\n.route(\"/nickname/get/\", Method::GET, get_nickname)\n.route(\"/nickname/set/\", Method::POST, set_nickname)\n.route(\"/crash_actors\", Method::POST, crash_actors)\n+ .route(\"/usage/payments\", Method::GET, get_payments)\n})\n.bind(format!(\n\"[::0]:{}\",\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/mod.rs", "new_path": "rita/src/rita_client/dashboard/mod.rs", "diff": "@@ -13,4 +13,5 @@ pub mod neighbors;\npub mod notifications;\npub mod system_chain;\npub mod update;\n+pub mod usage;\npub mod wifi;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "rita/src/rita_client/dashboard/usage.rs", "diff": "+use crate::rita_common::usage_tracker::GetUsage;\n+use crate::rita_common::usage_tracker::UsageHour;\n+use crate::rita_common::usage_tracker::UsageTracker;\n+use crate::rita_common::usage_tracker::UsageType;\n+use ::actix::registry::SystemService;\n+use ::actix_web::{AsyncResponder, HttpRequest, Json};\n+use failure::Error;\n+use futures::Future;\n+use std::boxed::Box;\n+use std::collections::VecDeque;\n+\n+pub fn get_client_usage(\n+ _req: HttpRequest,\n+) -> Box<dyn Future<Item = Json<VecDeque<UsageHour>>, Error = Error>> {\n+ trace!(\"/usage/relay hit\");\n+ UsageTracker::from_registry()\n+ .send(GetUsage {\n+ kind: UsageType::Client,\n+ })\n+ .from_err()\n+ .and_then(move |reply| Ok(Json(reply?)))\n+ .responder()\n+}\n+\n+pub fn get_relay_usage(\n+ _req: HttpRequest,\n+) -> Box<dyn Future<Item = Json<VecDeque<UsageHour>>, Error = Error>> {\n+ trace!(\"/usage/relay hit\");\n+ UsageTracker::from_registry()\n+ .send(GetUsage {\n+ kind: UsageType::Relay,\n+ })\n+ .from_err()\n+ .and_then(move |reply| Ok(Json(reply?)))\n+ .responder()\n+}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/traffic_watcher/mod.rs", "new_path": "rita/src/rita_client/traffic_watcher/mod.rs", "diff": "//! must get paid for doing so.\nuse crate::rita_common::debt_keeper::{DebtKeeper, Traffic, TrafficUpdate};\n+use crate::rita_common::usage_tracker::UpdateUsage;\n+use crate::rita_common::usage_tracker::UsageTracker;\n+use crate::rita_common::usage_tracker::UsageType;\nuse crate::KI;\nuse crate::SETTING;\nuse ::actix::prelude::{Actor, Context, Handler, Message, Supervised, SystemService};\n@@ -174,8 +177,16 @@ pub fn watch(history: &mut TrafficWatcher, exit: &Identity, exit_price: u64) ->\n};\nDebtKeeper::from_registry().do_send(exit_update);\n+\n+ // update the usage tracker with the details of this round's usage\n+ UsageTracker::from_registry().do_send(UpdateUsage {\n+ kind: UsageType::Client,\n+ up: output,\n+ down: input,\n+ price: exit_dest_price as u32,\n+ });\n} else {\n- trace!(\"Exit bandwidth did not exceed free tier, no bill\");\n+ error!(\"no Exit bandwidth, no bill!\");\n}\nOk(())\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/mod.rs", "new_path": "rita/src/rita_common/dashboard/mod.rs", "diff": "@@ -13,6 +13,7 @@ pub mod nickname;\npub mod own_info;\npub mod pricing;\npub mod settings;\n+pub mod usage;\npub mod wallet;\npub struct Dashboard;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "rita/src/rita_common/dashboard/usage.rs", "diff": "+use crate::rita_common::usage_tracker::GetPayments;\n+use crate::rita_common::usage_tracker::PaymentHour;\n+use crate::rita_common::usage_tracker::UsageTracker;\n+use ::actix::registry::SystemService;\n+use ::actix_web::{AsyncResponder, HttpRequest, Json};\n+use failure::Error;\n+use futures::Future;\n+use std::boxed::Box;\n+use std::collections::VecDeque;\n+\n+pub fn get_payments(\n+ _req: HttpRequest,\n+) -> Box<dyn Future<Item = Json<VecDeque<PaymentHour>>, Error = Error>> {\n+ trace!(\"/usage/relay hit\");\n+ UsageTracker::from_registry()\n+ .send(GetPayments {})\n+ .from_err()\n+ .and_then(move |reply| Ok(Json(reply?)))\n+ .responder()\n+}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/mod.rs", "new_path": "rita/src/rita_common/mod.rs", "diff": "@@ -10,3 +10,4 @@ pub mod peer_listener;\npub mod rita_loop;\npub mod traffic_watcher;\npub mod tunnel_manager;\n+pub mod usage_tracker;\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "@@ -7,6 +7,8 @@ use crate::rita_common::debt_keeper::DebtKeeper;\nuse crate::rita_common::debt_keeper::PaymentFailed;\nuse crate::rita_common::oracle::update_nonce;\nuse crate::rita_common::rita_loop::get_web3_server;\n+use crate::rita_common::usage_tracker::UpdatePayments;\n+use crate::rita_common::usage_tracker::UsageTracker;\nuse crate::SETTING;\nuse ::actix::prelude::{Actor, Arbiter, Context, Handler, Message, Supervised, SystemService};\nuse ::actix_web::client;\n@@ -159,6 +161,11 @@ impl PaymentController {\ntx_id, msg, full_node, pmt.amount\n);\nSETTING.get_payment_mut().nonce += 1u64.into();\n+\n+ // update the usage tracker with the details of this payment\n+ UsageTracker::from_registry()\n+ .do_send(UpdatePayments { payment: pmt });\n+\nOk(()) as Result<(), ()>\n}\nErr(e) => {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/traffic_watcher/mod.rs", "new_path": "rita/src/rita_common/traffic_watcher/mod.rs", "diff": "//! iptables and ipset counters on each per hop tunnel (the WireGuard tunnel between two devices). These counts\n//! are then stored and used to compute amounts for bills.\n+use crate::rita_common::debt_keeper;\n+use crate::rita_common::debt_keeper::DebtKeeper;\n+use crate::rita_common::debt_keeper::Traffic;\nuse crate::rita_common::tunnel_manager::Neighbor;\n-use ::actix::prelude::*;\n-\n+use crate::rita_common::usage_tracker::UpdateUsage;\n+use crate::rita_common::usage_tracker::UsageTracker;\n+use crate::rita_common::usage_tracker::UsageType;\nuse crate::KI;\n+use crate::SETTING;\n+use ::actix::{Actor, Context, Handler, Message, Supervised, SystemService};\nuse althea_kernel_interface::FilterTarget;\n-\nuse althea_types::Identity;\n-\nuse babel_monitor::Babel;\n-\n-use crate::rita_common::debt_keeper;\n-use crate::rita_common::debt_keeper::DebtKeeper;\n-use crate::rita_common::debt_keeper::Traffic;\n-\n+use failure::Error;\n+use ipnetwork::IpNetwork;\n+use settings::RitaCommonSettings;\nuse std::collections::HashMap;\nuse std::io::{Read, Write};\nuse std::net::{IpAddr, SocketAddr, TcpStream};\n-use ipnetwork::IpNetwork;\n-\n-use crate::SETTING;\n-use settings::RitaCommonSettings;\n-\n-use failure::Error;\n-\npub struct TrafficWatcher;\nimpl Actor for TrafficWatcher {\n@@ -232,6 +227,34 @@ pub fn get_output_counters() -> Result<HashMap<(IpAddr, String), u64>, Error> {\nOk(total_output_counters)\n}\n+/// Takes and sumns the input and output counters for logging\n+fn update_usage(\n+ input: &HashMap<(IpAddr, String), u64>,\n+ output: &HashMap<(IpAddr, String), u64>,\n+ our_fee: u32,\n+) {\n+ let mut total_in = 0;\n+ let mut total_out = 0;\n+ for (_, count) in input.iter() {\n+ total_in += count;\n+ }\n+ for (_, count) in output.iter() {\n+ total_out += count;\n+ }\n+ info!(\n+ \"Total of {} bytes relay upload and {} bytes relay download\",\n+ total_out, total_in\n+ );\n+\n+ // update the usage tracker with the details of this round's usage\n+ UsageTracker::from_registry().do_send(UpdateUsage {\n+ kind: UsageType::Relay,\n+ up: total_out,\n+ down: total_in,\n+ price: our_fee,\n+ });\n+}\n+\n/// This traffic watcher watches how much traffic each neighbor sends to each destination\n/// between the last time watch was run, (This does _not_ block the thread)\n/// It also gathers the price to each destination from Babel and uses this information\n@@ -246,6 +269,7 @@ pub fn watch<T: Read + Write>(babel: Babel<T>, neighbors: &[Neighbor]) -> Result\nlet total_input_counters = get_input_counters()?;\nlet total_output_counters = get_output_counters()?;\n+ update_usage(&total_input_counters, &total_output_counters, local_fee);\n// Flow counters should debit your neighbor which you received the packet from\n// Destination counters should credit your neighbor which you sent the packet to\n" }, { "change_type": "ADD", "old_path": null, "new_path": "rita/src/rita_common/usage_tracker/mod.rs", "diff": "+//! Collects messages from the various traffic watchers to allow the creation of graphs about\n+//! usage. Within each traffic watcher a simple message containing the amount of bandwidth used\n+//! in that round and exactly what type of bandwidth it is is sent to this module, from there\n+//! the handler updates the storage to reflect the new total. When a user would like to inspect\n+//! or graph usage they query an endpoint which will request the data from this module.\n+//!\n+//! Persistant storage is planned but not currently implemented.\n+\n+use actix::Actor;\n+use actix::Context;\n+use actix::Handler;\n+use actix::Message;\n+use actix::Supervised;\n+use actix::SystemService;\n+use althea_types::PaymentTx;\n+use failure::Error;\n+use std::collections::VecDeque;\n+use std::time::SystemTime;\n+use std::time::UNIX_EPOCH;\n+\n+/// On year worth of usage storage\n+const MAX_ENTRIES: usize = 8760;\n+\n+/// In an effort to converge this module between the three possible bw tracking\n+/// use cases this enum is used to identify which sort of usage we are tracking\n+#[derive(Clone, Copy, Debug)]\n+#[allow(dead_code)]\n+pub enum UsageType {\n+ Client,\n+ Relay,\n+ Exit,\n+}\n+\n+/// A struct for tracking each hour of usage, indexed by time in hours since\n+/// the unix epoch\n+#[derive(Clone, Copy, Debug, Serialize)]\n+pub struct UsageHour {\n+ index: u64,\n+ up: u64,\n+ down: u64,\n+ price: u32,\n+}\n+\n+/// A struct for tracking each hours of paymetns indexed in hours since unix epoch\n+#[derive(Clone, Debug, Serialize)]\n+pub struct PaymentHour {\n+ index: u64,\n+ payments: Vec<PaymentTx>,\n+}\n+\n+/// The main actor that holds the usage state for the duration of operations\n+/// at some point loading and saving will be defined in service started\n+#[derive(Default, Clone, Debug, Serialize)]\n+pub struct UsageTracker {\n+ // at least one of these will be left unused\n+ client_bandwith: VecDeque<UsageHour>,\n+ relay_bandwith: VecDeque<UsageHour>,\n+ exit_bandwith: VecDeque<UsageHour>,\n+ /// A history of txid's\n+ payments: VecDeque<PaymentHour>,\n+}\n+\n+impl Actor for UsageTracker {\n+ type Context = Context<Self>;\n+}\n+\n+impl Supervised for UsageTracker {}\n+impl SystemService for UsageTracker {\n+ fn service_started(&mut self, _ctx: &mut Context<Self>) {\n+ info!(\"UsageTracker started\");\n+ }\n+}\n+\n+/// Gets the current hour since the unix epoch\n+fn get_current_hour() -> Result<u64, Error> {\n+ let seconds = SystemTime::now().duration_since(UNIX_EPOCH)?;\n+ Ok(seconds.as_secs() / (60 * 60))\n+}\n+\n+/// The messauge used to update the current usage hour from each traffic\n+/// watcher module\n+#[derive(Clone, Copy, Debug)]\n+pub struct UpdateUsage {\n+ pub kind: UsageType,\n+ pub up: u64,\n+ pub down: u64,\n+ pub price: u32,\n+}\n+\n+impl Message for UpdateUsage {\n+ type Result = Result<(), Error>;\n+}\n+\n+impl Handler<UpdateUsage> for UsageTracker {\n+ type Result = Result<(), Error>;\n+ fn handle(&mut self, msg: UpdateUsage, _: &mut Context<Self>) -> Self::Result {\n+ let current_hour = match get_current_hour() {\n+ Ok(hour) => hour,\n+ Err(e) => {\n+ error!(\"System time is set earlier than unix epoch! {:?}\", e);\n+ return Ok(());\n+ }\n+ };\n+ process_usage_update(current_hour, msg, self);\n+\n+ Ok(())\n+ }\n+}\n+\n+fn process_usage_update(current_hour: u64, msg: UpdateUsage, data: &mut UsageTracker) {\n+ // history contains a reference to whatever the correct storage array is\n+ let history = match msg.kind {\n+ UsageType::Client => &mut data.client_bandwith,\n+ UsageType::Relay => &mut data.relay_bandwith,\n+ UsageType::Exit => &mut data.exit_bandwith,\n+ };\n+ // we grab the front entry from the VecDeque, if there is an entry one we check if it's\n+ // up to date, if it is we add to it, if it's not or there is no entry we create one.\n+ // note that price is only sampled once per hour.\n+ match history.front_mut() {\n+ None => history.push_front(UsageHour {\n+ index: current_hour,\n+ up: msg.up,\n+ down: msg.down,\n+ price: msg.price,\n+ }),\n+ Some(entry) => {\n+ if entry.index == current_hour {\n+ entry.up += msg.up;\n+ entry.down += msg.down;\n+ } else {\n+ history.push_front(UsageHour {\n+ index: current_hour,\n+ up: msg.up,\n+ down: msg.down,\n+ price: msg.price,\n+ })\n+ }\n+ }\n+ }\n+ while history.len() > MAX_ENTRIES {\n+ let _discarded_entry = history.pop_back();\n+ }\n+}\n+\n+pub struct UpdatePayments {\n+ pub payment: PaymentTx,\n+}\n+\n+impl Message for UpdatePayments {\n+ type Result = Result<(), Error>;\n+}\n+\n+impl Handler<UpdatePayments> for UsageTracker {\n+ type Result = Result<(), Error>;\n+ fn handle(&mut self, msg: UpdatePayments, _: &mut Context<Self>) -> Self::Result {\n+ let current_hour = match get_current_hour() {\n+ Ok(hour) => hour,\n+ Err(e) => {\n+ error!(\"System time is set earlier than unix epoch! {:?}\", e);\n+ return Ok(());\n+ }\n+ };\n+ match self.payments.front_mut() {\n+ None => self.payments.push_front(PaymentHour {\n+ index: current_hour,\n+ payments: vec![msg.payment],\n+ }),\n+ Some(entry) => {\n+ if entry.index == current_hour {\n+ entry.payments.push(msg.payment);\n+ } else {\n+ self.payments.push_front(PaymentHour {\n+ index: current_hour,\n+ payments: vec![msg.payment],\n+ })\n+ }\n+ }\n+ }\n+ while self.payments.len() > MAX_ENTRIES {\n+ let _discarded_entry = self.payments.pop_back();\n+ }\n+ Ok(())\n+ }\n+}\n+\n+pub struct GetUsage {\n+ pub kind: UsageType,\n+}\n+\n+impl Message for GetUsage {\n+ type Result = Result<VecDeque<UsageHour>, Error>;\n+}\n+\n+impl Handler<GetUsage> for UsageTracker {\n+ type Result = Result<VecDeque<UsageHour>, Error>;\n+ fn handle(&mut self, msg: GetUsage, _: &mut Context<Self>) -> Self::Result {\n+ match msg.kind {\n+ UsageType::Client => Ok(self.client_bandwith.clone()),\n+ UsageType::Relay => Ok(self.relay_bandwith.clone()),\n+ UsageType::Exit => Ok(self.exit_bandwith.clone()),\n+ }\n+ }\n+}\n+\n+pub struct GetPayments;\n+\n+impl Message for GetPayments {\n+ type Result = Result<VecDeque<PaymentHour>, Error>;\n+}\n+\n+impl Handler<GetPayments> for UsageTracker {\n+ type Result = Result<VecDeque<PaymentHour>, Error>;\n+ fn handle(&mut self, _msg: GetPayments, _: &mut Context<Self>) -> Self::Result {\n+ Ok(self.payments.clone())\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "use crate::rita_common::debt_keeper;\nuse crate::rita_common::debt_keeper::DebtKeeper;\nuse crate::rita_common::debt_keeper::Traffic;\n+use crate::rita_common::usage_tracker::UpdateUsage;\n+use crate::rita_common::usage_tracker::UsageTracker;\n+use crate::rita_common::usage_tracker::UsageType;\nuse crate::SETTING;\nuse ::actix::prelude::{Actor, Context, Handler, Message, Supervised, SystemService};\nuse althea_kernel_interface::wg_iface_counter::WgUsage;\n@@ -139,7 +142,7 @@ fn generate_helper_maps(\nOk((identities, id_from_ip))\n}\n-fn counters_logging(counters: &HashMap<WgKey, WgUsage>) {\n+fn counters_logging(counters: &HashMap<WgKey, WgUsage>, exit_fee: u32) {\ntrace!(\"exit counters: {:?}\", counters);\nlet mut total_in: u64 = 0;\n@@ -163,6 +166,15 @@ fn counters_logging(counters: &HashMap<WgKey, WgUsage>) {\nlet output = entry.1;\ntotal_out += output.upload;\n}\n+\n+ // update the usage tracker with the details of this round's usage\n+ UsageTracker::from_registry().do_send(UpdateUsage {\n+ kind: UsageType::Exit,\n+ up: total_out,\n+ down: total_in,\n+ price: exit_fee,\n+ });\n+\ninfo!(\"Total Exit output of {} bytes this round\", total_out);\n}\n@@ -237,7 +249,8 @@ pub fn watch<T: Read + Write>(\nreturn Err(e);\n}\n};\n- counters_logging(&counters);\n+\n+ counters_logging(&counters, our_price as u32);\n// creates new usage entires does not actualy update the values\nupdate_usage_history(&counters, usage_history);\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add bandwidth and payments tracking features This adds the UsageTracker module, which will track both bandwidth usage and payments for graphing by the dashboard. Currently it is not persistant.
20,244
22.04.2019 16:44:58
14,400
26aeff3e781ac31cdc57fade99b00ad8760920df
Add documentation for tracking endpoints
[ { "change_type": "MODIFY", "old_path": "docs/api/router-dashboard.md", "new_path": "docs/api/router-dashboard.md", "diff": "@@ -1271,3 +1271,78 @@ Manually runs the update script\n`curl -v -XPOST http://192.168.10.1:4877/router/update`\n---\n+\n+## /usage/client\n+\n+Gets a history of client bandwidth usage, index is in hours since unix epoch, the first being\n+the latest, up and down are in bytes, and the price is in wei/gb\n+\n+- URL: `<rita ip>:<rita_dashboard_port>/usage/client`\n+- Method: `GET`\n+- URL Params: `None`\n+- Data Params: `None`\n+- Success Response:\n+ - Code: 200 OK\n+ - Contents:\n+\n+```\n+[{\"index\":432212,\"up\":154040,\"down\":433480,\"price\":71400000}, ...]\n+```\n+\n+- Error Response: `500 Server Error`\n+\n+- Sample Call:\n+\n+`curl -v -XGET http://192.168.10.1:4877/usage/client`\n+\n+---\n+\n+## /usage/relay\n+\n+Gets a history of relay bandwidth usage, index is in hours since unix epoch, the first being\n+the latest, up and down are in bytes, and the price is in wei/gb\n+\n+- URL: `<rita ip>:<rita_dashboard_port>/usage/relay`\n+- Method: `GET`\n+- URL Params: `None`\n+- Data Params: `None`\n+- Success Response:\n+ - Code: 200 OK\n+ - Contents:\n+\n+```\n+[{\"index\":432212,\"up\":154040,\"down\":433480,\"price\":71400000}, ...]\n+```\n+\n+- Error Response: `500 Server Error`\n+\n+- Sample Call:\n+\n+`curl -v -XGET http://192.168.10.1:4877/usage/relay`\n+\n+---\n+\n+## /usage/payments\n+\n+Gets a history of payments, indexes are hours since unix epoch the first being the latest\n+amounts are in wei\n+\n+- URL: `<rita ip>:<rita_dashboard_port>/usage/payments`\n+- Method: `GET`\n+- URL Params: `None`\n+- Data Params: `None`\n+- Success Response:\n+ - Code: 200 OK\n+ - Contents:\n+\n+```\n+[{\"index\":432212,\"payments\":[{\"to\":{\"mesh_ip\":\"fd00::1337:1e0f\",\"eth_address\":\"0x5aee3dff733f56cfe7e5390b9cc3a46a90ca1cfa\",\"wg_public_key\":\"zgAlhyOQy8crB0ewrsWt3ES9SvFguwx5mq9i2KiknmA=\",\"nickname\":null},\"from\":{\"mesh_ip\":\"fd3f:fd20:e900:4e94:a638:f99b:b7f7:6ec0\",\"eth_address\":\"0xbda3c7fa35896de7fa3e3591b44b44baaa3e3bc1\",\"wg_public_key\":\"+/JmQoUnJeKoWb/cmXGBal6J/TtAQpEDL9hCD1fSSiY=\",\"nickname\":null},\"amount\":\"1691124136800000\",\"txid\":\"1180495127369290936054714943770774396461041662226307173060896507466108779575\"}, ...]}]\n+```\n+\n+- Error Response: `500 Server Error`\n+\n+- Sample Call:\n+\n+`curl -v -XGET http://192.168.10.1:4877/usage/payments`\n+\n+---\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add documentation for tracking endpoints
20,244
23.04.2019 07:47:57
14,400
9193ab4b977b2cde6aa9c95f4e02886ba8e03cca
Format txid's correctly while uint256 is an accurate representaiton of a txid it requires nontrivial formatting to be usefull, especially if you want to submit it to a full node. This replaces the stored payments with their own struct which provides txid's in a properly readable format.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/usage.rs", "new_path": "rita/src/rita_client/dashboard/usage.rs", "diff": "@@ -18,7 +18,7 @@ pub fn get_client_usage(\nkind: UsageType::Client,\n})\n.from_err()\n- .and_then(move |reply| Ok(Json(reply?)))\n+ .and_then(|reply| Ok(Json(reply?)))\n.responder()\n}\n@@ -31,6 +31,6 @@ pub fn get_relay_usage(\nkind: UsageType::Relay,\n})\n.from_err()\n- .and_then(move |reply| Ok(Json(reply?)))\n+ .and_then(|reply| Ok(Json(reply?)))\n.responder()\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/usage.rs", "new_path": "rita/src/rita_common/dashboard/usage.rs", "diff": "@@ -15,6 +15,6 @@ pub fn get_payments(\nUsageTracker::from_registry()\n.send(GetPayments {})\n.from_err()\n- .and_then(move |reply| Ok(Json(reply?)))\n+ .and_then(|reply| Ok(Json(reply?)))\n.responder()\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/usage_tracker/mod.rs", "new_path": "rita/src/rita_common/usage_tracker/mod.rs", "diff": "@@ -12,8 +12,10 @@ use actix::Handler;\nuse actix::Message;\nuse actix::Supervised;\nuse actix::SystemService;\n+use althea_types::Identity;\nuse althea_types::PaymentTx;\nuse failure::Error;\n+use num256::Uint256;\nuse std::collections::VecDeque;\nuse std::time::SystemTime;\nuse std::time::UNIX_EPOCH;\n@@ -41,11 +43,39 @@ pub struct UsageHour {\nprice: u32,\n}\n+/// A version of payment tx with a string txid so that the formatting is correct\n+/// for display to users.\n+#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)]\n+pub struct FormattedPaymentTx {\n+ pub to: Identity,\n+ pub from: Identity,\n+ pub amount: Uint256,\n+ // should always be populated in this case\n+ pub txid: String,\n+}\n+\n+fn to_formatted_payment_tx(input: PaymentTx) -> FormattedPaymentTx {\n+ match input.txid {\n+ Some(txid) => FormattedPaymentTx {\n+ to: input.to,\n+ from: input.from,\n+ amount: input.amount,\n+ txid: format!(\"{:#066x}\", txid),\n+ },\n+ None => FormattedPaymentTx {\n+ to: input.to,\n+ from: input.from,\n+ amount: input.amount,\n+ txid: String::new(),\n+ },\n+ }\n+}\n+\n/// A struct for tracking each hours of paymetns indexed in hours since unix epoch\n#[derive(Clone, Debug, Serialize)]\npub struct PaymentHour {\nindex: u64,\n- payments: Vec<PaymentTx>,\n+ payments: Vec<FormattedPaymentTx>,\n}\n/// The main actor that holds the usage state for the duration of operations\n@@ -161,18 +191,19 @@ impl Handler<UpdatePayments> for UsageTracker {\nreturn Ok(());\n}\n};\n+ let formatted_payment = to_formatted_payment_tx(msg.payment);\nmatch self.payments.front_mut() {\nNone => self.payments.push_front(PaymentHour {\nindex: current_hour,\n- payments: vec![msg.payment],\n+ payments: vec![formatted_payment],\n}),\nSome(entry) => {\nif entry.index == current_hour {\n- entry.payments.push(msg.payment);\n+ entry.payments.push(formatted_payment);\n} else {\nself.payments.push_front(PaymentHour {\nindex: current_hour,\n- payments: vec![msg.payment],\n+ payments: vec![formatted_payment],\n})\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Format txid's correctly while uint256 is an accurate representaiton of a txid it requires nontrivial formatting to be usefull, especially if you want to submit it to a full node. This replaces the stored payments with their own struct which provides txid's in a properly readable format.
20,244
23.04.2019 10:10:54
14,400
27bfb3a2fd532b8aee4a59309bb95e8e2b365127
Add persistance for usage history
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/usage_tracker/mod.rs", "new_path": "rita/src/rita_common/usage_tracker/mod.rs", "diff": "//!\n//! Persistant storage is planned but not currently implemented.\n+use crate::SETTING;\nuse actix::Actor;\nuse actix::Context;\nuse actix::Handler;\n@@ -16,16 +17,25 @@ use althea_types::Identity;\nuse althea_types::PaymentTx;\nuse failure::Error;\nuse num256::Uint256;\n+use serde::{Deserialize, Serialize};\n+use serde_json::Error as SerdeError;\n+use settings::RitaCommonSettings;\nuse std::collections::VecDeque;\n+use std::fs::File;\n+use std::io::Error as IOError;\n+use std::io::Read;\n+use std::io::Write;\nuse std::time::SystemTime;\nuse std::time::UNIX_EPOCH;\n/// On year worth of usage storage\nconst MAX_ENTRIES: usize = 8760;\n+/// Save every 24 hours\n+const SAVE_FREQENCY: u64 = 24;\n/// In an effort to converge this module between the three possible bw tracking\n/// use cases this enum is used to identify which sort of usage we are tracking\n-#[derive(Clone, Copy, Debug)]\n+#[derive(Clone, Copy, Debug, Serialize, Deserialize)]\n#[allow(dead_code)]\npub enum UsageType {\nClient,\n@@ -35,7 +45,7 @@ pub enum UsageType {\n/// A struct for tracking each hour of usage, indexed by time in hours since\n/// the unix epoch\n-#[derive(Clone, Copy, Debug, Serialize)]\n+#[derive(Clone, Copy, Debug, Serialize, Deserialize)]\npub struct UsageHour {\nindex: u64,\nup: u64,\n@@ -72,7 +82,7 @@ fn to_formatted_payment_tx(input: PaymentTx) -> FormattedPaymentTx {\n}\n/// A struct for tracking each hours of paymetns indexed in hours since unix epoch\n-#[derive(Clone, Debug, Serialize)]\n+#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct PaymentHour {\nindex: u64,\npayments: Vec<FormattedPaymentTx>,\n@@ -80,16 +90,67 @@ pub struct PaymentHour {\n/// The main actor that holds the usage state for the duration of operations\n/// at some point loading and saving will be defined in service started\n-#[derive(Default, Clone, Debug, Serialize)]\n+#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct UsageTracker {\n+ last_save_hour: u64,\n// at least one of these will be left unused\nclient_bandwith: VecDeque<UsageHour>,\nrelay_bandwith: VecDeque<UsageHour>,\nexit_bandwith: VecDeque<UsageHour>,\n- /// A history of txid's\n+ /// A history of payments\npayments: VecDeque<PaymentHour>,\n}\n+impl Default for UsageTracker {\n+ fn default() -> UsageTracker {\n+ let file = File::open(SETTING.get_network().usage_tracker_file.clone());\n+ // if the loading process goes wrong for any reason, we just start again\n+ let blank_usage_tracker = UsageTracker {\n+ last_save_hour: 0,\n+ client_bandwith: VecDeque::new(),\n+ relay_bandwith: VecDeque::new(),\n+ exit_bandwith: VecDeque::new(),\n+ payments: VecDeque::new(),\n+ };\n+\n+ match file {\n+ Ok(mut file) => {\n+ let mut contents = String::new();\n+ match file.read_to_string(&mut contents) {\n+ Ok(_bytes_read) => {\n+ let deserialized: Result<UsageTracker, SerdeError> =\n+ serde_json::from_str(&contents);\n+\n+ match deserialized {\n+ Ok(value) => value,\n+ Err(e) => {\n+ error!(\"Failed to deserialize usage tracker {:?}\", e);\n+ blank_usage_tracker\n+ }\n+ }\n+ }\n+ Err(e) => {\n+ error!(\"Failed to read usage tracker file! {:?}\", e);\n+ blank_usage_tracker\n+ }\n+ }\n+ }\n+ Err(e) => {\n+ error!(\"Failed to open usage tracker file! {:?}\", e);\n+ blank_usage_tracker\n+ }\n+ }\n+ }\n+}\n+\n+impl UsageTracker {\n+ fn save(&mut self) -> Result<(), IOError> {\n+ let serialized = serde_json::to_string(self)?;\n+ let mut file = File::create(SETTING.get_network().usage_tracker_file.clone())?;\n+ file.write_all(serialized.as_bytes())\n+ }\n+}\n+\nimpl Actor for UsageTracker {\ntype Context = Context<Self>;\n}\n@@ -171,6 +232,11 @@ fn process_usage_update(current_hour: u64, msg: UpdateUsage, data: &mut UsageTra\nwhile history.len() > MAX_ENTRIES {\nlet _discarded_entry = history.pop_back();\n}\n+ if (current_hour - SAVE_FREQENCY) > data.last_save_hour {\n+ data.last_save_hour = current_hour;\n+ let res = data.save();\n+ info!(\"Saving usage data: {:?}\", res);\n+ }\n}\npub struct UpdatePayments {\n@@ -211,6 +277,11 @@ impl Handler<UpdatePayments> for UsageTracker {\nwhile self.payments.len() > MAX_ENTRIES {\nlet _discarded_entry = self.payments.pop_back();\n}\n+ if (current_hour - SAVE_FREQENCY) > self.last_save_hour {\n+ self.last_save_hour = current_hour;\n+ let res = self.save();\n+ info!(\"Saving usage data: {:?}\", res);\n+ }\nOk(())\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "settings/src/network.rs", "new_path": "settings/src/network.rs", "diff": "@@ -18,6 +18,10 @@ fn default_metric_factor() -> u32 {\n1_900u32\n}\n+fn default_usage_tracker_file() -> String {\n+ \"/var/rita-usage-tracker.json\".to_string()\n+}\n+\n#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]\npub struct NetworkSettings {\n/// How much non-financial metrics matter compared to a route's cost. By default a 2x more\n@@ -83,6 +87,9 @@ pub struct NetworkSettings {\n/// Nickname of the device on the network\n#[serde(skip_serializing_if = \"Option::is_none\")]\npub nickname: Option<ArrayString<[u8; 32]>>,\n+ /// Full file path for usage tracker storage\n+ #[serde(default = \"default_usage_tracker_file\")]\n+ pub usage_tracker_file: String,\n}\nimpl Default for NetworkSettings {\n@@ -110,6 +117,7 @@ impl Default for NetworkSettings {\ntunnel_timeout_seconds: default_tunnel_timeout(),\ndevice: None,\nnickname: None,\n+ usage_tracker_file: default_usage_tracker_file(),\n}\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add persistance for usage history
20,244
29.04.2019 14:35:10
14,400
066fcff8a858524bdb0218546a2e33e5ee656b2e
Track dao paymetns too
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dao_manager/mod.rs", "new_path": "rita/src/rita_common/dao_manager/mod.rs", "diff": "//! to compute the amount it should pay at a time, these micropayments have the effect of pro-rating\n//! the DAO fee amount and preventing the router from drastically making a large payment\n+use crate::rita_common::usage_tracker::UpdatePayments;\n+use crate::rita_common::usage_tracker::UsageTracker;\nuse crate::SETTING;\nuse ::actix::{Actor, Arbiter, Context, Handler, Message, Supervised, SystemService};\n+use althea_types::Identity;\n+use althea_types::PaymentTx;\nuse clarity::Transaction;\nuse futures::future::Future;\nuse num256::Int256;\n@@ -58,6 +62,7 @@ impl Handler<Tick> for DAOManager {\nlet dao_settings = SETTING.get_dao();\nlet payment_settings = SETTING.get_payment();\nlet eth_private_key = payment_settings.eth_private_key;\n+ let our_id = SETTING.get_identity().unwrap();\nlet gas_price = payment_settings.gas_price.clone();\nlet nonce = payment_settings.nonce.clone();\nlet pay_threshold = payment_settings.pay_threshold.clone();\n@@ -70,6 +75,16 @@ impl Handler<Tick> for DAOManager {\nif we_have_a_dao && should_pay {\n// pay all the daos on the list at once\nfor address in dao_addresses {\n+ let amount_to_pay = pay_threshold.abs().to_uint256().unwrap().clone();\n+ let dao_identity = Identity {\n+ eth_address: address,\n+ wg_public_key: \"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF=\"\n+ .parse()\n+ .unwrap(),\n+ mesh_ip: \"::1\".parse().unwrap(),\n+ nickname: None,\n+ };\n+\nlet full_node = get_web3_server();\nlet web3 = Web3::new(&full_node);\n@@ -78,7 +93,7 @@ impl Handler<Tick> for DAOManager {\ngas_price: gas_price.clone(),\ngas_limit: \"21000\".parse().unwrap(),\nto: address,\n- value: pay_threshold.abs().to_uint256().unwrap(),\n+ value: amount_to_pay.clone(),\ndata: Vec::new(),\nsignature: None,\n};\n@@ -96,8 +111,27 @@ impl Handler<Tick> for DAOManager {\n};\nlet transaction_status = web3.eth_send_raw_transaction(transaction_bytes);\n- // in theory this may fail, for now we will just underpay when that occurs\n- Arbiter::spawn(transaction_status.then(|_res| Ok(())));\n+\n+ // in theory this may fail, for now there is no handler and\n+ // we will just underpay when that occurs\n+ Arbiter::spawn(transaction_status.then(move |res| match res {\n+ Ok(txid) => {\n+ info!(\"Successfully paid the subnet dao!\");\n+ UsageTracker::from_registry().do_send(UpdatePayments {\n+ payment: PaymentTx {\n+ to: dao_identity,\n+ from: our_id,\n+ amount: amount_to_pay,\n+ txid: Some(txid),\n+ },\n+ });\n+ Ok(())\n+ }\n+ Err(e) => {\n+ warn!(\"Failed to pay subnet dao! {:?}\", e);\n+ Ok(())\n+ }\n+ }));\n}\nself.last_payment_time = Instant::now();\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Track dao paymetns too
20,244
29.04.2019 14:38:48
14,400
aea8a2c4bcb63683ad993caedf4db60bc9538170
No non-verifiable unwraps in dao_manager
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dao_manager/mod.rs", "new_path": "rita/src/rita_common/dao_manager/mod.rs", "diff": "@@ -62,12 +62,18 @@ impl Handler<Tick> for DAOManager {\nlet dao_settings = SETTING.get_dao();\nlet payment_settings = SETTING.get_payment();\nlet eth_private_key = payment_settings.eth_private_key;\n- let our_id = SETTING.get_identity().unwrap();\n+ let our_id = match SETTING.get_identity() {\n+ Some(id) => id,\n+ None => return,\n+ };\nlet gas_price = payment_settings.gas_price.clone();\nlet nonce = payment_settings.nonce.clone();\nlet pay_threshold = payment_settings.pay_threshold.clone();\nlet dao_addresses = dao_settings.dao_addresses.clone();\n- let dao_fee = dao_settings.dao_fee.to_int256().unwrap();\n+ let dao_fee = match dao_settings.dao_fee.to_int256() {\n+ Some(val) => val,\n+ None => return,\n+ };\nlet we_have_a_dao = !dao_addresses.is_empty();\nlet should_pay =\n(Int256::from(self.last_payment_time.elapsed().as_secs()) * dao_fee) > pay_threshold;\n@@ -75,7 +81,11 @@ impl Handler<Tick> for DAOManager {\nif we_have_a_dao && should_pay {\n// pay all the daos on the list at once\nfor address in dao_addresses {\n- let amount_to_pay = pay_threshold.abs().to_uint256().unwrap().clone();\n+ let amount_to_pay = match pay_threshold.abs().to_uint256().clone() {\n+ Some(val) => val,\n+ None => return,\n+ };\n+\nlet dao_identity = Identity {\neth_address: address,\nwg_public_key: \"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF=\"\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
No non-verifiable unwraps in dao_manager
20,244
06.05.2019 10:38:04
14,400
0102890019946f6c1a33b17d0fdfe1445c3cc12f
Track recieved payments too
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_validator/mod.rs", "new_path": "rita/src/rita_common/payment_validator/mod.rs", "diff": "use crate::rita_common;\nuse crate::rita_common::debt_keeper::DebtKeeper;\nuse crate::rita_common::rita_loop::get_web3_server;\n+use crate::rita_common::usage_tracker::UpdatePayments;\n+use crate::rita_common::usage_tracker::UsageTracker;\nuse crate::SETTING;\nuse ::actix::{Actor, Arbiter, Context, Handler, Message, Supervised, SystemService};\nuse althea_types::PaymentTx;\n@@ -139,9 +141,13 @@ pub fn validate_transaction(ts: &ToValidate) {\n);\nDebtKeeper::from_registry().do_send(PaymentReceived {\nfrom: pmt.from,\n- amount: pmt.amount,\n+ amount: pmt.amount.clone(),\n});\nPaymentValidator::from_registry().do_send(Remove(long_life_ts));\n+\n+ // update the usage tracker with the details of this payment\n+ UsageTracker::from_registry()\n+ .do_send(UpdatePayments { payment: pmt });\n} else {\ntrace!(\"transaction is vaild but not in a block yet\");\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Track recieved payments too
20,244
06.05.2019 11:50:01
14,400
c5a39897dd21a8c7438902a176e4d52f746441d3
Instrument PaymentFailed flow
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/debt_keeper/mod.rs", "new_path": "rita/src/rita_common/debt_keeper/mod.rs", "diff": "@@ -108,18 +108,29 @@ impl Handler<PaymentFailed> for DebtKeeper {\nSome(entry) => {\n// no need to check for negative amount_int because we're converting\n// from a uint256\n+ info!(\n+ \"Handling failed payment by adding {} back into the debts account\",\n+ amount_int\n+ );\nentry.debt += amount_int.clone();\nentry.total_payment_sent = entry\n.total_payment_sent\n.checked_sub(&msg.amount)\n.ok_or_else(|| {\n+ error!(\"Failed to correct total payments! Value is now inaccurate!\");\nformat_err!(\"Unable to subtract amount from total payments sent\")\n})?;\nOk(())\n}\n- None => bail!(\"Payment failed but no debt! Somthing Must have gone wrong!\"),\n+ None => {\n+ error!(\"Failed to find id for payment failure! Payments now inaccurate!\");\n+ bail!(\"Payment failed but no debt! Somthing Must have gone wrong!\")\n+ }\n},\n- None => bail!(\"Unsable to convert amount to integer256 bit\"),\n+ None => {\n+ error!(\"Failed to convert amount for payment failure! Payments now inaccurate!\");\n+ bail!(\"Unable to convert amount to integer256 bit\")\n+ }\n}\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Instrument PaymentFailed flow
20,244
06.05.2019 11:53:50
14,400
fdd2b19e2bad82a91d8ef09a36a787a48f7f9fce
Minor clippy nit
[ { "change_type": "MODIFY", "old_path": "rita/src/client.rs", "new_path": "rita/src/client.rs", "diff": "@@ -175,11 +175,9 @@ fn main() {\n// If we are an an OpenWRT device try and rescue it from update issues\n// TODO remove in Beta 6\n- if KI.is_openwrt() {\n- if KI.check_cron().is_err() {\n+ if KI.is_openwrt() && KI.check_cron().is_err() {\nerror!(\"Failed to setup cron!\");\n}\n- }\nlet args: Args = Docopt::new((*USAGE).as_str())\n.and_then(|d| d.deserialize())\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Minor clippy nit
20,244
06.05.2019 12:32:38
14,400
03f6d6f34628a3cd7fcb05ed452e7e8f49a383ff
Add timeouts to babel tcpstream operations I've seen babel hang some in production, this adds a pretty reasonable timeout to Babel read/write operations
[ { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "#[macro_use]\nextern crate failure;\n-\n#[macro_use]\nextern crate log;\n+use bufstream::BufStream;\n+use failure::Error;\n+use ipnetwork::IpNetwork;\nuse std::collections::VecDeque;\nuse std::io::{BufRead, Read, Write};\nuse std::iter::Iterator;\nuse std::net::IpAddr;\n+use std::net::SocketAddr;\n+use std::net::TcpStream;\nuse std::str;\n+use std::time::Duration;\n-use bufstream::BufStream;\n-use failure::Error;\n-use ipnetwork::IpNetwork;\n+const BABEL_OPERATION_TIMEOUT: Duration = Duration::from_secs(4);\n#[derive(Debug, Fail)]\npub enum BabelMonitorError {\n@@ -32,7 +35,10 @@ pub enum BabelMonitorError {\nNoNeighbor(String),\n}\n-use crate::BabelMonitorError::*;\n+use crate::BabelMonitorError::{\n+ CommandFailed, InvalidPreamble, LocalFeeNotFound, NoNeighbor, NoTerminator, ReadFailed,\n+ VariableNotFound,\n+};\n// If a function doesn't need internal state of the Babel object\n// we don't want to place it as a member function.\n@@ -78,6 +84,15 @@ pub struct Neighbor {\npub cost: u16,\n}\n+/// Opens a tcpstream to the babel management socket using a standard timeout\n+/// for both the open and read operations\n+pub fn open_babel_stream(babel_port: u16) -> Result<TcpStream, Error> {\n+ let socket: SocketAddr = format!(\"[::1]:{}\", babel_port,).parse()?;\n+ let stream = TcpStream::connect_timeout(&socket, BABEL_OPERATION_TIMEOUT)?;\n+ stream.set_read_timeout(Some(BABEL_OPERATION_TIMEOUT))?;\n+ Ok(stream)\n+}\n+\npub struct Babel<T: Read + Write> {\nstream: BufStream<T>,\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/exits.rs", "new_path": "rita/src/rita_client/dashboard/exits.rs", "diff": "@@ -11,6 +11,7 @@ use ::actix_web::AsyncResponder;\nuse ::actix_web::Path;\nuse ::actix_web::{HttpRequest, HttpResponse, Json};\nuse althea_types::ExitState;\n+use babel_monitor::open_babel_stream;\nuse babel_monitor::Babel;\nuse failure::Error;\nuse futures::{future, Future};\n@@ -20,7 +21,6 @@ use settings::FileWrite;\nuse settings::RitaCommonSettings;\nuse std::boxed::Box;\nuse std::collections::HashMap;\n-use std::net::{SocketAddr, TcpStream};\nuse std::time::Duration;\n#[derive(Serialize)]\n@@ -66,9 +66,7 @@ impl Handler<GetExitInfo> for Dashboard {\ntype Result = Result<Vec<ExitInfo>, Error>;\nfn handle(&mut self, _msg: GetExitInfo, _ctx: &mut Self::Context) -> Self::Result {\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port).parse()?,\n- )?;\n+ let stream = open_babel_stream(SETTING.get_network().babel_port)?;\nlet mut babel = Babel::new(stream);\nbabel.start_connection()?;\nlet route_table_sample = babel.parse_routes()?;\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/neighbors.rs", "new_path": "rita/src/rita_client/dashboard/neighbors.rs", "diff": "@@ -2,11 +2,12 @@ use crate::rita_common::dashboard::Dashboard;\nuse crate::rita_common::debt_keeper::{DebtKeeper, Dump, NodeDebtData};\nuse crate::rita_common::tunnel_manager::{GetNeighbors, Neighbor, TunnelManager};\nuse crate::SETTING;\n-use ::actix::prelude::*;\n+use ::actix::{Handler, Message, ResponseFuture, SystemService};\nuse ::actix_web::AsyncResponder;\nuse ::actix_web::{HttpRequest, Json};\nuse althea_types::Identity;\nuse arrayvec::ArrayString;\n+use babel_monitor::open_babel_stream;\nuse babel_monitor::Babel;\nuse failure::Error;\nuse futures::Future;\n@@ -15,7 +16,6 @@ use settings::client::RitaClientSettings;\nuse settings::RitaCommonSettings;\nuse std::boxed::Box;\nuse std::collections::HashMap;\n-use std::net::{SocketAddr, TcpStream};\n#[derive(Serialize)]\npub struct NodeInfo {\n@@ -58,9 +58,7 @@ impl Handler<GetNeighborInfo> for Dashboard {\nmerge_debts_and_neighbors(neighbors, &mut debts);\n}\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port).parse()?,\n- )?;\n+ let stream = open_babel_stream(SETTING.get_network().babel_port)?;\nlet mut babel = Babel::new(stream);\nbabel.start_connection()?;\nlet route_table_sample = babel.parse_routes()?;\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/traffic_watcher/mod.rs", "new_path": "rita/src/rita_client/traffic_watcher/mod.rs", "diff": "@@ -14,17 +14,16 @@ use crate::KI;\nuse crate::SETTING;\nuse ::actix::prelude::{Actor, Context, Handler, Message, Supervised, SystemService};\nuse althea_types::Identity;\n+use babel_monitor::open_babel_stream;\nuse babel_monitor::Babel;\nuse babel_monitor::Route;\nuse failure::Error;\nuse settings::RitaCommonSettings;\n-use std::net::{IpAddr, SocketAddr, TcpStream};\n+use std::net::IpAddr;\n/// Returns the babel route to a given mesh ip with the properly capped price\nfn find_exit_route_capped(exit_mesh_ip: IpAddr) -> Result<Route, Error> {\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port).parse()?,\n- )?;\n+ let stream = open_babel_stream(SETTING.get_network().babel_port)?;\nlet mut babel = Babel::new(stream);\nbabel.start_connection()?;\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/babel.rs", "new_path": "rita/src/rita_common/dashboard/babel.rs", "diff": "@@ -5,10 +5,10 @@ use ::actix_web::Path;\nuse ::actix_web::{HttpRequest, HttpResponse, Result};\nuse ::settings::FileWrite;\nuse ::settings::RitaCommonSettings;\n+use babel_monitor::open_babel_stream;\nuse babel_monitor::Babel;\nuse failure::Error;\nuse std::collections::HashMap;\n-use std::net::{SocketAddr, TcpStream};\npub fn get_local_fee(_req: HttpRequest) -> Result<HttpResponse, Error> {\ndebug!(\"/local_fee GET hit\");\n@@ -36,11 +36,7 @@ pub fn set_local_fee(path: Path<u32>) -> Result<HttpResponse, Error> {\nbail!(\"Price is too high due to babel bug!\");\n}\n- let stream = match TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port)\n- .parse()\n- .unwrap(),\n- ) {\n+ let stream = match open_babel_stream(SETTING.get_network().babel_port) {\nOk(s) => s,\nErr(e) => {\nerror!(\"Failed to set local fee! {:?}\", e);\n@@ -102,11 +98,7 @@ pub fn set_metric_factor(path: Path<u32>) -> Result<HttpResponse, Error> {\ndebug!(\"/metric_factor/{} POST hit\", new_factor);\nlet mut ret = HashMap::<String, String>::new();\n- let stream = match TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port)\n- .parse()\n- .unwrap(),\n- ) {\n+ let stream = match open_babel_stream(SETTING.get_network().babel_port) {\nOk(s) => s,\nErr(e) => {\nerror!(\"Failed to set metric factor! {:?}\", e);\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/traffic_watcher/mod.rs", "new_path": "rita/src/rita_common/traffic_watcher/mod.rs", "diff": "@@ -14,13 +14,14 @@ use crate::SETTING;\nuse ::actix::{Actor, Context, Handler, Message, Supervised, SystemService};\nuse althea_kernel_interface::FilterTarget;\nuse althea_types::Identity;\n+use babel_monitor::open_babel_stream;\nuse babel_monitor::Babel;\nuse failure::Error;\nuse ipnetwork::IpNetwork;\nuse settings::RitaCommonSettings;\nuse std::collections::HashMap;\nuse std::io::{Read, Write};\n-use std::net::{IpAddr, SocketAddr, TcpStream};\n+use std::net::IpAddr;\npub struct TrafficWatcher;\n@@ -66,9 +67,7 @@ impl Handler<Watch> for TrafficWatcher {\ntype Result = Result<(), Error>;\nfn handle(&mut self, msg: Watch, _: &mut Context<Self>) -> Self::Result {\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port).parse()?,\n- )?;\n+ let stream = open_babel_stream(SETTING.get_network().babel_port)?;\nwatch(Babel::new(stream), &msg.neighbors)\n}\n@@ -358,18 +357,3 @@ pub fn watch<T: Read + Write>(babel: Babel<T>, neighbors: &[Neighbor]) -> Result\nOk(())\n}\n-\n-#[cfg(test)]\n-mod tests {\n- use env_logger;\n-\n- use super::*;\n-\n- #[test]\n- #[ignore]\n- fn debug_babel_socket_common() {\n- env_logger::init();\n- let bm_stream = TcpStream::connect::<SocketAddr>(\"[::1]:9001\".parse().unwrap()).unwrap();\n- watch(Babel::new(bm_stream), &Vec::new()).unwrap();\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -15,6 +15,7 @@ use ::actix::actors::resolver;\nuse ::actix::prelude::{Actor, Arbiter, Context, Handler, Message, Supervised, SystemService};\nuse althea_types::Identity;\nuse althea_types::LocalIdentity;\n+use babel_monitor::open_babel_stream;\nuse babel_monitor::Babel;\nuse failure::Error;\nuse futures::Future;\n@@ -281,9 +282,8 @@ impl Handler<PortCallback> for TunnelManager {\n}\npub fn make_babel_stream() -> Result<TcpStream, Error> {\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port).parse()?,\n- )?;\n+ let stream = open_babel_stream(SETTING.get_network().babel_port)?;\n+\nOk(stream)\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "@@ -15,18 +15,19 @@ use crate::rita_common::usage_tracker::UpdateUsage;\nuse crate::rita_common::usage_tracker::UsageTracker;\nuse crate::rita_common::usage_tracker::UsageType;\nuse crate::SETTING;\n-use ::actix::prelude::{Actor, Context, Handler, Message, Supervised, SystemService};\n+use ::actix::{Actor, Context, Handler, Message, Supervised, SystemService};\nuse althea_kernel_interface::wg_iface_counter::WgUsage;\nuse althea_kernel_interface::KI;\nuse althea_types::Identity;\nuse althea_types::WgKey;\n+use babel_monitor::open_babel_stream;\nuse babel_monitor::Babel;\nuse ipnetwork::IpNetwork;\nuse settings::exit::RitaExitSettings;\nuse settings::RitaCommonSettings;\nuse std::collections::HashMap;\nuse std::io::{Read, Write};\n-use std::net::{IpAddr, SocketAddr, TcpStream};\n+use std::net::IpAddr;\nuse failure::Error;\n@@ -68,9 +69,7 @@ impl Handler<Watch> for TrafficWatcher {\ntype Result = Result<(), Error>;\nfn handle(&mut self, msg: Watch, _: &mut Context<Self>) -> Self::Result {\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", SETTING.get_network().babel_port).parse()?,\n- )?;\n+ let stream = open_babel_stream(SETTING.get_network().babel_port)?;\nwatch(&mut self.last_seen_bytes, Babel::new(stream), &msg.0)\n}\n@@ -337,18 +336,3 @@ pub fn watch<T: Read + Write>(\nOk(())\n}\n-\n-#[cfg(test)]\n-mod tests {\n- use env_logger;\n-\n- use super::*;\n-\n- #[test]\n- #[ignore]\n- fn debug_babel_socket_client() {\n- env_logger::init();\n- let bm_stream = TcpStream::connect::<SocketAddr>(\"[::1]:9001\".parse().unwrap()).unwrap();\n- watch(&mut HashMap::new(), Babel::new(bm_stream), &[]).unwrap();\n- }\n-}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add timeouts to babel tcpstream operations I've seen babel hang some in production, this adds a pretty reasonable timeout to Babel read/write operations
20,244
07.05.2019 10:53:58
14,400
03ab01ca6a3bd44940a1277cdecb3d1e6d3714dc
Reduce exit log spam Missed this one last time, once again we have id's from the database but no routes because the vast majority of historical signups will be old routers that are no longer online. Leading to a few hundred lines of warnings every loop
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "@@ -285,7 +285,7 @@ pub fn watch<T: Read + Write>(\n// this can be caused by a peer that has not yet formed a babel route\n(Some(id), None, _) => warn!(\"We have an id {:?} but not destination\", id),\n// if we have a babel route we should have a peer it's possible we have a mesh client sneaking in?\n- (None, Some(dest), _) => warn!(\"We have a destination {:?} but no id\", dest),\n+ (None, Some(dest), _) => trace!(\"We have a destination {:?} but no id\", dest),\n// dead entry?\n(None, None, _) => warn!(\"We have no id or dest for an input counter on {:?}\", wg_key),\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Reduce exit log spam Missed this one last time, once again we have id's from the database but no routes because the vast majority of historical signups will be old routers that are no longer online. Leading to a few hundred lines of warnings every loop
20,244
08.05.2019 12:00:58
14,400
1e8fc0c30f485c64d1f54fce3bb9729cb24ca347
More logging in payment received flow Seeing some errors here in prod
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/debt_keeper/mod.rs", "new_path": "rita/src/rita_common/debt_keeper/mod.rs", "diff": "@@ -237,10 +237,9 @@ impl DebtKeeper {\n.to_int256()\n.ok_or_else(|| format_err!(\"Unable to convert amount to 256 bit signed integer\"))?;\nlet debt_data = self.get_debt_data_mut(ident);\n- trace!(\n+ info!(\n\"payment received: old incoming payments for {:?}: {:?}\",\n- ident.mesh_ip,\n- debt_data.incoming_payments\n+ ident.mesh_ip, debt_data.incoming_payments\n);\n// just a counter, no convergence importance\n@@ -250,6 +249,10 @@ impl DebtKeeper {\nlet they_owe_us = debt_data.debt < Int256::from(0);\nlet incoming_greater_than_debt = debt_data.incoming_payments > debt_data.debt.abs();\n+ if debt_data.incoming_payments < Int256::from(0) {\n+ error!(\"Negative incoming payments!\");\n+ bail!(\"Billing state is wrong!\")\n+ }\n// somewhat more complicated, we apply incoming to the balance, but don't allow\n// the balance to go positive (we owe them) we don't want to get into paying them\n@@ -263,13 +266,14 @@ impl DebtKeeper {\ndebt_data.debt += debt_data.incoming_payments.clone();\ndebt_data.incoming_payments = zero;\n}\n- (false, _) => {}\n+ (false, _) => {\n+ error!(\"Why did we get a payment when they don't owe us anything?\");\n+ }\n}\n- trace!(\n+ info!(\n\"new incoming payments for {:?}: {:?}\",\n- ident.mesh_ip,\n- debt_data.incoming_payments\n+ ident.mesh_ip, debt_data.incoming_payments\n);\nOk(())\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
More logging in payment received flow Seeing some errors here in prod
20,244
08.05.2019 14:45:22
14,400
136673d551a41bc335d7e2095b7aa5cd22fea277
Payments received should also be a uint
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/debt_keeper/mod.rs", "new_path": "rita/src/rita_common/debt_keeper/mod.rs", "diff": "@@ -28,7 +28,7 @@ pub struct NodeDebtData {\npub total_payment_received: Uint256,\npub total_payment_sent: Uint256,\npub debt: Int256,\n- pub incoming_payments: Int256,\n+ pub incoming_payments: Uint256,\npub action: DebtAction,\n}\n@@ -38,7 +38,7 @@ impl NodeDebtData {\ntotal_payment_received: Uint256::from(0u32),\ntotal_payment_sent: Uint256::from(0u32),\ndebt: Int256::from(0),\n- incoming_payments: Int256::from(0),\n+ incoming_payments: Uint256::from(0u32),\naction: DebtAction::OpenTunnel,\n}\n}\n@@ -103,35 +103,7 @@ impl Handler<PaymentFailed> for DebtKeeper {\ntype Result = Result<(), Error>;\nfn handle(&mut self, msg: PaymentFailed, _: &mut Context<Self>) -> Self::Result {\n- match msg.amount.to_int256() {\n- Some(amount_int) => match self.debt_data.get_mut(&msg.to) {\n- Some(entry) => {\n- // no need to check for negative amount_int because we're converting\n- // from a uint256\n- info!(\n- \"Handling failed payment by adding {} back into the debts account\",\n- amount_int\n- );\n- entry.debt += amount_int.clone();\n- entry.total_payment_sent = entry\n- .total_payment_sent\n- .checked_sub(&msg.amount)\n- .ok_or_else(|| {\n- error!(\"Failed to correct total payments! Value is now inaccurate!\");\n- format_err!(\"Unable to subtract amount from total payments sent\")\n- })?;\n- Ok(())\n- }\n- None => {\n- error!(\"Failed to find id for payment failure! Payments now inaccurate!\");\n- bail!(\"Payment failed but no debt! Somthing Must have gone wrong!\")\n- }\n- },\n- None => {\n- error!(\"Failed to convert amount for payment failure! Payments now inaccurate!\");\n- bail!(\"Unable to convert amount to integer256 bit\")\n- }\n- }\n+ self.payment_failed(&msg.to, msg.amount)\n}\n}\n@@ -231,11 +203,42 @@ impl DebtKeeper {\n.or_insert_with(NodeDebtData::new)\n}\n+ fn payment_failed(&mut self, to: &Identity, amount: Uint256) -> Result<(), Error> {\n+ match amount.to_int256() {\n+ Some(amount_int) => match self.debt_data.get_mut(&to) {\n+ Some(entry) => {\n+ // no need to check for negative amount_int because we're converting\n+ // from a uint256\n+ info!(\n+ \"Handling failed payment by adding {} back into the debts account\",\n+ amount_int\n+ );\n+ entry.debt += amount_int.clone();\n+ entry.total_payment_sent = entry\n+ .total_payment_sent\n+ .checked_sub(&amount)\n+ .ok_or_else(|| {\n+ error!(\"Failed to correct total payments! Value is now inaccurate!\");\n+ format_err!(\"Unable to subtract amount from total payments sent\")\n+ })?;\n+ Ok(())\n+ }\n+ None => {\n+ error!(\"Failed to find id for payment failure! Payments now inaccurate!\");\n+ bail!(\"Payment failed but no debt! Somthing Must have gone wrong!\")\n+ }\n+ },\n+ None => {\n+ error!(\"Failed to convert amount for payment failure! Payments now inaccurate!\");\n+ bail!(\"Unable to convert amount to integer256 bit\")\n+ }\n+ }\n+ }\n+\nfn payment_received(&mut self, ident: &Identity, amount: Uint256) -> Result<(), Error> {\n- let zero = Int256::from(0);\n- let incoming_amount = amount\n- .to_int256()\n- .ok_or_else(|| format_err!(\"Unable to convert amount to 256 bit signed integer\"))?;\n+ let signed_zero = Int256::from(0);\n+ let unsigned_zero = Uint256::from(0u32);\n+\nlet debt_data = self.get_debt_data_mut(ident);\ninfo!(\n\"payment received: old incoming payments for {:?}: {:?}\",\n@@ -245,26 +248,30 @@ impl DebtKeeper {\n// just a counter, no convergence importance\ndebt_data.total_payment_received += amount.clone();\n// add in the latest amount to the pile before processing\n- debt_data.incoming_payments += incoming_amount;\n+ debt_data.incoming_payments += amount;\nlet they_owe_us = debt_data.debt < Int256::from(0);\n- let incoming_greater_than_debt = debt_data.incoming_payments > debt_data.debt.abs();\n- if debt_data.incoming_payments < Int256::from(0) {\n- error!(\"Negative incoming payments!\");\n- bail!(\"Billing state is wrong!\")\n- }\n+ // unwrap is safe because the abs of a signed 256 bit int can't overflow a unsigned 256 bit int or be negative\n+ let incoming_greater_than_debt =\n+ debt_data.incoming_payments > debt_data.debt.abs().to_uint256().unwrap();\n// somewhat more complicated, we apply incoming to the balance, but don't allow\n// the balance to go positive (we owe them) we don't want to get into paying them\n// because they overpaid us.\nmatch (they_owe_us, incoming_greater_than_debt) {\n(true, true) => {\n- debt_data.incoming_payments -= debt_data.debt.abs();\n- debt_data.debt = zero;\n+ debt_data.incoming_payments -= debt_data.debt.abs().to_uint256().unwrap();\n+ debt_data.debt = signed_zero;\n}\n(true, false) => {\n- debt_data.debt += debt_data.incoming_payments.clone();\n- debt_data.incoming_payments = zero;\n+ // we validate payments before they get here, so in theory if someone pays you a few trillion coins and it\n+ // gets into a block this could overflow\n+ let signed_incoming = match debt_data.incoming_payments.to_int256() {\n+ Some(val) => val,\n+ None => bail!(\"Unsigned payment int too big! You're super rich now\"),\n+ };\n+ debt_data.debt += signed_incoming;\n+ debt_data.incoming_payments = unsigned_zero;\n}\n(false, _) => {\nerror!(\"Why did we get a payment when they don't owe us anything?\");\n@@ -281,7 +288,6 @@ impl DebtKeeper {\nfn traffic_update(&mut self, ident: &Identity, amount: Int256) {\ntrace!(\"traffic update for {} is {}\", ident.mesh_ip, amount);\nlet debt_data = self.get_debt_data_mut(ident);\n- assert!(debt_data.incoming_payments >= Int256::from(0));\n// we handle the incoming debit or credit versus our existing debit or credit\n// very simple\n@@ -487,7 +493,6 @@ mod tests {\nlet mut d = DebtKeeper::new();\nlet ident = get_test_identity();\n- // send lots of payments\nfor _ in 0..100 {\nd.traffic_update(&ident, Int256::from(100))\n}\n@@ -539,4 +544,35 @@ mod tests {\nassert_eq!(d.send_update(&ident).unwrap(), DebtAction::OpenTunnel);\n}\n+\n+ #[test]\n+ fn test_payment_fail() {\n+ SETTING.get_payment_mut().pay_threshold = Int256::from(5);\n+ SETTING.get_payment_mut().close_threshold = Int256::from(-10);\n+\n+ let mut d = DebtKeeper::new();\n+ let ident = get_test_identity();\n+\n+ for _ in 0..100 {\n+ d.traffic_update(&ident, Int256::from(100))\n+ }\n+ assert_eq!(\n+ d.send_update(&ident).unwrap(),\n+ DebtAction::MakePayment {\n+ amount: Uint256::from(10000u32),\n+ to: ident,\n+ }\n+ );\n+ d.payment_failed(&ident, Uint256::from(10000u64)).unwrap();\n+\n+ assert_eq!(\n+ d.get_debts()[&ident].total_payment_sent,\n+ Uint256::from(0u32)\n+ );\n+ d.send_update(&ident).unwrap();\n+ assert_eq!(\n+ d.get_debts()[&ident].total_payment_sent,\n+ Uint256::from(10000u32)\n+ );\n+ }\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Payments received should also be a uint
20,249
07.05.2019 14:44:12
25,200
3428d90f1b1cf37eaf251278cd163e81c4f86075
Endpoints for getting/setting dao_fee
[ { "change_type": "MODIFY", "old_path": "rita/src/client.rs", "new_path": "rita/src/client.rs", "diff": "@@ -247,6 +247,8 @@ fn main() {\n.route(\"/exits/{name}/select\", Method::POST, select_exit)\n.route(\"/local_fee\", Method::GET, get_local_fee)\n.route(\"/local_fee/{fee}\", Method::POST, set_local_fee)\n+ .route(\"/dao_fee\", Method::GET, get_dao_fee)\n+ .route(\"/dao_fee/{fee}\", Method::POST, set_dao_fee)\n.route(\"/metric_factor\", Method::GET, get_metric_factor)\n.route(\"/metric_factor/{factor}\", Method::POST, set_metric_factor)\n.route(\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/dao.rs", "new_path": "rita/src/rita_common/dashboard/dao.rs", "diff": "use crate::ARGS;\nuse crate::SETTING;\nuse ::actix_web::Path;\n-use ::actix_web::{HttpRequest, Json, Result};\n+use ::actix_web::{HttpRequest, HttpResponse, Json, Result};\nuse ::settings::FileWrite;\nuse ::settings::RitaCommonSettings;\nuse clarity::Address;\nuse failure::Error;\n+use num256::Uint256;\n+use std::collections::HashMap;\npub fn get_dao_list(_req: HttpRequest) -> Result<Json<Vec<Address>>, Error> {\ntrace!(\"get dao list: Hit\");\n@@ -51,3 +53,23 @@ pub fn remove_from_dao_list(path: Path<(Address)>) -> Result<Json<()>, Error> {\n}\nOk(Json(()))\n}\n+\n+pub fn get_dao_fee(_req: HttpRequest) -> Result<HttpResponse, Error> {\n+ debug!(\"/dao_fee GET hit\");\n+ let mut ret = HashMap::new();\n+ ret.insert(\"dao_fee\", SETTING.get_dao().dao_fee.to_string());\n+\n+ Ok(HttpResponse::Ok().json(ret))\n+}\n+\n+pub fn set_dao_fee(path: Path<Uint256>) -> Result<Json<()>, Error> {\n+ let new_fee = path.into_inner();\n+ debug!(\"/dao_fee/{} POST hit\", new_fee);\n+ SETTING.get_dao_mut().dao_fee = new_fee;\n+\n+ // try and save the config and fail if we can't\n+ if let Err(e) = SETTING.write().unwrap().write(&ARGS.flag_config) {\n+ return Err(e);\n+ }\n+ Ok(Json(()))\n+}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/oracle/mod.rs", "new_path": "rita/src/rita_common/oracle/mod.rs", "diff": "@@ -306,8 +306,12 @@ fn update_our_price() {\nnew_prices.fee_multiplier;\ndrop(payment);\n+ let new_dao_fee = Uint256::from(new_prices.dao_fee);\n+ let current_dao_fee = SETTING.get_dao().dao_fee.clone();\n+ if new_dao_fee > current_dao_fee {\nlet mut dao = SETTING.get_dao_mut();\n- dao.dao_fee = Uint256::from(new_prices.dao_fee);\n+ dao.dao_fee = new_dao_fee;\n+ }\ntrace!(\"Successfully updated prices\");\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Endpoints for getting/setting dao_fee
20,244
14.05.2019 18:40:57
14,400
298f31fc54b7112baa3551ab6ad37fa2f8f0862a
More exit logging spam tweaks
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -248,7 +248,7 @@ fn low_balance_notification(\nconfig: Option<ExitVerifSettings>,\nconn: &PgConnection,\n) {\n- info!(\"Checking low balance nofication\");\n+ trace!(\"Checking low balance nofication\");\nlet time_since_last_notification =\nsecs_since_unix_epoch() - their_record.last_balance_warning_time;\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/sms.rs", "new_path": "rita/src/rita_exit/database/sms.rs", "diff": "@@ -49,7 +49,7 @@ pub struct SmsRequest {\n/// Sends the authy verification text by hitting the api endpoint\nfn send_text(number: String, api_key: String) -> Result<(), Error> {\n- trace!(\"Sending message for {}\", number);\n+ info!(\"Sending message for {}\", number);\nlet number: PhoneNumber = number.parse()?;\nlet client = reqwest::Client::builder()\n.timeout(Duration::from_secs(1))\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "@@ -283,7 +283,7 @@ pub fn watch<T: Read + Write>(\n},\n(Some(id), Some(_dest), None) => warn!(\"Entry for {:?} should have been created\", id),\n// this can be caused by a peer that has not yet formed a babel route\n- (Some(id), None, _) => warn!(\"We have an id {:?} but not destination\", id),\n+ (Some(id), None, _) => trace!(\"We have an id {:?} but not destination\", id),\n// if we have a babel route we should have a peer it's possible we have a mesh client sneaking in?\n(None, Some(dest), _) => trace!(\"We have a destination {:?} but no id\", dest),\n// dead entry?\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
More exit logging spam tweaks
20,244
03.05.2019 21:08:57
14,400
75ad7633d061c9e0c499bd4a988068cd165d1046
Reboot the router after port toggling
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/interfaces.rs", "new_path": "rita/src/rita_client/dashboard/interfaces.rs", "diff": "//! A generalized interface for modifying networking interface assignments using UCI\nuse crate::rita_common::peer_listener::PeerListener;\n-use crate::rita_common::peer_listener::{Listen, UnListen};\n+use crate::rita_common::peer_listener::UnListen;\nuse crate::ARGS;\nuse crate::KI;\nuse crate::SETTING;\n-use ::actix::prelude::*;\n+use ::actix::prelude::{Arbiter, SystemService};\nuse ::actix_web::{HttpRequest, HttpResponse, Json};\nuse failure::Error;\nuse futures::Future;\n@@ -329,8 +329,12 @@ pub fn ethernet_transform_mode(\nlet fut = Delay::new(when)\n.map_err(|e| warn!(\"timer failed; err={:?}\", e))\n.and_then(move |_| {\n- trace!(\"Adding mesh interface {:?}\", locally_owned_ifname);\n- PeerListener::from_registry().do_send(Listen(locally_owned_ifname));\n+ trace!(\"rebooting router for {:?}\", locally_owned_ifname);\n+ // it's now safe to restart the router, return an error if that fails somehow\n+ // do not remove this, we lose the multicast listeners on other mesh ports when\n+ // we toggle network modes, this means we will clean up valid tunnels 15 minutes\n+ // after the toggle unless we do this\n+ let _ = KI.run_command(\"reboot\", &[]);\nOk(())\n});\n@@ -343,15 +347,7 @@ pub fn ethernet_transform_mode(\n// We edited disk contents, force global sync\nKI.fs_sync()?;\n- trace!(\"Successsfully transformed ethernet mode, rebooting\");\n-\n- // it's now safe to restart the process, return an error if that fails somehow\n- // do not remove this, we lose the multicast listeners on other mesh ports when\n- // we toggle network modes, this means we will clean up valid tunnels 15 minutes\n- // after the toggle unless we do this\n- if let Err(e) = KI.run_command(\"/etc/init.d/rita\", &[\"restart\"]) {\n- return Err(e);\n- }\n+ trace!(\"Successsfully transformed ethernet mode, rebooting in 60 seconds\");\nOk(())\n}\n@@ -471,13 +467,15 @@ pub fn wlan_transform_mode(ifname: &str, a: InterfaceMode, b: InterfaceMode) ->\n);\n} else if mesh_add {\nlet when = Instant::now() + Duration::from_millis(60000);\n- let locally_owned_ifname = mesh_wlan.to_string();\nlet fut = Delay::new(when)\n.map_err(|e| warn!(\"timer failed; err={:?}\", e))\n.and_then(move |_| {\n- trace!(\"Adding mesh interface {:?}\", locally_owned_ifname);\n- PeerListener::from_registry().do_send(Listen(locally_owned_ifname));\n+ // it's now safe to restart the router, return an error if that fails somehow\n+ // do not remove this, we lose the multicast listeners on other mesh ports when\n+ // we toggle network modes, this means we will clean up valid tunnels 15 minutes\n+ // after the toggle unless we do this\n+ let _ = KI.run_command(\"reboot\", &[]);\nOk(())\n});\n@@ -493,14 +491,6 @@ pub fn wlan_transform_mode(ifname: &str, a: InterfaceMode, b: InterfaceMode) ->\n// We edited disk contents, force global sync\nKI.fs_sync()?;\n- // it's now safe to restart the process, return an error if that fails somehow\n- // do not remove this, we lose the multicast listeners on other mesh ports when\n- // we toggle network modes, this means we will clean up valid tunnels 15 minutes\n- // after the toggle unless we do this\n- if let Err(e) = KI.run_command(\"/etc/init.d/rita\", &[\"restart\"]) {\n- return Err(e);\n- }\n-\nOk(())\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Reboot the router after port toggling
20,244
15.05.2019 10:09:00
14,400
c0534e7dd2e3985e1fb2a7a8074ba6fc0cb11aba
Add DAO fee endpoints to the exit Questionably useful, but in theory this could happen and it scilences the warning
[ { "change_type": "MODIFY", "old_path": "rita/src/exit.rs", "new_path": "rita/src/exit.rs", "diff": "@@ -232,12 +232,11 @@ fn main() {\nserver::new(|| {\nApp::new()\n.middleware(middleware::Headers)\n- // assuming exit nodes dont need wifi\n- //.resource(\"/wifisettings\", |r| r.route().filter(pred::Get()).h(get_wifi_config))\n- //.resource(\"/wifisettings\", |r| r.route().filter(pred::Post()).h(set_wifi_config))\n.route(\"/info\", Method::GET, get_own_info)\n.route(\"/local_fee\", Method::GET, get_local_fee)\n.route(\"/local_fee/{fee}\", Method::POST, set_local_fee)\n+ .route(\"/dao_fee\", Method::GET, get_dao_fee)\n+ .route(\"/dao_fee/{fee}\", Method::POST, set_dao_fee)\n.route(\"/metric_factor\", Method::GET, get_metric_factor)\n.route(\"/metric_factor/{factor}\", Method::POST, set_metric_factor)\n.route(\"/settings\", Method::GET, get_settings)\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add DAO fee endpoints to the exit Questionably useful, but in theory this could happen and it scilences the warning
20,244
16.05.2019 14:45:51
14,400
c6f286102930f75380016fe794809c78672aeb3b
Block age check reversed Pretty bad bug here, all payments would be dropped as too old unless they where actually too old.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_validator/mod.rs", "new_path": "rita/src/rita_common/payment_validator/mod.rs", "diff": "@@ -305,7 +305,7 @@ fn payment_is_old(chain_height: Uint256, tx_height: Option<Uint256>) -> bool {\nif tx_block > chain_height {\nfalse\n} else {\n- chain_height - tx_block < Uint256::from(BLOCKS_TO_OLD)\n+ chain_height - tx_block > Uint256::from(BLOCKS_TO_OLD)\n}\n}\nNone => false,\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Block age check reversed Pretty bad bug here, all payments would be dropped as too old unless they where actually too old.
20,244
16.05.2019 20:06:12
14,400
466f92afc6ef411aa8d9162ff6c925a8a8a5e4b5
Always log transactions in readable format
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/network_endpoints/mod.rs", "new_path": "rita/src/rita_common/network_endpoints/mod.rs", "diff": "@@ -47,17 +47,10 @@ pub fn make_payments(\n) -> Box<dyn Future<Item = HttpResponse, Error = Error>> {\nlet txid = pmt.0.txid.clone();\n- info!(\n- \"Got Payment from {:?} for {} with txid {:?}\",\n- pmt.1.connection_info().remote(),\n- pmt.0.amount,\n- txid,\n- );\n-\n// we didn't get a txid, probably an old client.\n// why don't we need an Either up here? Because the types ultimately match?\nif txid.is_none() {\n- trace!(\"Did not find txid, payment failed!\");\n+ info!(\"Did not find txid, payment failed!\");\nreturn Box::new(future::ok(\nHttpResponse::new(StatusCode::from_u16(400u16).unwrap())\n.into_builder()\n@@ -65,7 +58,12 @@ pub fn make_payments(\n));\n}\nlet txid = txid.unwrap();\n- trace!(\"Payment txid is {:#x}\", txid);\n+ info!(\n+ \"Got Payment from {:?} for {} with txid {:#066x}\",\n+ pmt.1.connection_info().remote(),\n+ pmt.0.amount,\n+ txid,\n+ );\nlet ts = ToValidate {\npayment: pmt.0.into_inner(),\nrecieved: Instant::now(),\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_validator/mod.rs", "new_path": "rita/src/rita_common/payment_validator/mod.rs", "diff": "@@ -217,7 +217,7 @@ fn handle_tx_messaging(\n}\nif is_old {\n- error!(\"Transaction is more than 6 hours old! {:?}\", pmt.txid);\n+ error!(\"Transaction is more than 6 hours old! {:#066x}\", txid);\nPaymentValidator::from_registry().do_send(Remove {\ntx: ts,\nsuccess: false,\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Always log transactions in readable format
20,244
16.05.2019 20:16:32
14,400
67f1baf139b8b2ed5302a148593be7f85cb719cc
Crash and hope for recovery when out of ports
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -541,7 +541,11 @@ impl TunnelManager {\nmatch (port, udp_table) {\n(Some(p), Ok(used_ports)) => {\nif used_ports.contains(&p) {\n- warn!(\"We tried to allocate a used port {}!\", p);\n+ warn!(\n+ \"We tried to allocate a used port {}!, there are {} ports remaining\",\n+ p,\n+ self.free_ports.len()\n+ );\nif level < 10 {\n// don't use push here, you'll get that same\n@@ -552,8 +556,9 @@ impl TunnelManager {\nself.get_port(level + 1)\n} else {\n// we've tried a bunch of ports and all are used\n- // break recusion and try this one anyways\n- Some(p)\n+ // break recusion and die, hopefully to be restarted in 15min\n+ error!(\"We ran out of ports!\");\n+ panic!(\"We ran out of ports!\");\n}\n} else {\nSome(p)\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Crash and hope for recovery when out of ports
20,244
17.05.2019 09:34:10
14,400
cd61be4d965124e615a665dba163b9298ac0f4bf
Fix DAO fee update u32 is way too small.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dao_manager/mod.rs", "new_path": "rita/src/rita_common/dao_manager/mod.rs", "diff": "@@ -77,10 +77,13 @@ impl Handler<Tick> for DAOManager {\nlet we_have_a_dao = !dao_addresses.is_empty();\nlet should_pay =\n(Int256::from(self.last_payment_time.elapsed().as_secs()) * dao_fee) > pay_threshold;\n+ trace!(\"We should pay the subnet dao {}\", should_pay);\n+ trace!(\"We have a dao to pay {}\", we_have_a_dao);\nif we_have_a_dao && should_pay {\n// pay all the daos on the list at once\nfor address in dao_addresses {\n+ trace!(\"Paying subnet dao fee to {}\", address);\nlet amount_to_pay = match pay_threshold.abs().to_uint256().clone() {\nSome(val) => val,\nNone => return,\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/oracle/mod.rs", "new_path": "rita/src/rita_common/oracle/mod.rs", "diff": "@@ -255,7 +255,7 @@ struct PriceUpdate {\nclient: u32,\ngateway: u32,\nmax: u32,\n- dao_fee: u32,\n+ dao_fee: u128,\nwarning: u128,\nfee_multiplier: u32,\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Fix DAO fee update u32 is way too small.
20,244
17.05.2019 11:15:01
14,400
181b75ad35fa1842f44f7eeb66b9c56bb8256c3b
Update nonce during withdraw flow We are no longer constantly updating our nonce, meaning we need special handling if we need to update it during a withdraw.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/wallet.rs", "new_path": "rita/src/rita_common/dashboard/wallet.rs", "diff": "+use crate::rita_common::oracle::update_nonce;\nuse crate::rita_common::rita_loop::get_web3_server;\nuse crate::SETTING;\nuse ::actix_web::http::StatusCode;\n@@ -18,6 +19,16 @@ pub fn withdraw(path: Path<(Address, u64)>) -> Box<dyn Future<Item = HttpRespons\nlet full_node = get_web3_server();\nlet web3 = Web3::new(&full_node);\nlet payment_settings = SETTING.get_payment();\n+ let our_address = match payment_settings.eth_address {\n+ Some(address) => address,\n+ None => {\n+ return Box::new(future::ok(\n+ HttpResponse::new(StatusCode::from_u16(504u16).unwrap())\n+ .into_builder()\n+ .json(\"No Address configured, withdraw impossible!\"),\n+ ))\n+ }\n+ };\nlet tx = Transaction {\nnonce: payment_settings.nonce.clone(),\n@@ -48,17 +59,26 @@ pub fn withdraw(path: Path<(Address, u64)>) -> Box<dyn Future<Item = HttpRespons\nlet transaction_status = web3.eth_send_raw_transaction(transaction_bytes);\n- Box::new(transaction_status.then(|result| {\n- match result {\n+ Box::new(transaction_status.then(move |result| match result {\nOk(tx_id) => Box::new(future::ok({\nSETTING.get_payment_mut().nonce += 1u64.into();\nHttpResponse::Ok().json(format!(\"txid:{:#066x}\", tx_id))\n})),\n- Err(e) => Box::new(future::ok(\n+ Err(e) => {\n+ update_nonce(our_address, &web3);\n+ if e.to_string().contains(\"nonce\") {\n+ Box::new(future::ok(\n+ HttpResponse::new(StatusCode::from_u16(504u16).unwrap())\n+ .into_builder()\n+ .json(format!(\"The nonce was not updated, try again {:?}\", e)),\n+ ))\n+ } else {\n+ Box::new(future::ok(\nHttpResponse::new(StatusCode::from_u16(504u16).unwrap())\n.into_builder()\n.json(format!(\"Full node failed to send transaction! {:?}\", e)),\n- )),\n+ ))\n+ }\n}\n}))\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Update nonce during withdraw flow We are no longer constantly updating our nonce, meaning we need special handling if we need to update it during a withdraw.
20,244
17.05.2019 12:00:14
14,400
f396d949e601a75304d33de775f334299937073b
Update port flow to randomize requests The errors I keep seeing don't really match the function definitions, somehow we get into a loop requesting the same port despite poping it off and pushing it backonto the end.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -19,6 +19,8 @@ use babel_monitor::open_babel_stream;\nuse babel_monitor::Babel;\nuse failure::Error;\nuse futures::Future;\n+use rand::thread_rng;\n+use rand::Rng;\nuse settings::RitaCommonSettings;\nuse std::collections::HashMap;\nuse std::fmt;\n@@ -537,9 +539,11 @@ impl TunnelManager {\n/// interally to prevent unchecked recursion\nfn get_port(&mut self, level: usize) -> Option<u16> {\nlet udp_table = KI.used_ports();\n- let port = self.free_ports.pop();\n+ let mut rng = thread_rng();\n+ let val = rng.gen_range(0, self.free_ports.len());\n+ let port = self.free_ports.remove(val);\nmatch (port, udp_table) {\n- (Some(p), Ok(used_ports)) => {\n+ (p, Ok(used_ports)) => {\nif used_ports.contains(&p) {\nwarn!(\n\"We tried to allocate a used port {}!, there are {} ports remaining\",\n@@ -548,11 +552,7 @@ impl TunnelManager {\n);\nif level < 10 {\n- // don't use push here, you'll get that same\n- // entry back in the next pop and recurse forever\n- // hopefully the port will be free when we get\n- // back to it in a few hours\n- self.free_ports.insert(0, p);\n+ self.free_ports.push(p);\nself.get_port(level + 1)\n} else {\n// we've tried a bunch of ports and all are used\n@@ -564,13 +564,12 @@ impl TunnelManager {\nSome(p)\n}\n}\n- (Some(p), Err(e)) => {\n- // we can either crash for sure here or take the chance\n- // that the port is not actually used, we chose the latter\n+ (_p, Err(e)) => {\n+ // better not to open an individual tunnel than it is to\n+ // risk having a failed one\nwarn!(\"Failed to check if port was in use! {:?}\", e);\n- Some(p)\n+ None\n}\n- (None, _) => None,\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Update port flow to randomize requests The errors I keep seeing don't really match the function definitions, somehow we get into a loop requesting the same port despite poping it off and pushing it backonto the end.
20,244
17.05.2019 13:57:49
14,400
ea724aa131111d41501949e04ed6aca6d6cb9c26
Bump for Beta 5
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/own_info.rs", "new_path": "rita/src/rita_common/dashboard/own_info.rs", "diff": "@@ -6,7 +6,7 @@ use clarity::Address;\nuse failure::Error;\nuse num256::{Int256, Uint256};\n-pub static READABLE_VERSION: &str = \"Beta 4 RC6\";\n+pub static READABLE_VERSION: &str = \"Beta 5 RC1\";\n#[derive(Serialize)]\npub struct OwnInfo {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Bump for Beta 5
20,244
17.05.2019 22:08:28
14,400
aa7cca6a0be2a7c5db29f746ed0a36b8de1dbfc3
Don't log so many geoip operations
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/geoip.rs", "new_path": "rita/src/rita_exit/database/geoip.rs", "diff": "@@ -80,7 +80,7 @@ struct CountryDetails {\n/// get ISO country code from ip, consults a in memory cache\npub fn get_country(ip: &IpAddr, cache: &mut HashMap<IpAddr, String>) -> Result<String, Error> {\n- info!(\"get GeoIP country for {}\", ip.to_string());\n+ trace!(\"get GeoIP country for {}\", ip.to_string());\nlet client = reqwest::Client::new();\nlet api_user = SETTING\n.get_exit_network()\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "new_path": "rita/src/rita_exit/traffic_watcher/mod.rs", "diff": "@@ -116,7 +116,7 @@ fn get_babel_info<T: Read + Write>(\ndestinations.insert(id.wg_public_key, u64::from(price));\n}\n- None => warn!(\"Can't find destinatoin for client {:?}\", ip.ip()),\n+ None => warn!(\"Can't find destination for client {:?}\", ip.ip()),\n}\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Don't log so many geoip operations
20,244
17.05.2019 22:08:48
14,400
06a240a951d772712b628a75b51082c9ff21cd5c
Only connect to babel if tunnels actually need removal
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -339,20 +339,6 @@ impl Message for TriggerGC {\nimpl Handler<TriggerGC> for TunnelManager {\ntype Result = Result<(), Error>;\nfn handle(&mut self, msg: TriggerGC, _ctx: &mut Context<Self>) -> Self::Result {\n- let stream = match make_babel_stream() {\n- Ok(stream) => stream,\n- Err(e) => {\n- warn!(\"Tunnel GC failed to open babel stream with {:?}\", e);\n- return Err(e);\n- }\n- };\n- let mut babel = Babel::new(stream);\n- let res = babel.start_connection();\n- if res.is_err() {\n- warn!(\"Failed to start Babel RPC connection! {:?}\", res);\n- bail!(\"Failed to start Babel RPC connection!\");\n- }\n-\nlet mut good: HashMap<Identity, Vec<Tunnel>> = HashMap::new();\nlet mut timed_out: HashMap<Identity, Vec<Tunnel>> = HashMap::new();\n// Split entries into good and timed out rebuilding the double hashmap strucutre\n@@ -392,6 +378,20 @@ impl Handler<TriggerGC> for TunnelManager {\nfor tunnel in tunnels {\n// In the same spirit, we return the port to the free port pool only after tunnel\n// deletion goes well.\n+ let stream = match make_babel_stream() {\n+ Ok(stream) => stream,\n+ Err(e) => {\n+ warn!(\"Tunnel GC failed to open babel stream with {:?}\", e);\n+ return Err(e);\n+ }\n+ };\n+ let mut babel = Babel::new(stream);\n+ let res = babel.start_connection();\n+ if res.is_err() {\n+ warn!(\"Failed to start Babel RPC connection! {:?}\", res);\n+ bail!(\"Failed to start Babel RPC connection!\");\n+ }\n+\nlet res = babel.unmonitor(&tunnel.iface_name);\nif res.is_err() {\nwarn!(\"Failed to unmonitor {} with {:?}\", tunnel.iface_name, res);\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Only connect to babel if tunnels actually need removal
20,244
19.05.2019 07:17:29
14,400
55a834a918fe2b9bfa2fccd8a0aec216d96933bd
Batch DebtKeeper updates
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/debt_keeper/mod.rs", "new_path": "rita/src/rita_common/debt_keeper/mod.rs", "diff": "@@ -13,6 +13,7 @@ use crate::rita_common::payment_controller;\nuse crate::rita_common::payment_controller::PaymentController;\nuse crate::rita_common::payment_validator::PAYMENT_TIMEOUT;\nuse crate::rita_common::tunnel_manager::TunnelAction;\n+use crate::rita_common::tunnel_manager::TunnelChange;\nuse crate::rita_common::tunnel_manager::TunnelManager;\nuse crate::rita_common::tunnel_manager::TunnelStateChange;\nuse crate::SETTING;\n@@ -189,16 +190,20 @@ impl Handler<SendUpdate> for DebtKeeper {\nfn handle(&mut self, _msg: SendUpdate, _ctx: &mut Context<Self>) -> Self::Result {\ntrace!(\"sending debt keeper update\");\n+ // in order to keep from overloading actix when we have thousands of debts to process\n+ // (mainly on exits) we batch tunnel change operations before sending them over\n+ let mut debts_message = Vec::new();\n+\nfor (k, _) in self.debt_data.clone() {\nmatch self.send_update(&k)? {\nDebtAction::SuspendTunnel => {\n- TunnelManager::from_registry().do_send(TunnelStateChange {\n+ debts_message.push(TunnelChange {\nidentity: k,\naction: TunnelAction::PaymentOverdue,\n});\n}\nDebtAction::OpenTunnel => {\n- TunnelManager::from_registry().do_send(TunnelStateChange {\n+ debts_message.push(TunnelChange {\nidentity: k,\naction: TunnelAction::PaidOnTime,\n});\n@@ -215,6 +220,10 @@ impl Handler<SendUpdate> for DebtKeeper {\n})),\n}\n}\n+\n+ TunnelManager::from_registry().do_send(TunnelStateChange {\n+ tunnels: debts_message,\n+ });\nOk(())\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -793,38 +793,57 @@ impl TunnelManager {\n}\n}\n-pub struct TunnelStateChange {\n+pub struct TunnelChange {\npub identity: Identity,\npub action: TunnelAction,\n}\n+pub struct TunnelStateChange {\n+ pub tunnels: Vec<TunnelChange>,\n+}\n+\nimpl Message for TunnelStateChange {\ntype Result = Result<(), Error>;\n}\n-// Called by DAOManager to notify TunnelManager about the registration state of a given peer\n-// also called by DebtKeeper when someone doesn't pay their bill\n+// Called by DebtKeeper with the updated billing status of every tunnel every round\nimpl Handler<TunnelStateChange> for TunnelManager {\ntype Result = Result<(), Error>;\nfn handle(&mut self, msg: TunnelStateChange, _: &mut Context<Self>) -> Self::Result {\n+ for tunnel in msg.tunnels {\n+ let res = tunnel_state_change(tunnel, &mut self.tunnels);\n+ if res.is_err() {\n+ error!(\"Tunnel state change failed with {:?}\", res);\n+ }\n+ }\n+ Ok(())\n+ }\n+}\n+\n+fn tunnel_state_change(\n+ msg: TunnelChange,\n+ tunnels: &mut HashMap<Identity, Vec<Tunnel>>,\n+) -> Result<(), Error> {\n+ let id = msg.identity;\n+ let action = msg.action;\ntrace!(\n\"Tunnel state change request for {:?} with action {:?}\",\n- msg.identity,\n- msg.action\n+ id,\n+ action,\n);\nlet mut tunnel_bw_limits_need_change = false;\n// Find a tunnel\n- match self.tunnels.get_mut(&msg.identity) {\n+ match tunnels.get_mut(&id) {\nSome(tunnels) => {\nfor tunnel in tunnels.iter_mut() {\n- trace!(\"Handle action {} on tunnel {:?}\", msg.action, tunnel);\n- match msg.action {\n+ trace!(\"Handle action {} on tunnel {:?}\", action, tunnel);\n+ match action {\nTunnelAction::MembershipConfirmed => {\ntrace!(\n\"Membership confirmed for identity {:?} returned tunnel {:?}\",\n- msg.identity,\n+ id,\ntunnel\n);\nmatch tunnel.state.registration_state {\n@@ -838,12 +857,11 @@ impl Handler<TunnelStateChange> for TunnelManager {\n}\n}\nTunnelAction::MembershipExpired => {\n- trace!(\"Membership for identity {:?} is expired\", msg.identity);\n+ trace!(\"Membership for identity {:?} is expired\", id);\nmatch tunnel.state.registration_state {\nRegistrationState::Registered => {\ntunnel.unmonitor(make_babel_stream()?)?;\n- tunnel.state.registration_state =\n- RegistrationState::NotRegistered;\n+ tunnel.state.registration_state = RegistrationState::NotRegistered;\n}\nRegistrationState::NotRegistered => {\ncontinue;\n@@ -851,7 +869,7 @@ impl Handler<TunnelStateChange> for TunnelManager {\n}\n}\nTunnelAction::PaidOnTime => {\n- trace!(\"identity {:?} has paid!\", msg.identity);\n+ trace!(\"identity {:?} has paid!\", id);\nmatch tunnel.state.payment_state {\nPaymentState::Paid => {\ncontinue;\n@@ -864,7 +882,7 @@ impl Handler<TunnelStateChange> for TunnelManager {\n}\n}\nTunnelAction::PaymentOverdue => {\n- trace!(\"No payment from identity {:?}\", msg.identity);\n+ trace!(\"No payment from identity {:?}\", id);\nmatch tunnel.state.payment_state {\nPaymentState::Paid => {\ntrace!(\"Tunnel {:?} has entered an overdue state.\", tunnel);\n@@ -883,13 +901,13 @@ impl Handler<TunnelStateChange> for TunnelManager {\n// This is now pretty common since there's no more none action\n// and exits have identities for all clients (active or not)\n// on hand\n- trace!(\"Couldn't find tunnel for identity {:?}\", msg.identity);\n+ trace!(\"Couldn't find tunnel for identity {:?}\", id);\n}\n}\n// this is done ouside of the match to make the borrow checker happy\nif tunnel_bw_limits_need_change {\n- let res = tunnel_bw_limit_update(&self.tunnels);\n+ let res = tunnel_bw_limit_update(&tunnels);\n// if this fails consistently it could be a wallet draining attack\n// TODO check for that case\nif res.is_err() {\n@@ -899,7 +917,6 @@ impl Handler<TunnelStateChange> for TunnelManager {\nOk(())\n}\n-}\n/// Takes the tunnels list and iterates over it to update all of the traffic control settings\n/// since we can't figure out how to combine interfaces badnwidth budgets we're subdividing it\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Batch DebtKeeper updates
20,244
19.05.2019 07:18:20
14,400
b2554d06380d08a40ca030030f92173dc3c1cf72
Reduce babel operation timeout
[ { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "@@ -15,7 +15,7 @@ use std::net::TcpStream;\nuse std::str;\nuse std::time::Duration;\n-const BABEL_OPERATION_TIMEOUT: Duration = Duration::from_secs(4);\n+const BABEL_OPERATION_TIMEOUT: Duration = Duration::from_secs(1);\n#[derive(Debug, Fail)]\npub enum BabelMonitorError {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Reduce babel operation timeout
20,244
19.05.2019 19:45:56
14,400
221a3cb381b31ce901c6968cb8d71a3a4ecd7c6b
Improve logging of tunnel state changes
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -875,7 +875,10 @@ fn tunnel_state_change(\ncontinue;\n}\nPaymentState::Overdue => {\n- trace!(\"Tunnel {:?} has returned to a paid state.\", tunnel);\n+ info!(\n+ \"Tunnel {} has returned to a paid state.\",\n+ tunnel.neigh_id.global.wg_public_key\n+ );\ntunnel.state.payment_state = PaymentState::Paid;\ntunnel_bw_limits_need_change = true;\n}\n@@ -885,7 +888,10 @@ fn tunnel_state_change(\ntrace!(\"No payment from identity {:?}\", id);\nmatch tunnel.state.payment_state {\nPaymentState::Paid => {\n- trace!(\"Tunnel {:?} has entered an overdue state.\", tunnel);\n+ info!(\n+ \"Tunnel {} has entered an overdue state.\",\n+ tunnel.neigh_id.global.wg_public_key\n+ );\ntunnel.state.payment_state = PaymentState::Overdue;\ntunnel_bw_limits_need_change = true;\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Improve logging of tunnel state changes
20,244
20.05.2019 07:50:14
14,400
c08f333b04caf3c880e4e691837e0ea1a11d5021
Bump payment timeout to an hour With the way Eth is working right now this is much more reasonable
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_validator/mod.rs", "new_path": "rita/src/rita_common/payment_validator/mod.rs", "diff": "@@ -26,11 +26,12 @@ use std::time::{Duration, Instant};\nuse web3::client::Web3;\nuse web3::types::TransactionResponse;\n-// Discard payments after 15 minutes of failing to find txid\n-pub const PAYMENT_TIMEOUT: Duration = Duration::from_secs(900u64);\n+// Discard payments after 1 hour of failing to find txid\n+pub const PAYMENT_TIMEOUT: Duration = Duration::from_secs(3600u64);\n// How many blocks before we assume finality\nconst BLOCKS_TO_CONFIRM: u32 = 4;\n// How old does a txid need to be before we don't accept it?\n+// this is 12 hours\nconst BLOCKS_TO_OLD: u32 = 1440;\n#[derive(PartialEq, Eq, Hash, Clone, Debug)]\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Bump payment timeout to an hour With the way Eth is working right now this is much more reasonable
20,244
20.05.2019 12:09:31
14,400
cab6df42dc178cf1aa0b4a6070b0d2ee095373ab
Log bandwidth limit updates and database connection time
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -928,6 +928,7 @@ fn tunnel_state_change(\n/// since we can't figure out how to combine interfaces badnwidth budgets we're subdividing it\n/// here with manual terminal commands whenever there is a change\nfn tunnel_bw_limit_update(tunnels: &HashMap<Identity, Vec<Tunnel>>) -> Result<(), Error> {\n+ info!(\"Running tunnel bw limit update!\");\n// number of interfaces over which we will have to divide free tier BW\nlet mut limited_interfaces = 0u16;\nfor sublist in tunnels.iter() {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -57,12 +57,19 @@ pub mod struct_tools;\n/// Gets the Postgres database connection\npub fn get_database_connection() -> Result<PgConnection, ConnectionError> {\nlet db_uri = SETTING.get_db_uri();\n+ let start = Instant::now();\ninfo!(\"Opening database connection {:?}\", db_uri);\nif db_uri.contains(\"postgres://\")\n|| db_uri.contains(\"postgresql://\")\n|| db_uri.contains(\"psql://\")\n{\n- PgConnection::establish(&db_uri)\n+ let conn = PgConnection::establish(&db_uri);\n+ info!(\n+ \"It took {}s {}ms to open the database connection\",\n+ start.elapsed().as_secs(),\n+ start.elapsed().subsec_millis()\n+ );\n+ conn\n} else {\npanic!(\"You must provide a valid postgressql database uri!\");\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Log bandwidth limit updates and database connection time
20,244
20.05.2019 17:27:18
14,400
844e1149d1228508bfa5e18c8087d40fdb771e83
Bump for Beta5 RC2
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -173,7 +173,7 @@ dependencies = [\nname = \"althea_rs\"\nversion = \"0.1.10\"\ndependencies = [\n- \"rita 0.4.3\",\n+ \"rita 0.4.4\",\n]\n[[package]]\n@@ -2062,7 +2062,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.4.3\"\n+version = \"0.4.4\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "[package]\nname = \"rita\"\n-version = \"0.4.3\"\n+version = \"0.4.4\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/own_info.rs", "new_path": "rita/src/rita_common/dashboard/own_info.rs", "diff": "@@ -6,7 +6,7 @@ use clarity::Address;\nuse failure::Error;\nuse num256::{Int256, Uint256};\n-pub static READABLE_VERSION: &str = \"Beta 5 RC1\";\n+pub static READABLE_VERSION: &str = \"Beta 5 RC2\";\n#[derive(Serialize)]\npub struct OwnInfo {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Bump for Beta5 RC2
20,244
20.05.2019 17:45:45
14,400
b9649525e3d2aefff5820b9b05520d7c05dc8d06
Use Lettre crate
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -667,8 +667,8 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\n[[package]]\nname = \"email\"\n-version = \"0.0.19\"\n-source = \"git+https://github.com/lettre/rust-email#3086d7bcda2c3b3fa4b1297cba216151ce4a3efc\"\n+version = \"0.0.20\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\ndependencies = [\n\"base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -1210,10 +1210,10 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\n[[package]]\nname = \"lettre\"\n-version = \"0.9.0\"\n-source = \"git+https://github.com/lettre/lettre.git#c988b1760ad8179d9e7f3fb8594d2b86cf2a0a49\"\n+version = \"0.9.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\ndependencies = [\n- \"base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"bufstream 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -1229,14 +1229,14 @@ dependencies = [\n[[package]]\nname = \"lettre_email\"\n-version = \"0.9.0\"\n-source = \"git+https://github.com/lettre/lettre.git#c988b1760ad8179d9e7f3fb8594d2b86cf2a0a49\"\n+version = \"0.9.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\ndependencies = [\n- \"base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"email 0.0.19 (git+https://github.com/lettre/rust-email)\",\n+ \"base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"email 0.0.20 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"lettre 0.9.0 (git+https://github.com/lettre/lettre.git)\",\n+ \"lettre 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"uuid 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -2088,8 +2088,8 @@ dependencies = [\n\"handlebars 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"ipnetwork 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"lettre 0.9.0 (git+https://github.com/lettre/lettre.git)\",\n- \"lettre_email 0.9.0 (git+https://github.com/lettre/lettre.git)\",\n+ \"lettre 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"lettre_email 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"libsqlite3-sys 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"minihttpse 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -3147,7 +3147,7 @@ dependencies = [\n\"checksum dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"c0d0a1279c96732bc6800ce6337b6a614697b0e74ae058dc03c62ebeb78b4d86\"\n\"checksum dtoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"6d301140eb411af13d3115f9a562c85cc6b541ade9dfa314132244aaee7489dd\"\n\"checksum either 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"c67353c641dc847124ea1902d69bd753dee9bb3beff9aa3662ecf86c971d1fac\"\n-\"checksum email 0.0.19 (git+https://github.com/lettre/rust-email)\" = \"<none>\"\n+\"checksum email 0.0.20 (registry+https://github.com/rust-lang/crates.io-index)\" = \"91549a51bb0241165f13d57fc4c72cef063b4088fb078b019ecbf464a45f22e4\"\n\"checksum encoding 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)\" = \"6b0d943856b990d12d3b55b359144ff341533e516d94098b1d3fc1ac666d36ec\"\n\"checksum encoding-index-japanese 1.20141219.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"04e8b2ff42e9a05335dbf8b5c6f7567e5591d0d916ccef4e0b1710d32a0d0c91\"\n\"checksum encoding-index-korean 1.20141219.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"4dc33fb8e6bcba213fe2f14275f0963fd16f0a02c878e3095ecfdf5bee529d81\"\n@@ -3207,8 +3207,8 @@ dependencies = [\n\"checksum lazy_static 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)\" = \"76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73\"\n\"checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14\"\n\"checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f\"\n-\"checksum lettre 0.9.0 (git+https://github.com/lettre/lettre.git)\" = \"<none>\"\n-\"checksum lettre_email 0.9.0 (git+https://github.com/lettre/lettre.git)\" = \"<none>\"\n+\"checksum lettre 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"646aee0a55545eaffdf0df1ac19b500b51adb3095ec4dfdc704134e56ea23531\"\n+\"checksum lettre_email 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"ae1b3d43e4bb7beb9974a359cbb3ea4f93dfba6c1c0c6e9c9f82e538e0f9ab9f\"\n\"checksum libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)\" = \"aab692d7759f5cd8c859e169db98ae5b52c924add2af5fbbca11d12fefb567c1\"\n\"checksum libflate 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)\" = \"54d1ddf9c52870243c5689d7638d888331c1116aa5b398f3ba1acfa7d8758ca1\"\n\"checksum libsqlite3-sys 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"d3711dfd91a1081d2458ad2d06ea30a8755256e74038be2ad927d94e1c955ca8\"\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "@@ -60,8 +60,8 @@ num-traits=\"0.2\"\nclarity = \"0.1\"\neui48 = \"0.4\"\narrayvec = {version= \"0.4\", features = [\"serde-1\"]}\n-lettre = {git=\"https://github.com/lettre/lettre.git\"}\n-lettre_email = {git=\"https://github.com/lettre/lettre.git\"}\n+lettre = \"0.9\"\n+lettre_email = \"0.9\"\nphonenumber = \"0.2\"\n[features]\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Use Lettre crate
20,244
20.05.2019 17:57:29
14,400
a331a1b73339f770c1d2baa1c1e75e825493ed8f
Log the full node for all request failures Starting to suspect the recent exit lag issues are centered here
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/wallet.rs", "new_path": "rita/src/rita_common/dashboard/wallet.rs", "diff": "@@ -65,7 +65,7 @@ pub fn withdraw(path: Path<(Address, u64)>) -> Box<dyn Future<Item = HttpRespons\nHttpResponse::Ok().json(format!(\"txid:{:#066x}\", tx_id))\n})),\nErr(e) => {\n- update_nonce(our_address, &web3);\n+ update_nonce(our_address, &web3, full_node);\nif e.to_string().contains(\"nonce\") {\nBox::new(future::ok(\nHttpResponse::new(StatusCode::from_u16(504u16).unwrap())\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/oracle/mod.rs", "new_path": "rita/src/rita_common/oracle/mod.rs", "diff": "@@ -85,12 +85,12 @@ impl Handler<Update> for Oracle {\ndrop(payment_settings);\ninfo!(\"About to make web3 requests to {}\", full_node);\n- update_balance(our_address, &web3);\n+ update_balance(our_address, &web3, full_node.clone());\n// removed and placed into error handling in payment controller\n// time will tell if that was a good idea\n//update_nonce(our_address, &web3);\n- update_gas_price(&web3);\n- get_net_version(&web3);\n+ update_gas_price(&web3, full_node.clone());\n+ get_net_version(&web3, full_node);\nif oracle_enabled {\nupdate_our_price();\n}\n@@ -102,12 +102,15 @@ impl Handler<Update> for Oracle {\n/// Gets the balance for the provided eth address and updates it\n/// in the global SETTING variable, do not use this function as a generic\n/// balance getter.\n-fn update_balance(our_address: Address, web3: &Web3) {\n+fn update_balance(our_address: Address, web3: &Web3, full_node: String) {\nlet res = web3\n.eth_get_balance(our_address)\n- .then(|balance| match balance {\n+ .then(move |balance| match balance {\nOk(value) => {\n- info!(\"Got response from balance request {:?}\", value);\n+ info!(\n+ \"Got response from {} balance request {:?}\",\n+ full_node, value\n+ );\nlet our_balance = &mut SETTING.get_payment_mut().balance;\n// if our balance is not zero and the response we get from the full node\n// is zero either we very carefully emptied our wallet or it's that annoying Geth bug\n@@ -117,7 +120,7 @@ fn update_balance(our_address: Address, web3: &Web3) {\nOk(())\n}\nErr(e) => {\n- warn!(\"Balance request failed with {:?}\", e);\n+ warn!(\"Balance request to {} failed with {:?}\", full_node, e);\nErr(e)\n}\n})\n@@ -132,11 +135,11 @@ fn update_balance(our_address: Address, web3: &Web3) {\n/// a different network than the one we are actually using. For example an address\n/// that contains both real eth and test eth may be tricked into singing a transaction\n/// for real eth while operating on the testnet. Because of this we have warnings behavior\n-fn get_net_version(web3: &Web3) {\n+fn get_net_version(web3: &Web3, full_node: String) {\nlet res = web3.net_version()\n- .then(|net_version| match net_version {\n+ .then(move |net_version| match net_version {\nOk(value) => {\n- info!(\"Got response from net_version request {:?}\", value);\n+ info!(\"Got response from {} for net_version request {:?}\", full_node, value);\nmatch value.parse::<u64>() {\nOk(net_id_num) => {\nlet mut payment_settings = SETTING.get_payment_mut();\n@@ -156,7 +159,7 @@ fn get_net_version(web3: &Web3) {\nOk(())\n}\nErr(e) => {\n- warn!(\"net_version request failed with {:?}\", e);\n+ warn!(\"net_version request to {} failed with {:?}\", full_node, e);\nErr(e)\n}\n}).then(|_| Ok(()));\n@@ -172,18 +175,21 @@ fn get_net_version(web3: &Web3) {\n/// A potential attack here would be providing a lower nonce to cause you to replace an earlier transaction\n/// that is still unconfirmed. That's a bit of a streach, more realistiically this would be spoofed in conjunction\n/// with net_version\n-pub fn update_nonce(our_address: Address, web3: &Web3) {\n+pub fn update_nonce(our_address: Address, web3: &Web3, full_node: String) {\nlet res = web3\n.eth_get_transaction_count(our_address)\n- .then(|transaction_count| match transaction_count {\n+ .then(move |transaction_count| match transaction_count {\nOk(value) => {\n- info!(\"Got response from nonce request {:?}\", value);\n+ info!(\n+ \"Got response from {} for nonce request {:?}\",\n+ full_node, value\n+ );\nlet mut payment_settings = SETTING.get_payment_mut();\npayment_settings.nonce = value;\nOk(())\n}\nErr(e) => {\n- warn!(\"nonce request failed with {:?}\", e);\n+ warn!(\"nonce request to {} failed with {:?}\", full_node, e);\nErr(e)\n}\n})\n@@ -198,12 +204,15 @@ pub fn update_nonce(our_address: Address, web3: &Web3) {\n/// (or whatever they care to configure as dyanmic_fee_factor). This also handles dramatic spikes in\n/// gas prices by increasing the maximum debt before a drop to the free tier occurs. So if the blockchain\n/// is simply to busy to use for some period of time payments will simply wait.\n-fn update_gas_price(web3: &Web3) {\n+fn update_gas_price(web3: &Web3, full_node: String) {\nlet res = web3\n.eth_gas_price()\n- .then(|gas_price| match gas_price {\n+ .then(move |gas_price| match gas_price {\nOk(value) => {\n- info!(\"Got response from gas price request {:?}\", value);\n+ info!(\n+ \"Got response from {} for gas price request {:?}\",\n+ full_node, value\n+ );\n// Dynamic fee computation\nlet mut payment_settings = SETTING.get_payment_mut();\n@@ -241,7 +250,7 @@ fn update_gas_price(web3: &Web3) {\nOk(())\n}\nErr(e) => {\n- warn!(\"gas price request failed with {:?}\", e);\n+ warn!(\"gas price request to {} failed with {:?}\", full_node, e);\nErr(e)\n}\n})\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "@@ -188,7 +188,7 @@ impl PaymentController {\n// because by the time you're back here it's been reset by the oracle\n// so now we only update nonces when we get an error, otherwise it should\n// remain internally consistent and correct\n- update_nonce(our_address, &web3);\n+ update_nonce(our_address, &web3, full_node);\nDebtKeeper::from_registry().do_send(PaymentFailed {\nto: pmt.to,\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_validator/mod.rs", "new_path": "rita/src/rita_common/payment_validator/mod.rs", "diff": "@@ -126,14 +126,17 @@ impl Handler<Validate> for PaymentValidator {\ntype Result = ();\nfn handle(&mut self, _msg: Validate, _ctx: &mut Context<Self>) -> Self::Result {\n- trace!(\n+ info!(\n\"Attempting to validate {} transactions\",\nself.unvalidated_transactions.len()\n);\nlet mut to_delete = Vec::new();\nfor item in self.unvalidated_transactions.iter() {\nif item.recieved.elapsed() > PAYMENT_TIMEOUT {\n- error!(\"Transaction {:?} has timed out, payment failed!\", item);\n+ error!(\n+ \"Transaction {:#066x} has timed out, payment failed!\",\n+ item.payment.txid.clone().unwrap()\n+ );\nto_delete.push(item.clone());\n} else {\nvalidate_transaction(item);\n@@ -173,7 +176,11 @@ pub fn validate_transaction(ts: &ToValidate) {\n},\nErr(e) => {\n// full node failure, we don't actually know anything about the transaction\n- warn!(\"Failed to validate {:?} transaction with {:?}\", pmt.from, e);\n+ warn!(\n+ \"Failed to validate {:#066x} transaction with {:?}\",\n+ pmt.txid.unwrap(),\n+ e\n+ );\nOk(())\n}\n}),\n@@ -181,7 +188,11 @@ pub fn validate_transaction(ts: &ToValidate) {\n}\nErr(e) => {\n// full node failure, we don't actually know anything about the transaction\n- warn!(\"Failed to validate {:?} transaction with {:?}\", pmt.from, e);\n+ warn!(\n+ \"Failed to get blocknum to validate {:#066x} transaction with {:?}\",\n+ pmt.txid.unwrap(),\n+ e\n+ );\nEither::B(future::ok(()))\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Log the full node for all request failures Starting to suspect the recent exit lag issues are centered here
20,244
21.05.2019 07:30:37
14,400
986333ba80103c973ea7ee063bcffbf0694f59ca
Move Exit loop to it's own thread See the new comment at the top of the rita_exit rita_loop file for a full explanation of what's been done here. It's rather involved
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "//! tied together with message calls.\n//!\n//! In this loop the exit checks it's database for registered users and deploys the endpoint for\n-//! their exit tunnel\n+//! their exit tunnel the execution model for all of this is pretty whacky thanks to Actix quirks\n+//! we have the usual actors, these actors process Async events, but we have database queries by\n+//! Diesel that are syncronous so we create a special actix construct called a 'sync actor' that\n+//! is really another thread dedicated to running an actor which may block. Since it's another thread\n+//! the block now only halts the single actor. In order to run an actor like this regularly we would like\n+//! to use the run_interval closure setup, but that's only implemented for normal Async actors, likewise\n+//! the system service setup which lets us use from_registry also doesn't work with SyncActors\n+//! so as a workaround for both of those we have an actor Ritaloop which creates the SyncActor thread\n+//! and address on startup and then proceeds to spawn futures there using it's own loop.\n+//!\n+//! Crash behavior is really where this starts to cause issues, SyncActors can't really crash\n+//! they will always be ready for another message, AsyncActors on the other hand can, which is why\n+//! this one is marked as a system service, so that it will be restarted. But when it's restarted it\n+//! will create another SyncActor loop and addres to send messages to! Hopefully the borro checker and\n+//! actix work together on this on properly, not that I've every seen simple actors like the loop crash\n+//! very often.\nuse crate::rita_exit::database::struct_tools::clients_to_ids;\nuse crate::rita_exit::database::{\n@@ -11,21 +26,23 @@ use crate::rita_exit::database::{\n};\nuse crate::rita_exit::traffic_watcher::{TrafficWatcher, Watch};\nuse crate::SETTING;\n-use actix::prelude::{\n- Actor, ActorContext, Addr, Arbiter, AsyncContext, Context, Handler, Message, Supervised,\n- SystemService,\n+use actix::{\n+ Actor, ActorContext, Arbiter, AsyncContext, Context, Handler, Message, Supervised, SyncArbiter,\n+ SyncContext, SystemService,\n};\nuse diesel::query_dsl::RunQueryDsl;\nuse exit_db::models;\nuse failure::Error;\n-use futures::future::Future;\nuse settings::exit::RitaExitSettings;\nuse std::collections::HashMap;\nuse std::net::IpAddr;\nuse std::time::Duration;\n#[derive(Default)]\n-pub struct RitaLoop {\n+pub struct RitaLoop {}\n+\n+#[derive(Default)]\n+pub struct RitaSyncLoop {\n/// a simple cache to prevent regularly asking Maxmind for the same geoip data\npub geoip_cache: HashMap<IpAddr, String>,\n}\n@@ -38,19 +55,23 @@ impl Actor for RitaLoop {\nfn started(&mut self, ctx: &mut Context<Self>) {\ninfo!(\"exit loop started\");\n- ctx.run_interval(Duration::from_secs(EXIT_LOOP_SPEED), |_act, ctx| {\n- // we add a timeout on the loop future here as a hacky way to timeout\n- // the databse connection since diesel doesn't provide such a feature\n- let addr: Addr<Self> = ctx.address();\n- let fut = addr\n- .send(Tick)\n- .timeout(Duration::from_secs(4))\n- .then(|_result| Ok(()) as Result<(), ()>);\n- Arbiter::spawn(fut);\n+ let addr = SyncArbiter::start(1, || RitaSyncLoop {\n+ geoip_cache: HashMap::new(),\n+ });\n+ ctx.run_interval(Duration::from_secs(EXIT_LOOP_SPEED), move |_act, _ctx| {\n+ addr.do_send(Tick)\n});\n}\n}\n+impl Actor for RitaSyncLoop {\n+ type Context = SyncContext<Self>;\n+\n+ fn started(&mut self, _ctx: &mut SyncContext<Self>) {\n+ info!(\"exit sync loop started\");\n+ }\n+}\n+\nimpl SystemService for RitaLoop {}\nimpl Supervised for RitaLoop {\nfn restarting(&mut self, _ctx: &mut Context<RitaLoop>) {\n@@ -58,6 +79,12 @@ impl Supervised for RitaLoop {\n}\n}\n+impl Supervised for RitaSyncLoop {\n+ fn restarting(&mut self, _ctx: &mut SyncContext<RitaSyncLoop>) {\n+ error!(\"Rita Exit Sync loop actor died! recovering!\");\n+ }\n+}\n+\n/// Used to test actor respawning\npub struct Crash;\n@@ -79,9 +106,9 @@ impl Message for Tick {\ntype Result = Result<(), Error>;\n}\n-impl Handler<Tick> for RitaLoop {\n+impl Handler<Tick> for RitaSyncLoop {\ntype Result = Result<(), Error>;\n- fn handle(&mut self, _: Tick, _ctx: &mut Context<Self>) -> Self::Result {\n+ fn handle(&mut self, _: Tick, _ctx: &mut SyncContext<Self>) -> Self::Result {\nuse exit_db::schema::clients::dsl::clients;\ntrace!(\"Exit tick!\");\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Move Exit loop to it's own thread See the new comment at the top of the rita_exit rita_loop file for a full explanation of what's been done here. It's rather involved
20,244
21.05.2019 11:08:34
14,400
a0ff6dc9cb4da589e1c94cb71b5e54b641a0bc11
Increase registration timeout dramatically This seems to be much much slower than its should be on the exit side adding logging on the exit and more leeway on the client.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/exit_manager/mod.rs", "new_path": "rita/src/rita_client/exit_manager/mod.rs", "diff": "@@ -120,7 +120,7 @@ pub fn send_exit_setup_request(\nstream.from_err().and_then(move |stream| {\nclient::post(&endpoint)\n- .timeout(Duration::from_secs(8))\n+ .timeout(Duration::from_secs(600))\n.with_connection(Connection::from_stream(stream))\n.json(ident)\n.unwrap()\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -143,7 +143,10 @@ pub fn signup_client(client: ExitClientIdentity) -> Result<ExitState, Error> {\nupdate_client(&client, &conn)?;\nget_client(client_mesh_ip, &conn)?\n} else {\n- trace!(\"record does not exist, creating\");\n+ info!(\n+ \"record for {} does not exist, creating\",\n+ client.global.wg_public_key\n+ );\nlet new_ip = get_next_client_ip(&conn)?;\n@@ -156,7 +159,7 @@ pub fn signup_client(client: ExitClientIdentity) -> Result<ExitState, Error> {\nlet c = client_to_new_db_client(&client, new_ip, user_country);\n- trace!(\"Inserting new client\");\n+ info!(\"Inserting new client {}\", client.global.wg_public_key);\ndiesel::insert_into(clients).values(&c).execute(&conn)?;\nc\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/sms.rs", "new_path": "rita/src/rita_exit/database/sms.rs", "diff": "@@ -77,7 +77,10 @@ pub fn handle_sms_registration(\napi_key: String,\nconn: &PgConnection,\n) -> Result<ExitState, Error> {\n- trace!(\"Handling phone registration for {:?}\", client);\n+ info!(\n+ \"Handling phone registration for {}\",\n+ client.global.wg_public_key\n+ );\nlet text_num = texts_sent(their_record);\nlet sent_more_than_allowed_texts = text_num > 10;\nmatch (\n@@ -89,6 +92,11 @@ pub fn handle_sms_registration(\n(Some(number), Some(code), true) => {\nif check_text(number, code, api_key)? {\nverify_client(&client, true, conn)?;\n+\n+ info!(\n+ \"Phone registration complete for {}\",\n+ client.global.wg_public_key\n+ );\nOk(ExitState::Registered {\nour_details: ExitClientDetails {\nclient_internal_ip: their_record.internal_ip.parse()?,\n@@ -127,6 +135,11 @@ pub fn handle_sms_registration(\n(Some(number), Some(code), false) => {\nif check_text(number, code, api_key)? {\nverify_client(&client, true, conn)?;\n+\n+ info!(\n+ \"Phone registration complete for {}\",\n+ client.global.wg_public_key\n+ );\nOk(ExitState::Registered {\nour_details: ExitClientDetails {\nclient_internal_ip: their_record.internal_ip.parse()?,\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/network_endpoints/mod.rs", "new_path": "rita/src/rita_exit/network_endpoints/mod.rs", "diff": "@@ -25,7 +25,10 @@ use std::time::SystemTime;\npub fn setup_request(\ntheir_id: (Json<ExitClientIdentity>, HttpRequest),\n) -> Result<Json<ExitState>, Error> {\n- trace!(\"Received requester identity for setup, {:?}\", their_id.0);\n+ info!(\n+ \"Received setup request from, {}\",\n+ their_id.0.global.wg_public_key\n+ );\nlet client_mesh_ip = their_id.0.global.mesh_ip;\nlet client = their_id.0.into_inner();\nlet remote_mesh_socket: SocketAddr = their_id\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Increase registration timeout dramatically This seems to be much much slower than its should be on the exit side adding logging on the exit and more leeway on the client.
20,244
21.05.2019 13:42:29
14,400
3dfd1036e63831ec492b1c08591a493bebe811b7
Exit loop every 30 seconds It doesn't seem like the exit loop reliably finishes in 5 seconds anymore, so lets just bump this
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "@@ -48,7 +48,7 @@ pub struct RitaSyncLoop {\n}\n// the speed in seconds for the exit loop\n-pub const EXIT_LOOP_SPEED: u64 = 5;\n+pub const EXIT_LOOP_SPEED: u64 = 30;\nimpl Actor for RitaLoop {\ntype Context = Context<Self>;\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Exit loop every 30 seconds It doesn't seem like the exit loop reliably finishes in 5 seconds anymore, so lets just bump this
20,244
21.05.2019 16:08:22
14,400
4e3240429702623f14d55a1a7a9cfa15f07ae039
Split rita common loop into fast and slow
[ { "change_type": "MODIFY", "old_path": "rita/src/client.rs", "new_path": "rita/src/client.rs", "diff": "@@ -48,6 +48,9 @@ mod middleware;\nmod rita_client;\nmod rita_common;\n+use rita_common::rita_loop::fast_loop::RitaFastLoop;\n+use rita_common::rita_loop::slow_loop::RitaSlowLoop;\n+\nuse crate::rita_client::dashboard::eth_private_key::*;\nuse crate::rita_client::dashboard::exits::*;\nuse crate::rita_client::dashboard::interfaces::*;\n@@ -328,7 +331,8 @@ fn main() {\n.shutdown_timeout(0)\n.start();\n- assert!(rita_common::rita_loop::RitaLoop::from_registry().connected());\n+ assert!(RitaFastLoop::from_registry().connected());\n+ assert!(RitaSlowLoop::from_registry().connected());\nassert!(rita_client::rita_loop::RitaLoop::from_registry().connected());\nsystem.run();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/exit.rs", "new_path": "rita/src/exit.rs", "diff": "@@ -45,6 +45,9 @@ mod middleware;\nmod rita_common;\nmod rita_exit;\n+use rita_common::rita_loop::fast_loop::RitaFastLoop;\n+use rita_common::rita_loop::slow_loop::RitaSlowLoop;\n+\nuse crate::rita_common::dashboard::babel::*;\nuse crate::rita_common::dashboard::dao::*;\nuse crate::rita_common::dashboard::debts::*;\n@@ -275,7 +278,8 @@ fn main() {\n.shutdown_timeout(0)\n.start();\n- assert!(rita_common::rita_loop::RitaLoop::from_registry().connected());\n+ assert!(RitaFastLoop::from_registry().connected());\n+ assert!(RitaSlowLoop::from_registry().connected());\nassert!(rita_exit::rita_loop::RitaLoop::from_registry().connected());\nsystem.run();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/oracle/mod.rs", "new_path": "rita/src/rita_common/oracle/mod.rs", "diff": "@@ -61,15 +61,8 @@ impl Default for Oracle {\n}\n}\n-/// How often we update all the Oracle values, currently every eth block\n-pub const ORACLE_UPDATE_RATE: Duration = Duration::from_secs(15);\npub const ORACLE_TIMEOUT: Duration = Duration::from_secs(1);\n-/// True if an update should occur\n-fn timer_check(timestamp: Instant) -> bool {\n- Instant::now() - timestamp > ORACLE_UPDATE_RATE\n-}\n-\n#[derive(Message)]\npub struct Update();\n@@ -77,7 +70,6 @@ impl Handler<Update> for Oracle {\ntype Result = ();\nfn handle(&mut self, _msg: Update, _ctx: &mut Context<Self>) -> Self::Result {\n- if timer_check(self.last_updated) {\nlet payment_settings = SETTING.get_payment();\nlet full_node = get_web3_server();\nlet web3 = Web3::new(&full_node, ORACLE_TIMEOUT);\n@@ -98,7 +90,6 @@ impl Handler<Update> for Oracle {\nself.last_updated = Instant::now();\n}\n}\n-}\n/// Gets the balance for the provided eth address and updates it\n/// in the global SETTING variable, do not use this function as a generic\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/peer_listener/mod.rs", "new_path": "rita/src/rita_common/peer_listener/mod.rs", "diff": "//! off the queue. These are turned into Peer structs which are passed to TunnelManager to do\n//! whatever remaining work there may be.\n-use crate::rita_common::rita_loop::Tick;\n+use crate::rita_common::rita_loop::fast_loop::Tick;\nuse crate::KI;\nuse crate::SETTING;\nuse ::actix::{Actor, Context};\n" }, { "change_type": "ADD", "old_path": null, "new_path": "rita/src/rita_common/rita_loop/fast_loop.rs", "diff": "+use crate::actix_utils::KillActor;\n+use crate::actix_utils::ResolverWrapper;\n+use crate::rita_common::debt_keeper::{DebtKeeper, SendUpdate};\n+use crate::rita_common::peer_listener::GetPeers;\n+use crate::rita_common::peer_listener::PeerListener;\n+use crate::rita_common::traffic_watcher::{TrafficWatcher, Watch};\n+use crate::rita_common::tunnel_manager::PeersToContact;\n+use crate::rita_common::tunnel_manager::{GetNeighbors, TunnelManager};\n+use crate::KI;\n+use crate::SETTING;\n+use actix::{\n+ Actor, ActorContext, Addr, Arbiter, AsyncContext, Context, Handler, Message, Supervised,\n+ System, SystemService,\n+};\n+use failure::Error;\n+use futures::Future;\n+use settings::RitaCommonSettings;\n+use std::time::{Duration, Instant};\n+\n+// the speed in seconds for the common loop\n+pub const FAST_LOOP_SPEED: u64 = 5;\n+pub const FAST_LOOP_TIMEOUT: Duration = Duration::from_secs(4);\n+\n+pub struct RitaFastLoop {\n+ was_gateway: bool,\n+}\n+\n+impl Default for RitaFastLoop {\n+ fn default() -> RitaFastLoop {\n+ RitaFastLoop { was_gateway: false }\n+ }\n+}\n+\n+impl Actor for RitaFastLoop {\n+ type Context = Context<Self>;\n+\n+ fn started(&mut self, ctx: &mut Context<Self>) {\n+ trace!(\"Common rita loop started!\");\n+\n+ ctx.run_interval(Duration::from_secs(FAST_LOOP_SPEED), |_act, ctx| {\n+ let addr: Addr<Self> = ctx.address();\n+ addr.do_send(Tick);\n+ });\n+ }\n+}\n+\n+impl SystemService for RitaFastLoop {}\n+impl Supervised for RitaFastLoop {\n+ fn restarting(&mut self, _ctx: &mut Context<RitaFastLoop>) {\n+ error!(\"Rita Common loop actor died! recovering!\");\n+ }\n+}\n+\n+/// Used to test actor respawning\n+pub struct Crash;\n+\n+impl Message for Crash {\n+ type Result = Result<(), Error>;\n+}\n+\n+impl Handler<Crash> for RitaFastLoop {\n+ type Result = Result<(), Error>;\n+ fn handle(&mut self, _: Crash, ctx: &mut Context<Self>) -> Self::Result {\n+ ctx.stop();\n+ Ok(())\n+ }\n+}\n+\n+pub struct Tick;\n+\n+impl Message for Tick {\n+ type Result = Result<(), Error>;\n+}\n+\n+impl Handler<Tick> for RitaFastLoop {\n+ type Result = Result<(), Error>;\n+ fn handle(&mut self, _: Tick, _ctx: &mut Context<Self>) -> Self::Result {\n+ trace!(\"Common tick!\");\n+\n+ self.was_gateway = manage_gateway(self.was_gateway);\n+\n+ let start = Instant::now();\n+\n+ // watch neighbors for billing\n+ Arbiter::spawn(\n+ TunnelManager::from_registry()\n+ .send(GetNeighbors)\n+ .timeout(FAST_LOOP_TIMEOUT)\n+ .then(move |res| {\n+ let res = res.unwrap().unwrap();\n+\n+ trace!(\"Currently open tunnels: {:?}\", res);\n+\n+ let neigh = Instant::now();\n+ info!(\n+ \"GetNeighbors completed in {}s {}ms\",\n+ start.elapsed().as_secs(),\n+ start.elapsed().subsec_millis()\n+ );\n+\n+ TrafficWatcher::from_registry()\n+ .send(Watch::new(res))\n+ .timeout(FAST_LOOP_TIMEOUT)\n+ .then(move |_res| {\n+ info!(\n+ \"TrafficWatcher completed in {}s {}ms\",\n+ neigh.elapsed().as_secs(),\n+ neigh.elapsed().subsec_millis()\n+ );\n+ Ok(())\n+ })\n+ }),\n+ );\n+\n+ // Update debts\n+ DebtKeeper::from_registry().do_send(SendUpdate {});\n+\n+ let start = Instant::now();\n+ trace!(\"Starting PeerListener tick\");\n+ Arbiter::spawn(\n+ PeerListener::from_registry()\n+ .send(Tick {})\n+ .timeout(FAST_LOOP_TIMEOUT)\n+ .then(move |res| {\n+ info!(\n+ \"PeerListener tick completed in {}s {}ms, with result {:?}\",\n+ start.elapsed().as_secs(),\n+ start.elapsed().subsec_millis(),\n+ res\n+ );\n+ res\n+ })\n+ .then(|_| Ok(())),\n+ );\n+\n+ let start = Instant::now();\n+ trace!(\"Getting Peers from PeerListener to pass to TunnelManager\");\n+ Arbiter::spawn(\n+ PeerListener::from_registry()\n+ .send(GetPeers {})\n+ .timeout(FAST_LOOP_TIMEOUT)\n+ .and_then(move |peers| {\n+ // GetPeers never fails so unwrap is safe\n+ let peers = peers.unwrap();\n+ info!(\n+ \"PeerListener get {} peers completed in {}s {}ms\",\n+ peers.len(),\n+ start.elapsed().as_secs(),\n+ start.elapsed().subsec_millis(),\n+ );\n+ TunnelManager::from_registry()\n+ .send(PeersToContact::new(peers))\n+ .timeout(FAST_LOOP_TIMEOUT)\n+ })\n+ .then(|_| Ok(())),\n+ );\n+\n+ Ok(())\n+ }\n+}\n+\n+/// Manages gateway functionaltiy and maintains the was_gateway parameter\n+fn manage_gateway(mut was_gateway: bool) -> bool {\n+ // Resolves the gateway client corner case\n+ // Background info here https://forum.altheamesh.com/t/the-gateway-client-corner-case/35\n+ let gateway = match SETTING.get_network().external_nic {\n+ Some(ref external_nic) => match KI.is_iface_up(external_nic) {\n+ Some(val) => val,\n+ None => false,\n+ },\n+ None => false,\n+ };\n+\n+ info!(\"We are a Gateway: {}\", gateway);\n+ SETTING.get_network_mut().is_gateway = gateway;\n+\n+ if SETTING.get_network().is_gateway {\n+ if was_gateway {\n+ // TODO I don't think this has been running for months\n+ info!(\"Killed trust dns actor!\");\n+ // trust_dns will fail to resolve if you plugin the wan port after Rita has started\n+ // this may be fixed in a future update of Trustdns\n+ let resolver_addr: Addr<ResolverWrapper> = System::current().registry().get();\n+ resolver_addr.do_send(KillActor);\n+ was_gateway = false;\n+ }\n+\n+ match KI.get_resolv_servers() {\n+ Ok(s) => {\n+ for ip in s.iter() {\n+ trace!(\"Resolv route {:?}\", ip);\n+ KI.manual_peers_route(&ip, &mut SETTING.get_network_mut().default_route)\n+ .unwrap();\n+ }\n+ }\n+ Err(e) => warn!(\"Failed to add DNS routes with {:?}\", e),\n+ }\n+ } else {\n+ was_gateway = false\n+ }\n+ was_gateway\n+}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/mod.rs", "new_path": "rita/src/rita_common/rita_loop/mod.rs", "diff": "//! all system functions. Anything that blocks will eventually filter up to block this loop and\n//! halt essential functions like opening tunnels and managing peers\n-use std::time::{Duration, Instant};\n-\n+use crate::SETTING;\nuse rand::thread_rng;\nuse rand::Rng;\n-\n-use crate::actix_utils::KillActor;\n-use actix::{\n- Actor, ActorContext, Addr, Arbiter, AsyncContext, Context, Handler, Message, Supervised,\n- System, SystemService,\n-};\n-\n-use crate::actix_utils::ResolverWrapper;\n-\n-use crate::KI;\n-\n-use crate::rita_common::tunnel_manager::{GetNeighbors, TriggerGC, TunnelManager};\n-\n-use crate::rita_common::traffic_watcher::{TrafficWatcher, Watch};\n-\n-use crate::rita_common::peer_listener::PeerListener;\n-\n-use crate::rita_common::debt_keeper::{DebtKeeper, SendUpdate};\n-\n-use crate::rita_common::peer_listener::GetPeers;\n-\n-use crate::rita_common::dao_manager::DAOManager;\n-use crate::rita_common::dao_manager::Tick as DAOTick;\n-\n-use crate::rita_common::tunnel_manager::PeersToContact;\n-\n-use crate::rita_common::payment_validator::{PaymentValidator, Validate};\n-\n-use crate::rita_common::oracle::{Oracle, Update};\n-\n-use failure::Error;\n-\n-use futures::Future;\n-\n-use crate::SETTING;\nuse settings::RitaCommonSettings;\n-// the speed in seconds for the common loop\n-pub const COMMON_LOOP_SPEED: u64 = 5;\n-pub const COMMON_LOOP_TIMEOUT: Duration = Duration::from_secs(4);\n-\n-pub struct RitaLoop {\n- was_gateway: bool,\n-}\n-\n-impl Default for RitaLoop {\n- fn default() -> RitaLoop {\n- RitaLoop { was_gateway: false }\n- }\n-}\n-\n-impl Actor for RitaLoop {\n- type Context = Context<Self>;\n-\n- fn started(&mut self, ctx: &mut Context<Self>) {\n- trace!(\"Common rita loop started!\");\n-\n- ctx.run_interval(Duration::from_secs(COMMON_LOOP_SPEED), |_act, ctx| {\n- let addr: Addr<Self> = ctx.address();\n- addr.do_send(Tick);\n- });\n- }\n-}\n-\n-impl SystemService for RitaLoop {}\n-impl Supervised for RitaLoop {\n- fn restarting(&mut self, _ctx: &mut Context<RitaLoop>) {\n- error!(\"Rita Common loop actor died! recovering!\");\n- }\n-}\n-\n-/// Used to test actor respawning\n-pub struct Crash;\n-\n-impl Message for Crash {\n- type Result = Result<(), Error>;\n-}\n-\n-impl Handler<Crash> for RitaLoop {\n- type Result = Result<(), Error>;\n- fn handle(&mut self, _: Crash, ctx: &mut Context<Self>) -> Self::Result {\n- ctx.stop();\n- Ok(())\n- }\n-}\n-\n-pub struct Tick;\n-\n-impl Message for Tick {\n- type Result = Result<(), Error>;\n-}\n-\n-impl Handler<Tick> for RitaLoop {\n- type Result = Result<(), Error>;\n- fn handle(&mut self, _: Tick, _ctx: &mut Context<Self>) -> Self::Result {\n- trace!(\"Common tick!\");\n-\n- self.was_gateway = manage_gateway(self.was_gateway);\n-\n- let start = Instant::now();\n-\n- // watch neighbors for billing\n- Arbiter::spawn(\n- TunnelManager::from_registry()\n- .send(GetNeighbors)\n- .timeout(COMMON_LOOP_TIMEOUT)\n- .then(move |res| {\n- let res = res.unwrap().unwrap();\n-\n- trace!(\"Currently open tunnels: {:?}\", res);\n-\n- let neigh = Instant::now();\n- info!(\n- \"GetNeighbors completed in {}s {}ms\",\n- start.elapsed().as_secs(),\n- start.elapsed().subsec_millis()\n- );\n-\n- TrafficWatcher::from_registry()\n- .send(Watch::new(res))\n- .timeout(COMMON_LOOP_TIMEOUT)\n- .then(move |_res| {\n- info!(\n- \"TrafficWatcher completed in {}s {}ms\",\n- neigh.elapsed().as_secs(),\n- neigh.elapsed().subsec_millis()\n- );\n- Ok(())\n- })\n- }),\n- );\n-\n- // Update debts\n- DebtKeeper::from_registry().do_send(SendUpdate {});\n-\n- // Check DAO payments\n- DAOManager::from_registry().do_send(DAOTick);\n-\n- // Check payments\n- PaymentValidator::from_registry().do_send(Validate());\n- // Update blockchain info\n- Oracle::from_registry().do_send(Update());\n-\n- let start = Instant::now();\n- Arbiter::spawn(\n- TunnelManager::from_registry()\n- .send(TriggerGC(Duration::from_secs(\n- SETTING.get_network().tunnel_timeout_seconds,\n- )))\n- .timeout(COMMON_LOOP_TIMEOUT)\n- .then(move |res| {\n- info!(\n- \"TunnelManager GC pass completed in {}s {}ms, with result {:?}\",\n- start.elapsed().as_secs(),\n- start.elapsed().subsec_millis(),\n- res\n- );\n- res\n- })\n- .then(|_| Ok(())),\n- );\n-\n- let start = Instant::now();\n- trace!(\"Starting PeerListener tick\");\n- Arbiter::spawn(\n- PeerListener::from_registry()\n- .send(Tick {})\n- .timeout(COMMON_LOOP_TIMEOUT)\n- .then(move |res| {\n- info!(\n- \"PeerListener tick completed in {}s {}ms, with result {:?}\",\n- start.elapsed().as_secs(),\n- start.elapsed().subsec_millis(),\n- res\n- );\n- res\n- })\n- .then(|_| Ok(())),\n- );\n-\n- let start = Instant::now();\n- trace!(\"Getting Peers from PeerListener to pass to TunnelManager\");\n- Arbiter::spawn(\n- PeerListener::from_registry()\n- .send(GetPeers {})\n- .timeout(COMMON_LOOP_TIMEOUT)\n- .and_then(move |peers| {\n- // GetPeers never fails so unwrap is safe\n- let peers = peers.unwrap();\n- info!(\n- \"PeerListener get {} peers completed in {}s {}ms\",\n- peers.len(),\n- start.elapsed().as_secs(),\n- start.elapsed().subsec_millis(),\n- );\n- TunnelManager::from_registry()\n- .send(PeersToContact::new(peers))\n- .timeout(COMMON_LOOP_TIMEOUT)\n- })\n- .then(|_| Ok(())),\n- );\n-\n- Ok(())\n- }\n-}\n-\n-/// Manages gateway functionaltiy and maintains the was_gateway parameter\n-fn manage_gateway(mut was_gateway: bool) -> bool {\n- // Resolves the gateway client corner case\n- // Background info here https://forum.altheamesh.com/t/the-gateway-client-corner-case/35\n- let gateway = match SETTING.get_network().external_nic {\n- Some(ref external_nic) => match KI.is_iface_up(external_nic) {\n- Some(val) => val,\n- None => false,\n- },\n- None => false,\n- };\n-\n- info!(\"We are a Gateway: {}\", gateway);\n- SETTING.get_network_mut().is_gateway = gateway;\n-\n- if SETTING.get_network().is_gateway {\n- if was_gateway {\n- // TODO I don't think this has been running for months\n- info!(\"Killed trust dns actor!\");\n- // trust_dns will fail to resolve if you plugin the wan port after Rita has started\n- // this may be fixed in a future update of Trustdns\n- let resolver_addr: Addr<ResolverWrapper> = System::current().registry().get();\n- resolver_addr.do_send(KillActor);\n- was_gateway = false;\n- }\n-\n- match KI.get_resolv_servers() {\n- Ok(s) => {\n- for ip in s.iter() {\n- trace!(\"Resolv route {:?}\", ip);\n- KI.manual_peers_route(&ip, &mut SETTING.get_network_mut().default_route)\n- .unwrap();\n- }\n- }\n- Err(e) => warn!(\"Failed to add DNS routes with {:?}\", e),\n- }\n- } else {\n- was_gateway = false\n- }\n- was_gateway\n-}\n+pub mod fast_loop;\n+pub mod slow_loop;\n/// Checks the list of full nodes, panics if none exist, if there exist\n/// one or more a random entry from the list is returned in an attempt\n" }, { "change_type": "ADD", "old_path": null, "new_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "diff": "+use crate::rita_common::dao_manager::DAOManager;\n+use crate::rita_common::dao_manager::Tick as DAOTick;\n+use crate::rita_common::oracle::{Oracle, Update};\n+use crate::rita_common::payment_validator::{PaymentValidator, Validate};\n+use crate::rita_common::tunnel_manager::{TriggerGC, TunnelManager};\n+use crate::SETTING;\n+use actix::{\n+ Actor, ActorContext, Addr, AsyncContext, Context, Handler, Message, Supervised, SystemService,\n+};\n+use failure::Error;\n+use settings::RitaCommonSettings;\n+use std::time::Duration;\n+\n+// the speed in seconds for the common loop\n+pub const SLOW_LOOP_SPEED: u64 = 60;\n+\n+pub struct RitaSlowLoop;\n+\n+impl Default for RitaSlowLoop {\n+ fn default() -> RitaSlowLoop {\n+ RitaSlowLoop {}\n+ }\n+}\n+\n+impl Actor for RitaSlowLoop {\n+ type Context = Context<Self>;\n+\n+ fn started(&mut self, ctx: &mut Context<Self>) {\n+ trace!(\"Common rita loop started!\");\n+\n+ ctx.run_interval(Duration::from_secs(SLOW_LOOP_SPEED), |_act, ctx| {\n+ let addr: Addr<Self> = ctx.address();\n+ addr.do_send(Tick);\n+ });\n+ }\n+}\n+\n+impl SystemService for RitaSlowLoop {}\n+impl Supervised for RitaSlowLoop {\n+ fn restarting(&mut self, _ctx: &mut Context<RitaSlowLoop>) {\n+ error!(\"Rita Common loop actor died! recovering!\");\n+ }\n+}\n+\n+/// Used to test actor respawning\n+pub struct Crash;\n+\n+impl Message for Crash {\n+ type Result = Result<(), Error>;\n+}\n+\n+impl Handler<Crash> for RitaSlowLoop {\n+ type Result = Result<(), Error>;\n+ fn handle(&mut self, _: Crash, ctx: &mut Context<Self>) -> Self::Result {\n+ ctx.stop();\n+ Ok(())\n+ }\n+}\n+\n+pub struct Tick;\n+\n+impl Message for Tick {\n+ type Result = Result<(), Error>;\n+}\n+\n+impl Handler<Tick> for RitaSlowLoop {\n+ type Result = Result<(), Error>;\n+ fn handle(&mut self, _: Tick, _ctx: &mut Context<Self>) -> Self::Result {\n+ trace!(\"Common Slow tick!\");\n+\n+ // Check DAO payments\n+ DAOManager::from_registry().do_send(DAOTick);\n+\n+ // Check payments\n+ PaymentValidator::from_registry().do_send(Validate());\n+ // Update blockchain info\n+ Oracle::from_registry().do_send(Update());\n+\n+ TunnelManager::from_registry().do_send(TriggerGC(Duration::from_secs(\n+ SETTING.get_network().tunnel_timeout_seconds,\n+ )));\n+\n+ Ok(())\n+ }\n+}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Split rita common loop into fast and slow
20,244
22.05.2019 09:43:43
14,400
310631e177e390e42dcce7cd112d49a3ea7e2ecb
Update timeouts to reflect slow loop Many of these timeouts can now be safely increased without any risk of a 'event leak' where we spawn events faster than they can timeout
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/oracle/mod.rs", "new_path": "rita/src/rita_common/oracle/mod.rs", "diff": "@@ -61,7 +61,8 @@ impl Default for Oracle {\n}\n}\n-pub const ORACLE_TIMEOUT: Duration = Duration::from_secs(1);\n+/// How long we wait for a response from the full node\n+pub const ORACLE_TIMEOUT: Duration = Duration::from_secs(5);\n#[derive(Message)]\npub struct Update();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_controller/mod.rs", "new_path": "rita/src/rita_common/payment_controller/mod.rs", "diff": "@@ -24,7 +24,7 @@ use std::time::Instant;\nuse tokio::net::TcpStream as TokioTcpStream;\nuse web30::client::Web3;\n-pub const TRANSACTION_SUBMISSON_TIMEOUT: Duration = Duration::from_secs(10);\n+pub const TRANSACTION_SUBMISSON_TIMEOUT: Duration = Duration::from_secs(15);\npub struct PaymentController();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/payment_validator/mod.rs", "new_path": "rita/src/rita_common/payment_validator/mod.rs", "diff": "@@ -26,7 +26,8 @@ use std::time::{Duration, Instant};\nuse web30::client::Web3;\nuse web30::types::TransactionResponse;\n-const TRANSACTION_VERIFICATION_TIMEOUT: Duration = Duration::from_secs(4);\n+// How long we will wait for full node responses\n+const TRANSACTION_VERIFICATION_TIMEOUT: Duration = Duration::from_secs(10);\n// Discard payments after 1 hour of failing to find txid\npub const PAYMENT_TIMEOUT: Duration = Duration::from_secs(3600u64);\n// How many blocks before we assume finality\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "new_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "diff": "@@ -73,6 +73,7 @@ impl Handler<Tick> for RitaSlowLoop {\n// Check payments\nPaymentValidator::from_registry().do_send(Validate());\n+\n// Update blockchain info\nOracle::from_registry().do_send(Update());\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Update timeouts to reflect slow loop Many of these timeouts can now be safely increased without any risk of a 'event leak' where we spawn events faster than they can timeout
20,244
22.05.2019 10:33:10
14,400
db91e8b0557ffb376c4d144ef62cb5e570579120
Fix obvious port leak in TunnelManager In retrospect adding the timeout here coresponds quite well to when we started to see more crashes due to port allocation errors. It's a testiment to the speed and reliability of DNS that we ran out of ports infreqently enough that I didn't notice this right away.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -622,12 +622,13 @@ impl TunnelManager {\n}\nErr(e) => {\nwarn!(\"Actor mailbox failure from DNS resolver! {:?}\", e);\n- // We might need a port callback here\n+ TunnelManager::from_registry().do_send(PortCallback(our_port));\nOk(())\n}\nOk(Err(e)) => {\nwarn!(\"DNS resolution failed with {:?}\", e);\n+ TunnelManager::from_registry().do_send(PortCallback(our_port));\nOk(())\n}\n});\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Fix obvious port leak in TunnelManager In retrospect adding the timeout here coresponds quite well to when we started to see more crashes due to port allocation errors. It's a testiment to the speed and reliability of DNS that we ran out of ports infreqently enough that I didn't notice this right away.
20,244
22.05.2019 12:29:14
14,400
d01a6b7f6cf6a2c48e09279cf1492a13584c283e
Bump for Beta 5 rc3
[ { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "[package]\nname = \"rita\"\n-version = \"0.4.4\"\n+version = \"0.4.5\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/own_info.rs", "new_path": "rita/src/rita_common/dashboard/own_info.rs", "diff": "@@ -6,7 +6,7 @@ use clarity::Address;\nuse failure::Error;\nuse num256::{Int256, Uint256};\n-pub static READABLE_VERSION: &str = \"Beta 5 RC2\";\n+pub static READABLE_VERSION: &str = \"Beta 5 RC3\";\n#[derive(Serialize)]\npub struct OwnInfo {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Bump for Beta 5 rc3
20,244
23.05.2019 15:40:12
14,400
8f204894679e8d4a6a5c0b4d1abfc3d364ca28be
Update web30 to prevent crashes
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -1969,7 +1969,7 @@ dependencies = [\n\"tokio-codec 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"trust-dns-resolver 0.10.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"web30 0.4.3 (git+https://github.com/althea-mesh/web30)\",\n+ \"web30 0.4.3 (git+https://github.com/althea-mesh/web30?rev=56b0068aa43eb563db996418eb96f3ade85ef73b)\",\n]\n[[package]]\n@@ -2776,7 +2776,7 @@ dependencies = [\n[[package]]\nname = \"web30\"\nversion = \"0.4.3\"\n-source = \"git+https://github.com/althea-mesh/web30#272e5b8ba5e61a15ee0d7bf49a3577a37b6a5493\"\n+source = \"git+https://github.com/althea-mesh/web30?rev=56b0068aa43eb563db996418eb96f3ade85ef73b#56b0068aa43eb563db996418eb96f3ade85ef73b\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -3159,7 +3159,7 @@ dependencies = [\n\"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd\"\n\"checksum walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)\" = \"9d9d7ed3431229a144296213105a390676cc49c9b6a72bd19f3176c98e129fa1\"\n\"checksum want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"797464475f30ddb8830cc529aaaae648d581f99e2036a928877dfde027ddf6b3\"\n-\"checksum web30 0.4.3 (git+https://github.com/althea-mesh/web30)\" = \"<none>\"\n+\"checksum web30 0.4.3 (git+https://github.com/althea-mesh/web30?rev=56b0068aa43eb563db996418eb96f3ade85ef73b)\" = \"<none>\"\n\"checksum widestring 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7157704c2e12e3d2189c507b7482c52820a16dfa4465ba91add92f266667cadb\"\n\"checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)\" = \"167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a\"\n\"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0\"\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "@@ -22,7 +22,7 @@ exit_db = { path = \"../exit_db\" }\nnum256 = \"0.2\"\nsettings = { path = \"../settings\" }\n-web30 = {git = \"https://github.com/althea-mesh/web30\"}\n+web30 = {git = \"https://github.com/althea-mesh/web30\", rev=\"56b0068aa43eb563db996418eb96f3ade85ef73b\"}\nsyslog = \"4\"\nactix = \"0.7\"\nactix-web = { version = \"0.7\", default_features = false, features= [\"ssl\"] }\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Update web30 to prevent crashes
20,244
24.05.2019 08:33:23
14,400
78bbd51916697a82f0b69bc6dc921bb80ea85645
Log statements looking for exit client leaks We're continuing to see steady time growth in the fully sync exit setup loop, despite no single command taking more than one second. So let start looking for client number growth
[ { "change_type": "MODIFY", "old_path": "althea_kernel_interface/src/exit_server_tunnel.rs", "new_path": "althea_kernel_interface/src/exit_server_tunnel.rs", "diff": "@@ -8,7 +8,7 @@ use failure::Error;\nuse std::net::IpAddr;\n-#[derive(Debug)]\n+#[derive(Debug, Clone, Copy)]\npub struct ExitClient {\npub internal_ip: IpAddr,\npub public_key: WgKey,\n@@ -52,7 +52,9 @@ impl dyn KernelInterface {\nself.run_command(&command, &arg_str[..])?;\n- for i in self.get_peers(\"wg_exit\")? {\n+ let wg_peers = self.get_peers(\"wg_exit\")?;\n+ info!(\"wg_exit has {} peers\", wg_peers.len());\n+ for i in wg_peers {\nif !client_pubkeys.contains(&i) {\nself.run_command(\n\"wg\",\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -446,7 +446,7 @@ pub fn setup_clients(clients_list: &[exit_db::models::Client]) -> Result<(), Err\n// setup all the tunnels\nlet exit_status = KI.set_exit_wg_config(\n- wg_clients,\n+ wg_clients.clone(),\nSETTING.get_exit_network().wg_tunnel_port,\n&SETTING.get_exit_network().wg_private_key_path,\n);\n@@ -461,9 +461,11 @@ pub fn setup_clients(clients_list: &[exit_db::models::Client]) -> Result<(), Err\n),\n}\ninfo!(\n- \"exit setup loop completed in {}s {}ms\",\n+ \"exit setup loop completed in {}s {}ms with {} clients and {} wg_clients\",\nstart.elapsed().as_secs(),\n- start.elapsed().subsec_millis()\n+ start.elapsed().subsec_millis(),\n+ clients_list.len(),\n+ wg_clients.len(),\n);\nOk(())\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Log statements looking for exit client leaks We're continuing to see steady time growth in the fully sync exit setup loop, despite no single command taking more than one second. So let start looking for client number growth
20,244
24.05.2019 10:03:10
14,400
b4880e6567e9daa7e7dc813ef7ff5b8ae48d97f6
Use git lettre Lettre has yet to update the crate for breaking changes making their way into Beta right now. So we'll have to use git
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -1099,12 +1099,10 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\n[[package]]\nname = \"lettre\"\nversion = \"0.9.1\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+source = \"git+https://github.com/lettre/lettre/#0ead3cde09a02918e3976aa442329fe247f05c55\"\ndependencies = [\n\"base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"bufstream 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"fast_chemail 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"hostname 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -1118,13 +1116,11 @@ dependencies = [\n[[package]]\nname = \"lettre_email\"\nversion = \"0.9.1\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+source = \"git+https://github.com/lettre/lettre/#0ead3cde09a02918e3976aa442329fe247f05c55\"\ndependencies = [\n\"base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"email 0.0.20 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"lettre 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"lettre 0.9.1 (git+https://github.com/lettre/lettre/)\",\n\"mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"uuid 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -1946,8 +1942,8 @@ dependencies = [\n\"handlebars 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"ipnetwork 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"lettre 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"lettre_email 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"lettre 0.9.1 (git+https://github.com/lettre/lettre/)\",\n+ \"lettre_email 0.9.1 (git+https://github.com/lettre/lettre/)\",\n\"libsqlite3-sys 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"minihttpse 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -2988,8 +2984,8 @@ dependencies = [\n\"checksum lazy_static 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)\" = \"76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73\"\n\"checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14\"\n\"checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f\"\n-\"checksum lettre 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"646aee0a55545eaffdf0df1ac19b500b51adb3095ec4dfdc704134e56ea23531\"\n-\"checksum lettre_email 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"ae1b3d43e4bb7beb9974a359cbb3ea4f93dfba6c1c0c6e9c9f82e538e0f9ab9f\"\n+\"checksum lettre 0.9.1 (git+https://github.com/lettre/lettre/)\" = \"<none>\"\n+\"checksum lettre_email 0.9.1 (git+https://github.com/lettre/lettre/)\" = \"<none>\"\n\"checksum libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)\" = \"aab692d7759f5cd8c859e169db98ae5b52c924add2af5fbbca11d12fefb567c1\"\n\"checksum libflate 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)\" = \"54d1ddf9c52870243c5689d7638d888331c1116aa5b398f3ba1acfa7d8758ca1\"\n\"checksum libsqlite3-sys 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"d3711dfd91a1081d2458ad2d06ea30a8755256e74038be2ad927d94e1c955ca8\"\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "@@ -59,8 +59,8 @@ num-traits=\"0.2\"\nclarity = \"0.1\"\neui48 = \"0.4\"\narrayvec = {version= \"0.4\", features = [\"serde-1\"]}\n-lettre = \"0.9\"\n-lettre_email = \"0.9\"\n+lettre = {git = \"https://github.com/lettre/lettre/\"}\n+lettre_email = {git = \"https://github.com/lettre/lettre/\"}\nphonenumber = \"0.2\"\n[features]\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "@@ -162,7 +162,8 @@ fn setup_exit_wg_tunnel() {\nKI.one_time_exit_setup(\n&SETTING.get_exit_network().own_internal_ip.into(),\nSETTING.get_exit_network().netmask,\n- ).expect(\"Failed to setup wg_exit!\");\n+ )\n+ .expect(\"Failed to setup wg_exit!\");\nKI.setup_nat(&SETTING.get_network().external_nic.clone().unwrap())\n.unwrap();\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Use git lettre Lettre has yet to update the crate for breaking changes making their way into Beta right now. So we'll have to use git
20,244
24.05.2019 23:37:55
14,400
e19e2dc2e18bf0f1e215bcd0dd7162d4563b88dd
Time has told, update the nonce in oracle This turned out to not be a great idea after some other change caused full nodes to lie to us about our transactions nonces
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/oracle/mod.rs", "new_path": "rita/src/rita_common/oracle/mod.rs", "diff": "@@ -80,9 +80,7 @@ impl Handler<Update> for Oracle {\ninfo!(\"About to make web3 requests to {}\", full_node);\nupdate_balance(our_address, &web3, full_node.clone());\n- // removed and placed into error handling in payment controller\n- // time will tell if that was a good idea\n- //update_nonce(our_address, &web3);\n+ update_nonce(our_address, &web3, full_node.clone());\nupdate_gas_price(&web3, full_node.clone());\nget_net_version(&web3, full_node);\nif oracle_enabled {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Time has told, update the nonce in oracle This turned out to not be a great idea after some other change caused full nodes to lie to us about our transactions nonces
20,244
27.05.2019 18:48:03
14,400
1b91a771cba5a47e720f6093665ab7bc56adb795
More efficient flow existance checking Results in about a 15x performance improvement in this section of code
[ { "change_type": "MODIFY", "old_path": "althea_kernel_interface/src/exit_server_tunnel.rs", "new_path": "althea_kernel_interface/src/exit_server_tunnel.rs", "diff": "@@ -56,6 +56,7 @@ impl dyn KernelInterface {\ninfo!(\"wg_exit has {} peers\", wg_peers.len());\nfor i in wg_peers {\nif !client_pubkeys.contains(&i) {\n+ warn!(\"Removing no longer authorized peer {}\", i);\nself.run_command(\n\"wg\",\n&[\"set\", \"wg_exit\", \"peer\", &format!(\"{}\", i), \"remove\"],\n@@ -64,10 +65,12 @@ impl dyn KernelInterface {\n}\n// setup traffic classes for enforcement with flow id's derived from the ip\n+ // only get the flows list once\n+ let flows = self.get_flows(\"wg_exit\")?;\nfor c in clients.iter() {\nmatch c.internal_ip {\nIpAddr::V4(addr) => {\n- if !self.has_flow(&addr, \"wg_exit\")? {\n+ if !self.has_flow_bulk(&addr, &flows) {\nself.create_flow_by_ip(\"wg_exit\", &addr)?\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "althea_kernel_interface/src/traffic_control.rs", "new_path": "althea_kernel_interface/src/traffic_control.rs", "diff": "@@ -38,6 +38,24 @@ impl KernelInterface {\nOk(stdout.contains(&format!(\"1:{}\", class_id)))\n}\n+ /// Gets the full flows list to pass to bulk functions\n+ pub fn get_flows(&self, iface_name: &str) -> Result<String, Error> {\n+ let result = self.run_command(\"tc\", &[\"filter\", \"show\", \"dev\", iface_name])?;\n+\n+ if !result.status.success() {\n+ let res = String::from_utf8(result.stderr)?;\n+ bail!(\"Failed to get flows {:?}\", res);\n+ }\n+ Ok(String::from_utf8(result.stdout)?)\n+ }\n+\n+ /// A version of the flows check designed to be run from the raw input, more efficient\n+ /// in the exit setup loop than running the same command several hundred times\n+ pub fn has_flow_bulk(&self, ip: &Ipv4Addr, tc_out: &str) -> bool {\n+ let class_id = self.get_class_id(&ip);\n+ tc_out.contains(&format!(\"1:{}\", class_id))\n+ }\n+\n/// Determines if the provided flow is assigned\npub fn has_class(&self, ip: &Ipv4Addr, iface_name: &str) -> Result<bool, Error> {\nlet class_id = self.get_class_id(ip);\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
More efficient flow existance checking Results in about a 15x performance improvement in this section of code
20,244
27.05.2019 19:57:55
14,400
961b9435a8140fb91d33c8e789c1fed8d6e3c277
Check for client uniqueness during setup
[ { "change_type": "MODIFY", "old_path": "althea_kernel_interface/src/exit_server_tunnel.rs", "new_path": "althea_kernel_interface/src/exit_server_tunnel.rs", "diff": "use super::{KernelInterface, KernelInterfaceError};\n-\nuse althea_types::WgKey;\n-\n-use std::collections::HashSet;\n-\n-use failure::Error;\n-\nuse std::net::IpAddr;\n+use failure::Error;\n+use std::collections::HashSet;\n-#[derive(Debug, Clone, Copy)]\n+#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]\npub struct ExitClient {\npub internal_ip: IpAddr,\npub public_key: WgKey,\n@@ -19,7 +15,7 @@ pub struct ExitClient {\nimpl dyn KernelInterface {\npub fn set_exit_wg_config(\n&self,\n- clients: Vec<ExitClient>,\n+ clients: &HashSet<ExitClient>,\nlisten_port: u16,\nprivate_key_path: &str,\n) -> Result<(), Error> {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -45,6 +45,7 @@ use std::collections::HashMap;\nuse std::net::IpAddr;\nuse std::time::Instant;\nuse std::time::{Duration, SystemTime, UNIX_EPOCH};\n+use std::collections::HashSet;\nmod database_tools;\npub mod db_client;\n@@ -430,13 +431,16 @@ pub fn setup_clients(clients_list: &[exit_db::models::Client]) -> Result<(), Err\nlet start = Instant::now();\n- let mut wg_clients = Vec::new();\n+ // use hashset to ensure uniqueness and check for duplicate db entries\n+ let mut wg_clients = HashSet::new();\ntrace!(\"got clients from db {:?}\", clients);\nfor c in clients_list.iter() {\nmatch (c.verified, to_exit_client(c.clone())) {\n- (true, Ok(exit_client_c)) => wg_clients.push(exit_client_c),\n+ (true, Ok(exit_client_c)) => if !wg_clients.insert(exit_client_c) {\n+ error!(\"Duplicate database entry! {}\", c.wg_pubkey);\n+ },\n(true, Err(e)) => warn!(\"Error converting {:?} to exit client {:?}\", c, e),\n(false, _) => trace!(\"{:?} is not verified, not adding to wg_exit\", c),\n}\n@@ -446,7 +450,7 @@ pub fn setup_clients(clients_list: &[exit_db::models::Client]) -> Result<(), Err\n// setup all the tunnels\nlet exit_status = KI.set_exit_wg_config(\n- wg_clients.clone(),\n+ &wg_clients,\nSETTING.get_exit_network().wg_tunnel_port,\n&SETTING.get_exit_network().wg_private_key_path,\n);\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Check for client uniqueness during setup
20,244
27.05.2019 20:22:43
14,400
d46c427e5557ce3dce6357fc9efac19d0f91f518
Only run exit setup when the clients list changes
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -46,6 +46,7 @@ use std::net::IpAddr;\nuse std::time::Instant;\nuse std::time::{Duration, SystemTime, UNIX_EPOCH};\nuse std::collections::HashSet;\n+use althea_kernel_interface::ExitClient;\nmod database_tools;\npub mod db_client;\n@@ -426,7 +427,7 @@ pub fn cleanup_exit_clients(\n/// into a single very long wg tunnel setup command which is then applied to the\n/// wg_exit tunnel (or created if it's the first run). This is the offically supported\n/// way to update live WireGuard tunnels and should not disrupt traffic\n-pub fn setup_clients(clients_list: &[exit_db::models::Client]) -> Result<(), Error> {\n+pub fn setup_clients(clients_list: &[exit_db::models::Client], old_clients: &HashSet<ExitClient>) -> Result<HashSet<ExitClient>, Error> {\nuse self::schema::clients::dsl::clients;\nlet start = Instant::now();\n@@ -447,6 +448,13 @@ pub fn setup_clients(clients_list: &[exit_db::models::Client]) -> Result<(), Err\n}\ntrace!(\"converted clients {:?}\", wg_clients);\n+ // symetric difference is an iterator of all items in A but not in B\n+ // or in B but not in A, in short if there's any difference between the two\n+ // it must be nonzero, since all entires must be unique there can not be duplicates\n+ if wg_clients.symmetric_difference(old_clients).count() == 0 {\n+ info!(\"No change in wg_exit, skipping setup for this round\");\n+ return Ok(wg_clients);\n+ }\n// setup all the tunnels\nlet exit_status = KI.set_exit_wg_config(\n@@ -471,7 +479,7 @@ pub fn setup_clients(clients_list: &[exit_db::models::Client]) -> Result<(), Err\nclients_list.len(),\nwg_clients.len(),\n);\n- Ok(())\n+ Ok(wg_clients)\n}\n/// Performs enforcement actions on clients by requesting a list of clients from debt keeper\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "@@ -39,6 +39,8 @@ use settings::RitaCommonSettings;\nuse std::collections::HashMap;\nuse std::net::IpAddr;\nuse std::time::Duration;\n+use althea_kernel_interface::ExitClient;\n+use std::collections::HashSet;\n#[derive(Default)]\npub struct RitaLoop {}\n@@ -47,6 +49,8 @@ pub struct RitaLoop {}\npub struct RitaSyncLoop {\n/// a simple cache to prevent regularly asking Maxmind for the same geoip data\npub geoip_cache: HashMap<IpAddr, String>,\n+ /// a cache of what tunnels we had setup last round, used to prevent extra setup ops\n+ pub wg_clients: HashSet<ExitClient>,\n}\n// the speed in seconds for the exit loop\n@@ -60,6 +64,7 @@ impl Actor for RitaLoop {\nsetup_exit_wg_tunnel();\nlet addr = SyncArbiter::start(1, || RitaSyncLoop {\ngeoip_cache: HashMap::new(),\n+ wg_clients: HashSet::new(),\n});\nctx.run_interval(Duration::from_secs(EXIT_LOOP_SPEED), move |_act, _ctx| {\naddr.do_send(Tick)\n@@ -127,9 +132,9 @@ impl Handler<Tick> for RitaSyncLoop {\nTrafficWatcher::from_registry().do_send(Watch(ids));\n// Create and update client tunnels\n- let res = setup_clients(&clients_list);\n- if res.is_err() {\n- error!(\"Setup clients failed with {:?}\", res);\n+ match setup_clients(&clients_list, &self.wg_clients) {\n+ Ok(wg_clients) => self.wg_clients = wg_clients,\n+ Err(e) => error!(\"Setup clients failed with {:?}\", e)\n}\n// find users that have not been active within the configured time period\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Only run exit setup when the clients list changes
20,244
28.05.2019 07:29:26
14,400
71b3cfdcab9e52c9eb3f31ef9ca86af29042839e
Add debts reset endpoint
[ { "change_type": "MODIFY", "old_path": "docs/api/router-dashboard.md", "new_path": "docs/api/router-dashboard.md", "diff": "@@ -702,6 +702,31 @@ Format:\n---\n+## /debts/reset\n+\n+Posting a JSON identity object to this endpoint will reset the debt of the provided identity to\n+zero. Use the /debts/ endpoint to get the id.\n+\n+- URL: `<rita ip>:<rita_dashboard_port>/debts/reset`\n+- Method: `POST`\n+- URL Params: `None`\n+- Data Params: `Json<Identity>`\n+- Success Response:\n+ - Code: 200 OK\n+ - Contents: `None`.\n+- Error Response: `500 Server Error`\n+- Sample Call\n+\n+`curl 127.0..1:<rita_dashboard_port>/debts/reset -H 'Content-Type: application/json' -i -d '{ \"mesh_ip\": \"a:b:c:d:e:f:g:h\", \"eth_address\": \"0x0101010101010101010101010101010101010101\", \"wg_public_key\": \"pubkey\"}'`\n+\n+Format:\n+\n+```json\n+[]\n+```\n+\n+---\n+\n## /dao_list\nCalling HTTP `GET` request on this endpoint returns a list of EthAddresses for a configured subnet DAO. If no DAO is configured it will return an empty list.\n" }, { "change_type": "MODIFY", "old_path": "rita/src/client.rs", "new_path": "rita/src/client.rs", "diff": "@@ -241,6 +241,7 @@ fn main() {\nremove_from_dao_list,\n)\n.route(\"/debts\", Method::GET, get_debts)\n+ .route(\"/debts/reset\", Method::POST, reset_debt)\n.route(\"/exits/sync\", Method::GET, exits_sync)\n.route(\"/exits\", Method::GET, get_exit_info)\n.route(\"/exits\", Method::POST, add_exits)\n" }, { "change_type": "MODIFY", "old_path": "rita/src/exit.rs", "new_path": "rita/src/exit.rs", "diff": "@@ -250,6 +250,7 @@ fn main() {\n.route(\"/wipe\", Method::POST, wipe)\n.route(\"/database\", Method::DELETE, nuke_db)\n.route(\"/debts\", Method::GET, get_debts)\n+ .route(\"/debts/reset\", Method::POST, reset_debt)\n.route(\"/dao_list\", Method::GET, get_dao_list)\n.route(\"/dao_list/add/{address}\", Method::POST, add_to_dao_list)\n.route(\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/debts.rs", "new_path": "rita/src/rita_common/dashboard/debts.rs", "diff": "+use crate::rita_common::debt_keeper::DebtKeeper;\nuse crate::rita_common::debt_keeper::GetDebtsList;\n-use crate::rita_common::debt_keeper::{DebtKeeper, GetDebtsResult};\n-use ::actix::registry::SystemService;\n-use ::actix_web::{AsyncResponder, HttpRequest, Json};\n+use crate::rita_common::debt_keeper::GetDebtsResult;\n+use crate::rita_common::debt_keeper::Traffic;\n+use crate::rita_common::debt_keeper::TrafficReplace;\n+use ::actix::SystemService;\n+use ::actix_web::{AsyncResponder, HttpRequest, HttpResponse, Json};\n+use althea_types::Identity;\nuse failure::Error;\nuse futures::Future;\nuse std::boxed::Box;\n@@ -16,3 +20,14 @@ pub fn get_debts(\n.and_then(move |reply| Ok(Json(reply?)))\n.responder()\n}\n+\n+pub fn reset_debt(user_to_forgive: Json<Identity>) -> HttpResponse {\n+ let forgiven_traffic = TrafficReplace {\n+ traffic: Traffic {\n+ from: user_to_forgive.into_inner(),\n+ amount: 0.into(),\n+ },\n+ };\n+ DebtKeeper::from_registry().do_send(forgiven_traffic);\n+ HttpResponse::Ok().json(())\n+}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add debts reset endpoint
20,244
28.05.2019 14:34:47
14,400
34a6ab7ed1f87e2e1cd9d6657ca967c8ea0455f2
Bump for Beta 5 RC5
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -173,7 +173,7 @@ dependencies = [\nname = \"althea_rs\"\nversion = \"0.1.10\"\ndependencies = [\n- \"rita 0.4.6\",\n+ \"rita 0.4.7\",\n]\n[[package]]\n@@ -1917,7 +1917,7 @@ dependencies = [\n[[package]]\nname = \"rita\"\n-version = \"0.4.6\"\n+version = \"0.4.7\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "[package]\nname = \"rita\"\n-version = \"0.4.6\"\n+version = \"0.4.7\"\nauthors = [\"Jehan <jehan.tremback@gmail.com>\", \"Ben <wangben3@gmail.com>\"]\nbuild = \"build.rs\"\nedition = \"2018\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/dashboard/own_info.rs", "new_path": "rita/src/rita_common/dashboard/own_info.rs", "diff": "@@ -6,7 +6,7 @@ use clarity::Address;\nuse failure::Error;\nuse num256::{Int256, Uint256};\n-pub static READABLE_VERSION: &str = \"Beta 5 RC4\";\n+pub static READABLE_VERSION: &str = \"Beta 5 RC5\";\n#[derive(Serialize)]\npub struct OwnInfo {\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Bump for Beta 5 RC5
20,244
29.05.2019 09:07:28
14,400
2e6f3ebef700ac2f2a6946c3e0b71d20068007f4
Cache wg lookups for region validation
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/geoip.rs", "new_path": "rita/src/rita_exit/database/geoip.rs", "diff": "@@ -42,6 +42,7 @@ pub struct IpPair {\n/// gets the gateway ip for a given set of mesh IPs, inactive addresses will simply\n/// not appear in the result vec\npub fn get_gateway_ip_bulk(mesh_ip_list: Vec<IpAddr>) -> Result<Vec<IpPair>, Error> {\n+ let mut remote_ip_cache: HashMap<String, IpAddr> = HashMap::new();\nlet mut babel = Babel::new(make_babel_stream()?);\nbabel.start_connection()?;\nlet routes = babel.parse_routes()?;\n@@ -53,17 +54,29 @@ pub fn get_gateway_ip_bulk(mesh_ip_list: Vec<IpAddr>) -> Result<Vec<IpPair>, Err\nif let IpNetwork::V6(ref ip) = route.prefix {\n// Only host addresses and installed routes\nif ip.prefix() == 128 && route.installed && IpAddr::V6(ip.ip()) == mesh_ip {\n+ // check if we've already looked up this interface this round, since gateways\n+ // have many clients this will often be the case\n+ if let Some(remote_ip) = remote_ip_cache.get(&route.iface) {\n+ results.push(IpPair {\n+ mesh_ip,\n+ gateway_ip: *remote_ip,\n+ });\n+ } else {\nmatch KI.get_wg_remote_ip(&route.iface) {\n- Ok(remote_ip) => results.push(IpPair {\n+ Ok(remote_ip) => {\n+ remote_ip_cache.insert(route.iface.clone(), remote_ip);\n+ results.push(IpPair {\nmesh_ip,\ngateway_ip: remote_ip,\n- }),\n+ })\n+ }\nErr(e) => error!(\"Failure looking up remote ip {:?}\", e),\n}\n}\n}\n}\n}\n+ }\nOk(results)\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Cache wg lookups for region validation
20,244
04.06.2019 14:27:34
14,400
7edfac6e6fe457f1cda0ea4287007733c68d902a
Clean up main files and bump worker counts
[ { "change_type": "MODIFY", "old_path": "rita/src/client.rs", "new_path": "rita/src/client.rs", "diff": "@@ -34,7 +34,6 @@ use settings::FileWrite;\nuse settings::client::{RitaClientSettings, RitaSettingsStruct};\nuse settings::RitaCommonSettings;\n-use actix::registry::SystemService;\nuse actix_web::http::Method;\nuse actix_web::{http, server, App};\n@@ -47,8 +46,9 @@ mod middleware;\nmod rita_client;\nmod rita_common;\n-use rita_common::rita_loop::fast_loop::RitaFastLoop;\n-use rita_common::rita_loop::slow_loop::RitaSlowLoop;\n+use rita_client::rita_loop::check_rita_client_actors;\n+use rita_common::rita_loop::check_rita_common_actors;\n+use rita_common::rita_loop::start_core_rita_endpoints;\nuse crate::rita_client::dashboard::eth_private_key::*;\nuse crate::rita_client::dashboard::exits::*;\n@@ -202,33 +202,15 @@ fn main() {\nlet system = actix::System::new(format!(\"main {:?}\", SETTING.get_network().mesh_ip));\n- assert!(rita_common::debt_keeper::DebtKeeper::from_registry().connected());\n- assert!(rita_common::payment_controller::PaymentController::from_registry().connected());\n- assert!(rita_common::payment_validator::PaymentValidator::from_registry().connected());\n- assert!(rita_common::tunnel_manager::TunnelManager::from_registry().connected());\n- assert!(rita_common::hello_handler::HelloHandler::from_registry().connected());\n- assert!(rita_common::traffic_watcher::TrafficWatcher::from_registry().connected());\n- assert!(rita_common::peer_listener::PeerListener::from_registry().connected());\n- assert!(rita_client::exit_manager::ExitManager::from_registry().connected());\n-\n- // rita\n- server::new(|| App::new().resource(\"/hello\", |r| r.method(Method::POST).with(hello_response)))\n- .workers(1)\n- .bind(format!(\"[::0]:{}\", SETTING.get_network().rita_hello_port))\n- .unwrap()\n- .shutdown_timeout(0)\n- .start();\n- server::new(|| {\n- App::new().resource(\"/make_payment\", |r| {\n- r.method(Method::POST).with(make_payments)\n- })\n- })\n- .workers(1)\n- .bind(format!(\"[::0]:{}\", SETTING.get_network().rita_contact_port))\n- .unwrap()\n- .shutdown_timeout(0)\n- .start();\n+ check_rita_common_actors();\n+ check_rita_client_actors();\n+ start_core_rita_endpoints(2);\n+ start_client_dashboard();\n+\n+ system.run();\n+}\n+fn start_client_dashboard() {\n// dashboard\nserver::new(|| {\nApp::new()\n@@ -330,10 +312,4 @@ fn main() {\n.unwrap()\n.shutdown_timeout(0)\n.start();\n-\n- assert!(RitaFastLoop::from_registry().connected());\n- assert!(RitaSlowLoop::from_registry().connected());\n- assert!(rita_client::rita_loop::RitaLoop::from_registry().connected());\n-\n- system.run();\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/exit.rs", "new_path": "rita/src/exit.rs", "diff": "@@ -36,7 +36,6 @@ use docopt::Docopt;\n#[cfg(not(test))]\nuse settings::FileWrite;\n-use actix::registry::SystemService;\nuse actix_web::http::Method;\nuse actix_web::{http, server, App};\n@@ -44,8 +43,11 @@ mod middleware;\nmod rita_common;\nmod rita_exit;\n-use rita_common::rita_loop::fast_loop::RitaFastLoop;\n-use rita_common::rita_loop::slow_loop::RitaSlowLoop;\n+use rita_common::rita_loop::check_rita_common_actors;\n+use rita_common::rita_loop::start_core_rita_endpoints;\n+\n+use rita_exit::rita_loop::check_rita_exit_actors;\n+use rita_exit::rita_loop::start_rita_exit_endpoints;\nuse crate::rita_common::dashboard::babel::*;\nuse crate::rita_common::dashboard::dao::*;\n@@ -184,55 +186,16 @@ fn main() {\nlet system = actix::System::new(format!(\"main {:?}\", SETTING.get_network().mesh_ip));\n- assert!(rita_common::debt_keeper::DebtKeeper::from_registry().connected());\n- assert!(rita_common::payment_controller::PaymentController::from_registry().connected());\n- assert!(rita_common::payment_validator::PaymentValidator::from_registry().connected());\n- assert!(rita_common::tunnel_manager::TunnelManager::from_registry().connected());\n- assert!(rita_common::hello_handler::HelloHandler::from_registry().connected());\n- assert!(rita_common::traffic_watcher::TrafficWatcher::from_registry().connected());\n- assert!(rita_common::peer_listener::PeerListener::from_registry().connected());\n-\n- assert!(rita_exit::traffic_watcher::TrafficWatcher::from_registry().connected());\n- assert!(rita_exit::database::db_client::DbClient::from_registry().connected());\n-\n- server::new(|| App::new().resource(\"/hello\", |r| r.method(Method::POST).with(hello_response)))\n- .bind(format!(\"[::0]:{}\", SETTING.get_network().rita_hello_port))\n- .unwrap()\n- .shutdown_timeout(0)\n- .start();\n- server::new(|| {\n- App::new().resource(\"/make_payment\", |r| {\n- r.method(Method::POST).with(make_payments)\n- })\n- })\n- .workers(8)\n- .bind(format!(\"[::0]:{}\", SETTING.get_network().rita_contact_port))\n- .unwrap()\n- .shutdown_timeout(0)\n- .start();\n+ check_rita_common_actors();\n+ check_rita_exit_actors();\n+ start_core_rita_endpoints(8);\n+ start_rita_exit_endpoints(128);\n+ start_rita_exit_dashboard();\n- // Exit stuff\n- server::new(|| {\n- App::new()\n- .resource(\"/setup\", |r| r.method(Method::POST).with(setup_request))\n- .resource(\"/status\", |r| r.method(Method::POST).with(status_request))\n- .resource(\"/exit_info\", |r| {\n- r.method(Method::GET).with(get_exit_info_http)\n- })\n- .resource(\"/rtt\", |r| r.method(Method::GET).with(rtt))\n- .resource(\"/client_debt\", |r| {\n- r.method(Method::POST).with(get_client_debt)\n- })\n- })\n- .workers(8)\n- .bind(format!(\n- \"[::0]:{}\",\n- SETTING.get_exit_network().exit_hello_port\n- ))\n- .unwrap()\n- .shutdown_timeout(0)\n- .start();\n+ system.run();\n+}\n+fn start_rita_exit_dashboard() {\n// Dashboard\nserver::new(|| {\nApp::new()\n@@ -275,12 +238,7 @@ fn main() {\nSETTING.get_network().rita_dashboard_port\n))\n.unwrap()\n+ .workers(1)\n.shutdown_timeout(0)\n.start();\n-\n- assert!(RitaFastLoop::from_registry().connected());\n- assert!(RitaSlowLoop::from_registry().connected());\n- assert!(rita_exit::rita_loop::RitaLoop::from_registry().connected());\n-\n- system.run();\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/rita_loop/mod.rs", "new_path": "rita/src/rita_client/rita_loop/mod.rs", "diff": "@@ -112,3 +112,8 @@ pub fn _compute_verification_rtt() -> Result<RTTimestamps, Error> {\ninfo!(\"Computed RTTs: inner {}ms\", inner_rtt_millis);\nOk(timestamps)\n}\n+\n+pub fn check_rita_client_actors() {\n+ assert!(crate::rita_client::rita_loop::RitaLoop::from_registry().connected());\n+ assert!(crate::rita_client::exit_manager::ExitManager::from_registry().connected());\n+}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/mod.rs", "new_path": "rita/src/rita_common/rita_loop/mod.rs", "diff": "//! all system functions. Anything that blocks will eventually filter up to block this loop and\n//! halt essential functions like opening tunnels and managing peers\n+use crate::rita_common::network_endpoints::*;\nuse crate::SETTING;\n+use actix::SystemService;\n+use actix_web::http::Method;\n+use actix_web::{server, App};\nuse rand::thread_rng;\nuse rand::Rng;\nuse settings::RitaCommonSettings;\n@@ -26,3 +30,37 @@ pub fn get_web3_server() -> String {\nnode_list[val].clone()\n}\n+\n+pub fn start_core_rita_endpoints(workers: usize) {\n+ // Rita hello function\n+ server::new(|| App::new().resource(\"/hello\", |r| r.method(Method::POST).with(hello_response)))\n+ .workers(workers)\n+ .bind(format!(\"[::0]:{}\", SETTING.get_network().rita_hello_port))\n+ .unwrap()\n+ .shutdown_timeout(0)\n+ .start();\n+\n+ // Rita accept payment function, on a different port\n+ server::new(|| {\n+ App::new().resource(\"/make_payment\", |r| {\n+ r.method(Method::POST).with(make_payments)\n+ })\n+ })\n+ .workers(workers)\n+ .bind(format!(\"[::0]:{}\", SETTING.get_network().rita_contact_port))\n+ .unwrap()\n+ .shutdown_timeout(0)\n+ .start();\n+}\n+\n+pub fn check_rita_common_actors() {\n+ assert!(crate::rita_common::debt_keeper::DebtKeeper::from_registry().connected());\n+ assert!(crate::rita_common::payment_controller::PaymentController::from_registry().connected());\n+ assert!(crate::rita_common::payment_validator::PaymentValidator::from_registry().connected());\n+ assert!(crate::rita_common::tunnel_manager::TunnelManager::from_registry().connected());\n+ assert!(crate::rita_common::hello_handler::HelloHandler::from_registry().connected());\n+ assert!(crate::rita_common::traffic_watcher::TrafficWatcher::from_registry().connected());\n+ assert!(crate::rita_common::peer_listener::PeerListener::from_registry().connected());\n+ assert!(crate::rita_common::rita_loop::fast_loop::RitaFastLoop::from_registry().connected());\n+ assert!(crate::rita_common::rita_loop::slow_loop::RitaSlowLoop::from_registry().connected());\n+}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "@@ -24,6 +24,7 @@ use crate::rita_exit::database::{\ncleanup_exit_clients, enforce_exit_clients, get_database_connection, setup_clients,\nvalidate_clients_region,\n};\n+use crate::rita_exit::network_endpoints::*;\nuse crate::rita_exit::traffic_watcher::{TrafficWatcher, Watch};\nuse crate::KI;\nuse crate::SETTING;\n@@ -31,6 +32,8 @@ use actix::{\nActor, ActorContext, Arbiter, AsyncContext, Context, Handler, Message, Supervised, SyncArbiter,\nSyncContext, SystemService,\n};\n+use actix_web::http::Method;\n+use actix_web::{server, App};\nuse althea_kernel_interface::ExitClient;\nuse diesel::query_dsl::RunQueryDsl;\nuse exit_db::models;\n@@ -172,3 +175,33 @@ fn setup_exit_wg_tunnel() {\nKI.setup_nat(&SETTING.get_network().external_nic.clone().unwrap())\n.unwrap();\n}\n+\n+pub fn check_rita_exit_actors() {\n+ assert!(crate::rita_exit::rita_loop::RitaLoop::from_registry().connected());\n+ assert!(crate::rita_exit::traffic_watcher::TrafficWatcher::from_registry().connected());\n+ assert!(crate::rita_exit::database::db_client::DbClient::from_registry().connected());\n+}\n+\n+pub fn start_rita_exit_endpoints(workers: usize) {\n+ // Exit stuff, huge threadpool to offset Pgsql blocking\n+ server::new(|| {\n+ App::new()\n+ .resource(\"/setup\", |r| r.method(Method::POST).with(setup_request))\n+ .resource(\"/status\", |r| r.method(Method::POST).with(status_request))\n+ .resource(\"/exit_info\", |r| {\n+ r.method(Method::GET).with(get_exit_info_http)\n+ })\n+ .resource(\"/rtt\", |r| r.method(Method::GET).with(rtt))\n+ .resource(\"/client_debt\", |r| {\n+ r.method(Method::POST).with(get_client_debt)\n+ })\n+ })\n+ .workers(workers)\n+ .bind(format!(\n+ \"[::0]:{}\",\n+ SETTING.get_exit_network().exit_hello_port\n+ ))\n+ .unwrap()\n+ .shutdown_timeout(0)\n+ .start();\n+}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Clean up main files and bump worker counts
20,244
30.05.2019 08:38:39
14,400
9bc6fc8fcf4da2d21b677bad96c12b33ac87267a
Async Babel monitor
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -253,9 +253,13 @@ dependencies = [\n\"bufstream 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"futures 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"ipnetwork 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"mockstream 0.0.3 (git+https://github.com/lazy-bitfield/rust-mockstream.git)\",\n+ \"tokio 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"tokio-tcp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n[[package]]\n" }, { "change_type": "MODIFY", "old_path": "Cargo.toml", "new_path": "Cargo.toml", "diff": "@@ -14,7 +14,7 @@ rita = { path = \"./rita\" }\nmembers = [\"althea_kernel_interface\", \"bounty_hunter\", \"settings\", \"clu\", \"exit_db\"]\n[profile.release]\n-opt-level = \"z\"\n+opt-level = 2\nlto = true\ncodegen-units = 1\nincremental = false\n" }, { "change_type": "MODIFY", "old_path": "babel_monitor/Cargo.toml", "new_path": "babel_monitor/Cargo.toml", "diff": "@@ -7,10 +7,14 @@ edition = \"2018\"\n[dependencies]\nascii = \"0.9\"\nbufstream = \"0.1\"\n-env_logger = \"0.6.0\"\n+env_logger = \"0.6\"\nfailure = \"0.1\"\nipnetwork = \"0.14\"\nlog = \"0.4\"\n+futures = \"0.1\"\n+tokio-tcp = \"0.1\"\n+tokio-io = \"0.1\"\n+tokio = \"0.1\"\n[dependencies.mockstream]\ngit = \"https://github.com/lazy-bitfield/rust-mockstream.git\"\n" }, { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "extern crate failure;\n#[macro_use]\nextern crate log;\n+extern crate futures;\n+extern crate tokio_tcp;\n-use bufstream::BufStream;\nuse failure::Error;\n+use futures::future::result as future_result;\n+use futures::future::Either;\n+use futures::future::Future;\nuse ipnetwork::IpNetwork;\nuse std::collections::VecDeque;\n-use std::io::{BufRead, Read, Write};\nuse std::iter::Iterator;\nuse std::net::IpAddr;\nuse std::net::SocketAddr;\n-use std::net::TcpStream;\nuse std::str;\n-use std::time::Duration;\n-\n-const BABEL_OPERATION_TIMEOUT: Duration = Duration::from_secs(1);\n+use tokio::io::read_to_end;\n+use tokio::io::write_all;\n+use tokio_tcp::ConnectFuture;\n+use tokio_tcp::TcpStream;\n#[derive(Debug, Fail)]\npub enum BabelMonitorError {\n@@ -33,11 +36,13 @@ pub enum BabelMonitorError {\nNoTerminator(String),\n#[fail(display = \"No Neighbor was found matching address:\\n{}\", _0)]\nNoNeighbor(String),\n+ #[fail(display = \"Tokio had a failure while it was talking to babel:\\n{}\", _0)]\n+ TokioError(String),\n}\nuse crate::BabelMonitorError::{\nCommandFailed, InvalidPreamble, LocalFeeNotFound, NoNeighbor, NoTerminator, ReadFailed,\n- VariableNotFound,\n+ TokioError, VariableNotFound,\n};\n// If a function doesn't need internal state of the Babel object\n@@ -86,31 +91,33 @@ pub struct Neighbor {\n/// Opens a tcpstream to the babel management socket using a standard timeout\n/// for both the open and read operations\n-pub fn open_babel_stream(babel_port: u16) -> Result<TcpStream, Error> {\n- let socket: SocketAddr = format!(\"[::1]:{}\", babel_port,).parse()?;\n- let stream = TcpStream::connect_timeout(&socket, BABEL_OPERATION_TIMEOUT)?;\n- stream.set_read_timeout(Some(BABEL_OPERATION_TIMEOUT))?;\n- Ok(stream)\n+pub fn open_babel_stream(babel_port: u16) -> ConnectFuture {\n+ let socket: SocketAddr = format!(\"[::1]:{}\", babel_port,).parse().unwrap();\n+ TcpStream::connect(&socket)\n}\n-pub struct Babel<T: Read + Write> {\n- stream: BufStream<T>,\n+fn read_babel(stream: TcpStream) -> Box<Future<Item = (TcpStream, String), Error = Error>> {\n+ let buffer = Vec::new();\n+ Box::new(read_to_end(stream, buffer).then(|result| {\n+ if result.is_err() {\n+ return Err(TokioError(format!(\"{:?}\", result)).into());\n}\n-\n-impl<T: Read + Write> Babel<T> {\n- pub fn new(stream: T) -> Babel<T> {\n- Babel {\n- stream: BufStream::new(stream),\n+ let (stream, buffer) = result.unwrap();\n+ let output = String::from_utf8(buffer);\n+ if output.is_err() {\n+ //handle\n}\n+ let output = output.unwrap();\n+ Ok((stream, read_babel_sync(output)?))\n+ }))\n}\n- fn read_babel(&mut self) -> Result<String, Error> {\n+fn read_babel_sync(output: String) -> Result<String, Error> {\nlet mut ret = String::new();\n- for line in Read::by_ref(&mut self.stream).lines() {\n- let line = &line?;\n+ for line in output.lines() {\nret.push_str(line);\nret.push_str(\"\\n\");\n- match line.as_str().trim() {\n+ match line.trim() {\n\"ok\" => {\ntrace!(\n\"Babel returned ok; full output:\\n{}\\nEND OF BABEL OUTPUT\",\n@@ -135,20 +142,38 @@ impl<T: Read + Write> Babel<T> {\nreturn Err(NoTerminator(ret).into());\n}\n- fn command(&mut self, cmd: &str) -> Result<String, Error> {\n- self.stream.write_all(format!(\"{}\\n\", cmd).as_bytes())?;\n- self.stream.flush()?;\n-\n- trace!(\"Sent '{}' to babel\", cmd);\n- match self.read_babel() {\n- Ok(out) => Ok(out),\n- Err(e) => Err(CommandFailed(String::from(cmd), e.to_string()).into()),\n+fn run_command(\n+ stream: TcpStream,\n+ cmd: &str,\n+) -> Box<Future<Item = (TcpStream, String), Error = Error>> {\n+ let mut bytes = Vec::new();\n+ bytes.clone_from_slice(&cmd.as_bytes());\n+ Box::new(write_all(stream, bytes).then(move |out| {\n+ if out.is_err() {\n+ return Box::new(Either::A(future_result(Err(TokioError(format!(\n+ \"{:?}\",\n+ out\n+ ))\n+ .into()))));\n}\n+ let (stream, _res) = out.unwrap();\n+ Box::new(Either::B(read_babel(stream)))\n+ }))\n}\n// Consumes the automated Preamble and validates configuration api version\n- pub fn start_connection(&mut self) -> Result<(), Error> {\n- let preamble = self.read_babel()?;\n+pub fn start_connection(stream: TcpStream) -> Box<Future<Item = TcpStream, Error = Error>> {\n+ Box::new(read_babel(stream).then(|result| {\n+ if let Err(e) = result {\n+ return Err(e);\n+ }\n+ let (stream, preamble) = result.unwrap();\n+ validate_preamble(preamble)?;\n+ Ok(stream)\n+ }))\n+}\n+\n+fn validate_preamble(preamble: String) -> Result<(), Error> {\n// Note you have changed the config interface, bump to 1.1 in babel\nif preamble.contains(\"ALTHEA 0.1\") {\ntrace!(\"Attached OK to Babel with preamble: {}\", preamble);\n@@ -158,8 +183,17 @@ impl<T: Read + Write> Babel<T> {\n}\n}\n- pub fn get_local_fee(&mut self) -> Result<u32, Error> {\n- let babel_output = self.command(\"dump\")?;\n+pub fn get_local_fee(stream: TcpStream) -> Box<Future<Item = (TcpStream, u32), Error = Error>> {\n+ Box::new(run_command(stream, \"dump\").then(|output| {\n+ if let Err(e) = output {\n+ return Err(e);\n+ }\n+ let (stream, babel_output) = output.unwrap();\n+ Ok((stream, get_local_fee_sync(babel_output)?))\n+ }))\n+}\n+\n+fn get_local_fee_sync(babel_output: String) -> Result<u32, Error> {\nlet fee_entry = match babel_output.split(\"\\n\").nth(0) {\nSome(entry) => entry,\n// Even an empty string wouldn't yield None\n@@ -175,45 +209,100 @@ impl<T: Read + Write> Babel<T> {\nErr(LocalFeeNotFound(String::from(fee_entry)).into())\n}\n- pub fn set_local_fee(&mut self, new_fee: u32) -> Result<(), Error> {\n- let _babel_output = self.command(&format!(\"fee {}\", new_fee))?;\n- Ok(())\n+pub fn set_local_fee(\n+ stream: TcpStream,\n+ new_fee: u32,\n+) -> Box<Future<Item = TcpStream, Error = Error>> {\n+ Box::new(\n+ run_command(stream, &format!(\"fee {}\", new_fee)).then(|result| {\n+ if let Err(e) = result {\n+ return Err(e);\n+ }\n+ let (stream, _out) = result.unwrap();\n+ Ok(stream)\n+ }),\n+ )\n}\n- pub fn set_metric_factor(&mut self, new_factor: u32) -> Result<(), Error> {\n- let _babel_output = self.command(&format!(\"metric-factor {}\", new_factor))?;\n- Ok(())\n+pub fn set_metric_factor(\n+ stream: TcpStream,\n+ new_factor: u32,\n+) -> Box<Future<Item = TcpStream, Error = Error>> {\n+ Box::new(\n+ run_command(stream, &format!(\"metric-factor {}\", new_factor)).then(|result| {\n+ if let Err(e) = result {\n+ return Err(e);\n+ }\n+ let (stream, _out) = result.unwrap();\n+ Ok(stream)\n+ }),\n+ )\n}\n- pub fn monitor(&mut self, iface: &str) -> Result<(), Error> {\n- let _ = self.command(&format!(\n+pub fn monitor(stream: TcpStream, iface: &str) -> Box<Future<Item = TcpStream, Error = Error>> {\n+ let command = &format!(\n\"interface {} max-rtt-penalty 500 enable-timestamps true\",\niface\n- ))?;\n+ );\n+ let iface = iface.to_string();\n+ Box::new(run_command(stream, &command).then(move |result| {\n+ if let Err(e) = result {\n+ return Err(e);\n+ }\ntrace!(\"Babel started monitoring: {}\", iface);\n- Ok(())\n+ let (stream, _out) = result.unwrap();\n+ Ok(stream)\n+ }))\n}\n- pub fn redistribute_ip(&mut self, ip: &IpAddr, allow: bool) -> Result<(), Error> {\n- let commmand = format!(\n+pub fn redistribute_ip(\n+ stream: TcpStream,\n+ ip: &IpAddr,\n+ allow: bool,\n+) -> Box<Future<Item = (TcpStream, String), Error = Error>> {\n+ let command = format!(\n\"redistribute ip {}/128 {}\",\nip,\nif allow { \"allow\" } else { \"deny\" }\n);\n- self.command(&commmand)?;\n- let _ = self.read_babel()?;\n- Ok(())\n+ Box::new(run_command(stream, &command).then(move |result| {\n+ if let Err(e) = result {\n+ return Box::new(Either::A(future_result(Err(e).into())));\n+ }\n+ let (stream, _out) = result.unwrap();\n+ Box::new(Either::B(read_babel(stream)))\n+ }))\n+}\n+\n+pub fn unmonitor(stream: TcpStream, iface: &str) -> Box<Future<Item = TcpStream, Error = Error>> {\n+ let command = format!(\"flush interface {}\", iface);\n+ let iface = iface.to_string();\n+ Box::new(run_command(stream, &command).then(move |result| {\n+ if let Err(e) = result {\n+ return Err(e);\n+ }\n+ trace!(\"Babel stopped monitoring: {}\", iface);\n+ let (stream, _out) = result.unwrap();\n+ Ok(stream)\n+ }))\n}\n- pub fn unmonitor(&mut self, iface: &str) -> Result<(), Error> {\n- self.command(&format!(\"flush interface {}\", iface))?;\n- Ok(())\n+pub fn parse_neighs(\n+ stream: TcpStream,\n+) -> Box<Future<Item = (TcpStream, VecDeque<Neighbor>), Error = Error>> {\n+ Box::new(run_command(stream, \"dump\").then(|result| {\n+ if let Err(e) = result {\n+ return Err(e);\n+ }\n+ let (stream, output) = result.unwrap();\n+ Ok((stream, parse_neighs_sync(output)?))\n+ }))\n}\n- pub fn parse_neighs(&mut self) -> Result<VecDeque<Neighbor>, Error> {\n+fn parse_neighs_sync(output: String) -> Result<VecDeque<Neighbor>, Error> {\nlet mut vector: VecDeque<Neighbor> = VecDeque::with_capacity(5);\nlet mut found_neigh = false;\n- for entry in self.command(\"dump\")?.split(\"\\n\") {\n+ for entry in output.split(\"\\n\") {\nif entry.contains(\"add neighbour\") {\nfound_neigh = true;\nlet neigh = Neighbor {\n@@ -307,9 +396,20 @@ impl<T: Read + Write> Babel<T> {\nOk(vector)\n}\n- pub fn parse_routes(&mut self) -> Result<VecDeque<Route>, Error> {\n+pub fn parse_routes(\n+ stream: TcpStream,\n+) -> Box<Future<Item = (TcpStream, VecDeque<Route>), Error = Error>> {\n+ Box::new(run_command(stream, \"dump\").then(|result| {\n+ if let Err(e) = result {\n+ return Err(e);\n+ }\n+ let (stream, babel_out) = result.unwrap();\n+ Ok((stream, parse_routes_sync(babel_out)?))\n+ }))\n+}\n+\n+pub fn parse_routes_sync(babel_out: String) -> Result<VecDeque<Route>, Error> {\nlet mut vector: VecDeque<Route> = VecDeque::with_capacity(20);\n- let babel_out = self.command(\"dump\")?;\nlet mut found_route = false;\ntrace!(\"Got from babel dump: {}\", babel_out);\n@@ -417,7 +517,6 @@ impl<T: Read + Write> Babel<T> {\n/// via that neighbor. This could be dramatically more efficient if we had the neighbors\n/// local ip lying around somewhere.\npub fn get_route_via_neigh(\n- &mut self,\nneigh_mesh_ip: IpAddr,\ndest_mesh_ip: IpAddr,\nroutes: &VecDeque<Route>,\n@@ -441,13 +540,8 @@ impl<T: Read + Write> Babel<T> {\n}\nErr(NoNeighbor(neigh_mesh_ip.to_string()).into())\n}\n-\n/// Checks if Babel has an installed route to the given destination\n- pub fn do_we_have_route(\n- &mut self,\n- mesh_ip: &IpAddr,\n- routes: &VecDeque<Route>,\n- ) -> Result<bool, Error> {\n+pub fn do_we_have_route(mesh_ip: &IpAddr, routes: &VecDeque<Route>) -> Result<bool, Error> {\nfor route in routes.iter() {\nif let IpNetwork::V6(ref ip) = route.prefix {\nif ip.ip() == *mesh_ip && route.installed {\n@@ -457,13 +551,8 @@ impl<T: Read + Write> Babel<T> {\n}\nOk(false)\n}\n-\n/// Returns the installed route to a given destination\n- pub fn get_installed_route(\n- &mut self,\n- mesh_ip: &IpAddr,\n- routes: &VecDeque<Route>,\n- ) -> Result<Route, Error> {\n+pub fn get_installed_route(mesh_ip: &IpAddr, routes: &VecDeque<Route>) -> Result<Route, Error> {\nlet mut exit_route = None;\nfor route in routes.iter() {\n// Only ip6\n@@ -480,11 +569,9 @@ impl<T: Read + Write> Babel<T> {\n}\nOk(exit_route.unwrap().clone())\n}\n-}\n#[cfg(test)]\nmod tests {\nuse super::*;\n- use mockstream::SharedMockStream;\nstatic TABLE: &'static str =\n\"local fee 1024\\n\\\n@@ -539,24 +626,6 @@ ok\\n\";\nstatic PRICE_LINE: &'static str = \"local price 1024\";\n- #[test]\n- fn mock_connect() {\n- let mut s = SharedMockStream::new();\n- s.push_bytes_to_read(PREAMBLE.as_bytes());\n- let mut b = Babel::new(s);\n- b.start_connection().unwrap()\n- }\n-\n- #[test]\n- fn mock_dump() {\n- let mut s = SharedMockStream::new();\n- s.push_bytes_to_read(TABLE.as_bytes());\n-\n- let mut b = Babel::new(s);\n- let dump = b.command(\"dump\").unwrap();\n- assert_eq!(&dump, TABLE);\n- }\n-\n#[test]\nfn line_parse() {\nassert_eq!(find_babel_val(\"metric\", XROUTE_LINE).unwrap(), \"0\");\n@@ -598,10 +667,7 @@ ok\\n\";\n#[test]\nfn neigh_parse() {\n- let mut s = SharedMockStream::new();\n- s.push_bytes_to_read(TABLE.as_bytes());\n- let mut b = Babel::new(s);\n- let neighs = b.parse_neighs().unwrap();\n+ let neighs = parse_neighs_sync(TABLE.to_string()).unwrap();\nlet neigh = neighs.get(0);\nassert!(neigh.is_some());\nlet neigh = neigh.unwrap();\n@@ -611,11 +677,7 @@ ok\\n\";\n#[test]\nfn route_parse() {\n- let mut s = SharedMockStream::new();\n- s.push_bytes_to_read(TABLE.as_bytes());\n- let mut b = Babel::new(s);\n-\n- let routes = b.parse_routes().unwrap();\n+ let routes = parse_routes_sync(TABLE.to_string()).unwrap();\nassert_eq!(routes.len(), 5);\nlet route = routes.get(0).unwrap();\n@@ -624,39 +686,22 @@ ok\\n\";\n#[test]\nfn local_fee_parse() {\n- let mut s = SharedMockStream::new();\n- s.push_bytes_to_read(TABLE.as_bytes());\n-\n- let mut b = Babel::new(s);\n- assert_eq!(b.get_local_fee().unwrap(), 1024);\n+ assert_eq!(get_local_fee_sync(TABLE.to_string()).unwrap(), 1024);\n}\n#[test]\nfn multiple_babel_outputs_in_stream() {\n- let mut s = SharedMockStream::new();\n- s.push_bytes_to_read(PREAMBLE.as_bytes());\n- s.push_bytes_to_read(TABLE.as_bytes());\n- s.push_bytes_to_read(b\"ok\\n\");\n-\n- let mut b = Babel::new(s);\n- b.start_connection().unwrap();\n-\n- let routes = b.parse_routes().unwrap();\n+ let input = PREAMBLE.to_string() + TABLE + \"ok\\n\";\n+ let routes = parse_routes_sync(input).unwrap();\nassert_eq!(routes.len(), 5);\nlet route = routes.get(0).unwrap();\nassert_eq!(route.price, 3072);\nassert_eq!(route.full_path_rtt, 22.805);\n-\n- b.command(\"interface wg0\").unwrap();\n}\n#[test]\nfn only_ok_in_output() {\n- let mut s = SharedMockStream::new();\n- s.push_bytes_to_read(b\"ok\\n\");\n-\n- let mut b = Babel::new(s);\n- b.command(\"interface wg0\").unwrap();\n+ read_babel_sync(\"ok\\n\".to_string()).unwrap();\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Async Babel monitor
20,244
30.05.2019 08:41:13
14,400
60f90d21cafd45e02c448651b9d37615640ea5df
Use Vec instead of VecDeque
[ { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "@@ -10,7 +10,6 @@ use futures::future::result as future_result;\nuse futures::future::Either;\nuse futures::future::Future;\nuse ipnetwork::IpNetwork;\n-use std::collections::VecDeque;\nuse std::iter::Iterator;\nuse std::net::IpAddr;\nuse std::net::SocketAddr;\n@@ -148,12 +147,13 @@ fn run_command(\n) -> Box<Future<Item = (TcpStream, String), Error = Error>> {\nlet mut bytes = Vec::new();\nbytes.clone_from_slice(&cmd.as_bytes());\n+ let cmd = cmd.to_string();\nBox::new(write_all(stream, bytes).then(move |out| {\nif out.is_err() {\n- return Box::new(Either::A(future_result(Err(TokioError(format!(\n- \"{:?}\",\n- out\n- ))\n+ return Box::new(Either::A(future_result(Err(CommandFailed(\n+ cmd,\n+ format!(\"{:?}\", out),\n+ )\n.into()))));\n}\nlet (stream, _res) = out.unwrap();\n@@ -289,7 +289,7 @@ pub fn unmonitor(stream: TcpStream, iface: &str) -> Box<Future<Item = TcpStream,\npub fn parse_neighs(\nstream: TcpStream,\n-) -> Box<Future<Item = (TcpStream, VecDeque<Neighbor>), Error = Error>> {\n+) -> Box<Future<Item = (TcpStream, Vec<Neighbor>), Error = Error>> {\nBox::new(run_command(stream, \"dump\").then(|result| {\nif let Err(e) = result {\nreturn Err(e);\n@@ -299,8 +299,8 @@ pub fn parse_neighs(\n}))\n}\n-fn parse_neighs_sync(output: String) -> Result<VecDeque<Neighbor>, Error> {\n- let mut vector: VecDeque<Neighbor> = VecDeque::with_capacity(5);\n+fn parse_neighs_sync(output: String) -> Result<Vec<Neighbor>, Error> {\n+ let mut vector: Vec<Neighbor> = Vec::with_capacity(5);\nlet mut found_neigh = false;\nfor entry in output.split(\"\\n\") {\nif entry.contains(\"add neighbour\") {\n@@ -387,7 +387,7 @@ fn parse_neighs_sync(output: String) -> Result<VecDeque<Neighbor>, Error> {\nErr(_) => continue,\n},\n};\n- vector.push_back(neigh);\n+ vector.push(neigh);\n}\n}\nif vector.len() == 0 && found_neigh {\n@@ -398,7 +398,7 @@ fn parse_neighs_sync(output: String) -> Result<VecDeque<Neighbor>, Error> {\npub fn parse_routes(\nstream: TcpStream,\n-) -> Box<Future<Item = (TcpStream, VecDeque<Route>), Error = Error>> {\n+) -> Box<Future<Item = (TcpStream, Vec<Route>), Error = Error>> {\nBox::new(run_command(stream, \"dump\").then(|result| {\nif let Err(e) = result {\nreturn Err(e);\n@@ -408,8 +408,8 @@ pub fn parse_routes(\n}))\n}\n-pub fn parse_routes_sync(babel_out: String) -> Result<VecDeque<Route>, Error> {\n- let mut vector: VecDeque<Route> = VecDeque::with_capacity(20);\n+pub fn parse_routes_sync(babel_out: String) -> Result<Vec<Route>, Error> {\n+ let mut vector: Vec<Route> = Vec::with_capacity(20);\nlet mut found_route = false;\ntrace!(\"Got from babel dump: {}\", babel_out);\n@@ -503,7 +503,7 @@ pub fn parse_routes_sync(babel_out: String) -> Result<VecDeque<Route>, Error> {\n},\n};\n- vector.push_back(route);\n+ vector.push(route);\n}\n}\nif vector.len() == 0 && found_route {\n@@ -519,7 +519,7 @@ pub fn parse_routes_sync(babel_out: String) -> Result<VecDeque<Route>, Error> {\npub fn get_route_via_neigh(\nneigh_mesh_ip: IpAddr,\ndest_mesh_ip: IpAddr,\n- routes: &VecDeque<Route>,\n+ routes: &Vec<Route>,\n) -> Result<Route, Error> {\n// First find the neighbors route to itself to get the local address\nfor neigh_route in routes.iter() {\n@@ -541,7 +541,7 @@ pub fn get_route_via_neigh(\nErr(NoNeighbor(neigh_mesh_ip.to_string()).into())\n}\n/// Checks if Babel has an installed route to the given destination\n-pub fn do_we_have_route(mesh_ip: &IpAddr, routes: &VecDeque<Route>) -> Result<bool, Error> {\n+pub fn do_we_have_route(mesh_ip: &IpAddr, routes: &Vec<Route>) -> Result<bool, Error> {\nfor route in routes.iter() {\nif let IpNetwork::V6(ref ip) = route.prefix {\nif ip.ip() == *mesh_ip && route.installed {\n@@ -552,7 +552,7 @@ pub fn do_we_have_route(mesh_ip: &IpAddr, routes: &VecDeque<Route>) -> Result<bo\nOk(false)\n}\n/// Returns the installed route to a given destination\n-pub fn get_installed_route(mesh_ip: &IpAddr, routes: &VecDeque<Route>) -> Result<Route, Error> {\n+pub fn get_installed_route(mesh_ip: &IpAddr, routes: &Vec<Route>) -> Result<Route, Error> {\nlet mut exit_route = None;\nfor route in routes.iter() {\n// Only ip6\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Use Vec instead of VecDeque
20,244
30.05.2019 09:38:53
14,400
838702341b430e197efdf0ae356f03be7cad5d99
Update clu to use async babel
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -435,10 +435,11 @@ dependencies = [\n\"clarity 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"futures 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"ipgen 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"regex 1.1.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)\",\n" }, { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "@@ -141,7 +141,7 @@ fn read_babel_sync(output: String) -> Result<String, Error> {\nreturn Err(NoTerminator(ret).into());\n}\n-fn run_command(\n+pub fn run_command(\nstream: TcpStream,\ncmd: &str,\n) -> Box<Future<Item = (TcpStream, String), Error = Error>> {\n" }, { "change_type": "MODIFY", "old_path": "clu/Cargo.toml", "new_path": "clu/Cargo.toml", "diff": "@@ -9,14 +9,15 @@ settings = { path = \"../settings\" }\nalthea_kernel_interface = { path = \"../althea_kernel_interface\" }\nalthea_types = { path = \"../althea_types\" }\nbabel_monitor = { path = \"../babel_monitor\" }\n-lazy_static = \"1.1\"\n+lazy_static = \"1.3\"\nlog = \"0.4\"\n-env_logger = \"0.6.0\"\n+env_logger = \"0.6\"\nfailure = \"0.1\"\nipgen = \"0.0.4\"\n-regex = \"1.0\"\n-rand = \"0.5\"\n+regex = \"1.1\"\n+rand = \"0.6\"\nserde = \"1.0\"\nserde_derive = \"1.0\"\nserde_json = \"1.0\"\nclarity = \"0.1\"\n+futures = \"0.1\"\n" }, { "change_type": "MODIFY", "old_path": "clu/src/lib.rs", "new_path": "clu/src/lib.rs", "diff": "#[macro_use]\nextern crate log;\n-\n#[macro_use]\nextern crate failure;\n-\n#[macro_use]\nextern crate lazy_static;\n-use settings;\n-use settings::exit::RitaExitSettings;\n-use settings::RitaCommonSettings;\n-\n-use ipgen;\n-use rand;\n-\n+use althea_kernel_interface::KI;\n+use babel_monitor::open_babel_stream;\n+use babel_monitor::run_command;\n+use babel_monitor::set_local_fee;\n+use babel_monitor::set_metric_factor;\n+use babel_monitor::start_connection;\nuse clarity::PrivateKey;\n-\n-use rand::{thread_rng, Rng};\n-\n-use std::str;\n-\nuse failure::Error;\n-\n-use althea_kernel_interface::KI;\n-\n+use futures::future::Future;\n+use futures::future::Join;\n+use ipgen;\n+use rand;\nuse rand::distributions::Alphanumeric;\n+use rand::{thread_rng, Rng};\nuse regex::Regex;\n+use settings;\n+use settings::exit::RitaExitSettings;\n+use settings::RitaCommonSettings;\nuse std::fs::File;\nuse std::io::Read;\nuse std::net::{IpAddr, SocketAddr, TcpStream};\nuse std::path::Path;\n+use std::str;\nuse std::sync::{Arc, RwLock};\n-use babel_monitor::Babel;\n-\n#[derive(Debug, Fail)]\npub enum CluError {\n#[fail(display = \"Runtime Error: {:?}\", _0)]\n@@ -208,23 +204,19 @@ fn linux_init(config: Arc<RwLock<settings::client::RitaSettingsStruct>>) -> Resu\nwarn!(\"THIS NODE DOESN'T PAY ATTENTION TO ROUTE PRICE - IT'LL CHOOSE THE BEST ROUTE EVEN IF IT COSTS WAY TOO MUCH. PLEASE SET metric_factor TO A LOWER VALUE TO DISABLE THIS WARNING.\");\n}\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", config.get_network().babel_port).parse()?,\n- )?;\n-\n- let mut babel = Babel::new(stream);\n-\n- babel.start_connection()?;\n-\n- match babel.set_local_fee(local_fee) {\n- Ok(()) => info!(\"Local fee set to {}\", local_fee),\n- Err(e) => warn!(\"Could not set local fee! {:?}\", e),\n- }\n-\n- match babel.set_metric_factor(metric_factor) {\n- Ok(()) => info!(\"Metric factor set to {}\", metric_factor),\n- Err(e) => warn!(\"Could not set metric factor! {:?}\", e),\n- }\n+ // it's safe to use wait because CLU is run outside of the event loop\n+ // pre-startup, if we can't get to babel now we should just panic\n+ open_babel_stream(config.get_network().babel_port)\n+ .then(|stream| {\n+ // if we can't get to babel here we panic\n+ let stream = stream.expect(\"Can't reach Babel!\");\n+ start_connection(stream).and_then(|stream| {\n+ set_local_fee(stream, local_fee)\n+ .and_then(|stream| Ok(set_metric_factor(stream, metric_factor)))\n+ })\n+ })\n+ .wait()\n+ .expect(\"Unable to set babel fee or metric factor!\");\nOk(())\n}\n@@ -316,23 +308,19 @@ fn linux_exit_init(\nlet local_fee = config.get_payment().local_fee;\nlet metric_factor = config.get_network().metric_factor;\n- let stream = TcpStream::connect::<SocketAddr>(\n- format!(\"[::1]:{}\", config.get_network().babel_port).parse()?,\n- )?;\n-\n- let mut babel = Babel::new(stream);\n-\n- babel.start_connection()?;\n-\n- babel.set_local_fee(local_fee)?;\n- if local_fee == 0 {\n- warn!(\"THIS NODE IS GIVING BANDWIDTH AWAY FOR FREE. PLEASE SET local_fee TO A NON-ZERO VALUE TO DISABLE THIS WARNING.\");\n- }\n-\n- babel.set_metric_factor(metric_factor)?;\n- if metric_factor == 0 {\n- warn!(\"THIS NODE DOESN'T PAY ATTENTION TO ROUTE QUALITY - IT'LL CHOOSE THE CHEAPEST ROUTE EVEN IF IT'S THE WORST LINK AROUND. PLEASE SET metric_factor TO A NON-ZERO VALUE TO DISABLE THIS WARNING.\");\n- }\n+ // it's safe to use wait because CLU is run outside of the event loop\n+ // pre-startup, if we can't get to babel now we should just panic\n+ open_babel_stream(config.get_network().babel_port)\n+ .then(|stream| {\n+ // if we can't get to babel here we panic\n+ let stream = stream.expect(\"Can't reach Babel!\");\n+ start_connection(stream).and_then(|stream| {\n+ set_local_fee(stream, local_fee)\n+ .and_then(|stream| Ok(set_metric_factor(stream, metric_factor)))\n+ })\n+ })\n+ .wait()\n+ .expect(\"Unable to set babel fee or metric factor!\");\nOk(())\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Update clu to use async babel
20,244
30.05.2019 18:25:29
14,400
dd50d01fb35c9ea216ac61ec33552edf806d7d97
Move price setting into Rita Just not viable to do this async without an arbiter around
[ { "change_type": "MODIFY", "old_path": "clu/Cargo.toml", "new_path": "clu/Cargo.toml", "diff": "@@ -8,7 +8,6 @@ edition = \"2018\"\nsettings = { path = \"../settings\" }\nalthea_kernel_interface = { path = \"../althea_kernel_interface\" }\nalthea_types = { path = \"../althea_types\" }\n-babel_monitor = { path = \"../babel_monitor\" }\nlazy_static = \"1.3\"\nlog = \"0.4\"\nenv_logger = \"0.6\"\n@@ -20,4 +19,3 @@ serde = \"1.0\"\nserde_derive = \"1.0\"\nserde_json = \"1.0\"\nclarity = \"0.1\"\n-futures = \"0.1\"\n" }, { "change_type": "MODIFY", "old_path": "clu/src/lib.rs", "new_path": "clu/src/lib.rs", "diff": "@@ -8,15 +8,8 @@ extern crate failure;\nextern crate lazy_static;\nuse althea_kernel_interface::KI;\n-use babel_monitor::open_babel_stream;\n-use babel_monitor::run_command;\n-use babel_monitor::set_local_fee;\n-use babel_monitor::set_metric_factor;\n-use babel_monitor::start_connection;\nuse clarity::PrivateKey;\nuse failure::Error;\n-use futures::future::Future;\n-use futures::future::Join;\nuse ipgen;\nuse rand;\nuse rand::distributions::Alphanumeric;\n@@ -27,7 +20,7 @@ use settings::exit::RitaExitSettings;\nuse settings::RitaCommonSettings;\nuse std::fs::File;\nuse std::io::Read;\n-use std::net::{IpAddr, SocketAddr, TcpStream};\n+use std::net::IpAddr;\nuse std::path::Path;\nuse std::str;\nuse std::sync::{Arc, RwLock};\n@@ -189,35 +182,6 @@ fn linux_init(config: Arc<RwLock<settings::client::RitaSettingsStruct>>) -> Resu\n}\n}\n- // Yield the mut lock\n- drop(payment_settings);\n-\n- let local_fee = config.get_payment().local_fee;\n- let metric_factor = config.get_network().metric_factor;\n- if local_fee == 0 {\n- warn!(\"THIS NODE IS GIVING BANDWIDTH AWAY FOR FREE. PLEASE SET local_fee TO A NON-ZERO VALUE TO DISABLE THIS WARNING.\");\n- }\n- if metric_factor == 0 {\n- warn!(\"THIS NODE DOESN'T PAY ATTENTION TO ROUTE QUALITY - IT'LL CHOOSE THE CHEAPEST ROUTE EVEN IF IT'S THE WORST LINK AROUND. PLEASE SET metric_factor TO A NON-ZERO VALUE TO DISABLE THIS WARNING.\");\n- }\n- if metric_factor > 2000000 {\n- warn!(\"THIS NODE DOESN'T PAY ATTENTION TO ROUTE PRICE - IT'LL CHOOSE THE BEST ROUTE EVEN IF IT COSTS WAY TOO MUCH. PLEASE SET metric_factor TO A LOWER VALUE TO DISABLE THIS WARNING.\");\n- }\n-\n- // it's safe to use wait because CLU is run outside of the event loop\n- // pre-startup, if we can't get to babel now we should just panic\n- open_babel_stream(config.get_network().babel_port)\n- .then(|stream| {\n- // if we can't get to babel here we panic\n- let stream = stream.expect(\"Can't reach Babel!\");\n- start_connection(stream).and_then(|stream| {\n- set_local_fee(stream, local_fee)\n- .and_then(|stream| Ok(set_metric_factor(stream, metric_factor)))\n- })\n- })\n- .wait()\n- .expect(\"Unable to set babel fee or metric factor!\");\n-\nOk(())\n}\n@@ -302,26 +266,6 @@ fn linux_exit_init(\n}\n}\n- // Yield the mut lock\n- drop(payment_settings);\n-\n- let local_fee = config.get_payment().local_fee;\n- let metric_factor = config.get_network().metric_factor;\n-\n- // it's safe to use wait because CLU is run outside of the event loop\n- // pre-startup, if we can't get to babel now we should just panic\n- open_babel_stream(config.get_network().babel_port)\n- .then(|stream| {\n- // if we can't get to babel here we panic\n- let stream = stream.expect(\"Can't reach Babel!\");\n- start_connection(stream).and_then(|stream| {\n- set_local_fee(stream, local_fee)\n- .and_then(|stream| Ok(set_metric_factor(stream, metric_factor)))\n- })\n- })\n- .wait()\n- .expect(\"Unable to set babel fee or metric factor!\");\n-\nOk(())\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "new_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "diff": "@@ -5,9 +5,15 @@ use crate::rita_common::payment_validator::{PaymentValidator, Validate};\nuse crate::rita_common::tunnel_manager::{TriggerGC, TunnelManager};\nuse crate::SETTING;\nuse actix::{\n- Actor, ActorContext, Addr, AsyncContext, Context, Handler, Message, Supervised, SystemService,\n+ Actor, ActorContext, Addr, Arbiter, AsyncContext, Context, Handler, Message, Supervised,\n+ SystemService,\n};\n+use babel_monitor::open_babel_stream;\n+use babel_monitor::set_local_fee;\n+use babel_monitor::set_metric_factor;\n+use babel_monitor::start_connection;\nuse failure::Error;\n+use futures::future::Future;\nuse settings::RitaCommonSettings;\nuse std::time::Duration;\n@@ -81,6 +87,37 @@ impl Handler<Tick> for RitaSlowLoop {\nSETTING.get_network().tunnel_timeout_seconds,\n)));\n+ // we really only need to run this on startup, but doing so periodically\n+ // could catch the edge case where babel is restarted under us\n+ set_babel_price();\n+\nOk(())\n}\n}\n+\n+fn set_babel_price() {\n+ let babel_port = SETTING.get_network().babel_port;\n+ let local_fee = SETTING.get_payment().local_fee;\n+ let metric_factor = SETTING.get_network().metric_factor;\n+ Arbiter::spawn(\n+ open_babel_stream(babel_port)\n+ .then(move |stream| {\n+ println!(\"We opened the stream!\");\n+ // if we can't get to babel here we panic\n+ let stream = stream.expect(\"Can't reach Babel!\");\n+ start_connection(stream).and_then(move |stream| {\n+ println!(\"We started the connection!\");\n+ set_local_fee(stream, local_fee).and_then(move |stream| {\n+ println!(\" we set the local fee\");\n+ Ok(set_metric_factor(stream, metric_factor))\n+ })\n+ })\n+ })\n+ .then(|res| {\n+ if let Err(e) = res {\n+ error!(\"Failed to set babel price {:?}\", e);\n+ }\n+ Ok(())\n+ }),\n+ )\n+}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Move price setting into Rita Just not viable to do this async without an arbiter around
20,244
30.05.2019 18:25:58
14,400
1c57883e3fb5e01c9eb82a9ebe71f693caa08388
Remove prelude from dashboard imports
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/interfaces.rs", "new_path": "rita/src/rita_client/dashboard/interfaces.rs", "diff": "@@ -4,7 +4,7 @@ use crate::rita_common::peer_listener::UnListen;\nuse crate::ARGS;\nuse crate::KI;\nuse crate::SETTING;\n-use ::actix::prelude::{Arbiter, SystemService};\n+use ::actix::{Arbiter, SystemService};\nuse ::actix_web::{HttpRequest, HttpResponse, Json};\nuse failure::Error;\nuse futures::Future;\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Remove prelude from dashboard imports
20,244
31.05.2019 11:58:01
14,400
a790731e76e813d72e16c067f98c4ac53596a0a9
Fix opt level This keeps sneaking in
[ { "change_type": "MODIFY", "old_path": "Cargo.toml", "new_path": "Cargo.toml", "diff": "@@ -14,7 +14,7 @@ rita = { path = \"./rita\" }\nmembers = [\"althea_kernel_interface\", \"bounty_hunter\", \"settings\", \"clu\", \"exit_db\"]\n[profile.release]\n-opt-level = 2\n+opt-level = \"z\"\nlto = true\ncodegen-units = 1\nincremental = false\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Fix opt level This keeps sneaking in
20,244
31.05.2019 11:59:25
14,400
aef2c938237a04f1dbb90684187c3d2e7209b8fd
Add module comment to Babel Manager
[ { "change_type": "MODIFY", "old_path": "babel_monitor/src/lib.rs", "new_path": "babel_monitor/src/lib.rs", "diff": "+//! Babel monitor is an async futures based interface for the Babeld management interface\n+//! it provides abastractions over the major data this interface provides and an async\n+//! way to efficiently communicate with it.\n+\n#[macro_use]\nextern crate failure;\n#[macro_use]\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add module comment to Babel Manager
20,244
31.05.2019 12:02:25
14,400
4427a72198c5d58ce5b718251f1e554679ef5318
Add warnings for unhandled errors
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -189,7 +189,9 @@ impl Tunnel {\nmonitor(stream, &iface_name)\n})\n})\n- .then(|res| Ok(())),\n+ .then(|res| {\n+ error!(\"Monitoring tunnel {} has failed! The tunnels cache is an incorrect state {:?}\" , iface_name, res);\n+ Ok(())}),\n)\n}\n@@ -207,7 +209,9 @@ impl Tunnel {\nunmonitor(stream, &iface_name)\n})\n})\n- .then(|res| Ok(())),\n+ .then(|res| {\n+ error!(\"Unmonitoring tunnel {} has failed! Babel will now listen on a non-existant tunnel {:?}\", iface_name, res);\n+ Ok(())}),\n)\n}\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add warnings for unhandled errors
20,244
31.05.2019 13:29:26
14,400
f1933dca2c438339a53fc1b3c1b2c1e82adfff3a
Add warnings for listen failures
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_common/tunnel_manager/mod.rs", "new_path": "rita/src/rita_common/tunnel_manager/mod.rs", "diff": "@@ -184,13 +184,13 @@ impl Tunnel {\nopen_babel_stream(babel_port)\n.from_err()\n.and_then(move |stream| {\n- start_connection(stream).then(move |stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(move |stream| {\nmonitor(stream, &iface_name)\n})\n})\n- .then(|res| {\n- error!(\"Monitoring tunnel {} has failed! The tunnels cache is an incorrect state {:?}\" , iface_name, res);\n+ .then(move |res| {\n+ // if you ever see this error go and make a handler to delete the tunnel from memory\n+ error!(\"Monitoring tunnel has failed! The tunnels cache is an incorrect state {:?}\" , res);\nOk(())}),\n)\n}\n@@ -204,13 +204,13 @@ impl Tunnel {\nopen_babel_stream(babel_port)\n.from_err()\n.and_then(move |stream| {\n- start_connection(stream).then(move |stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(move |stream| {\nunmonitor(stream, &iface_name)\n})\n})\n- .then(|res| {\n- error!(\"Unmonitoring tunnel {} has failed! Babel will now listen on a non-existant tunnel {:?}\", iface_name, res);\n+ .then(move |res| {\n+ // if you ever see this error go and make a handler to try and unlisten until it works\n+ error!(\"Unmonitoring tunnel has failed! Babel will now listen on a non-existant tunnel {:?}\", res);\nOk(())}),\n)\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add warnings for listen failures
20,244
31.05.2019 13:29:34
14,400
fd813663befbaf800116744d2f175f2feff1222d
Clean up neighbors endpoint
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/neighbors.rs", "new_path": "rita/src/rita_client/dashboard/neighbors.rs", "diff": "-use crate::rita_common::dashboard::Dashboard;\nuse crate::rita_common::debt_keeper::{DebtKeeper, Dump, NodeDebtData};\nuse crate::rita_common::tunnel_manager::{GetNeighbors, Neighbor, TunnelManager};\nuse crate::SETTING;\n-use ::actix::{Handler, Message, ResponseFuture, SystemService};\n+use ::actix::SystemService;\nuse ::actix_web::AsyncResponder;\nuse ::actix_web::{HttpRequest, Json};\nuse althea_types::Identity;\n@@ -11,12 +10,12 @@ use babel_monitor::get_route_via_neigh;\nuse babel_monitor::open_babel_stream;\nuse babel_monitor::parse_routes;\nuse babel_monitor::start_connection;\n+use babel_monitor::Route;\nuse failure::Error;\nuse futures::Future;\nuse num256::{Int256, Uint256};\nuse settings::client::RitaClientSettings;\nuse settings::RitaCommonSettings;\n-use std::boxed::Box;\nuse std::collections::HashMap;\n#[derive(Serialize)]\n@@ -30,21 +29,14 @@ pub struct NodeInfo {\npub price_to_exit: u32,\n}\n-pub struct GetNeighborInfo;\n-\n-impl Message for GetNeighborInfo {\n- type Result = Result<Vec<NodeInfo>, Error>;\n-}\n-\n/// Gets info about neighbors, including interested data about what their route\n/// price is to the exit and how much we may owe them. The debt data is now legacy\n/// since the /debts endpoint was introduced, and should be removed when it can be\n/// coordinated with the frontend.\n/// The routes info might also belong in /exits or a dedicated /routes endpoint\n-impl Handler<GetNeighborInfo> for Dashboard {\n- type Result = ResponseFuture<Vec<NodeInfo>, Error>;\n-\n- fn handle(&mut self, _msg: GetNeighborInfo, _ctx: &mut Self::Context) -> Self::Result {\n+pub fn get_neighbor_info(\n+ _req: HttpRequest,\n+) -> Box<Future<Item = Json<Vec<NodeInfo>>, Error = Error>> {\nBox::new(\nDebtKeeper::from_registry()\n.send(Dump {})\n@@ -67,9 +59,26 @@ impl Handler<GetNeighborInfo> for Dashboard {\n.and_then(move |stream| {\nstart_connection(stream).then(move |stream| {\nlet stream = stream.expect(\"Unexpected babel version!\");\n- parse_routes(stream).and_then(move |routes| {\n+ parse_routes(stream)\n+ .and_then(move |routes| {\nlet route_table_sample = routes.1;\n+ let output =\n+ generate_neighbors_list(route_table_sample, debts);\n+ Ok(Json(output))\n+ })\n+ .responder()\n+ })\n+ })\n+ })\n+ }),\n+ )\n+}\n+/// generates a list of neighbors coorelated with the quality of the route to the exit they provide\n+fn generate_neighbors_list(\n+ route_table_sample: Vec<Route>,\n+ debts: HashMap<Identity, NodeDebtData>,\n+) -> Vec<NodeInfo> {\nlet mut output = Vec::new();\nlet exit_client = SETTING.get_exit_client();\n@@ -78,28 +87,18 @@ impl Handler<GetNeighborInfo> for Dashboard {\nfor (identity, debt_info) in debts.iter() {\nlet nickname = match identity.nickname {\nSome(val) => val,\n- None => {\n- ArrayString::<[u8; 32]>::from(\"No Nickname\")\n- .unwrap()\n- }\n+ None => ArrayString::<[u8; 32]>::from(\"No Nickname\").unwrap(),\n};\nif current_exit.is_some() {\nlet exit_ip = current_exit.unwrap().id.mesh_ip;\n- let maybe_route = get_route_via_neigh(\n- identity.mesh_ip,\n- exit_ip,\n- &route_table_sample,\n- );\n+ let maybe_route = get_route_via_neigh(identity.mesh_ip, exit_ip, &route_table_sample);\n// We have a peer that is an exit, so we can't find a route\n// from them to our selected exit. Other errors can also get\n// caught here\nif maybe_route.is_err() {\n- output.push(nonviable_node_info(\n- nickname,\n- identity.mesh_ip.to_string(),\n- ));\n+ output.push(nonviable_node_info(nickname, identity.mesh_ip.to_string()));\ncontinue;\n}\n// we check that this is safe above\n@@ -107,14 +106,9 @@ impl Handler<GetNeighborInfo> for Dashboard {\noutput.push(NodeInfo {\nnickname: nickname.to_string(),\n- ip: serde_json::to_string(\n- &identity.mesh_ip,\n- )\n- .unwrap(),\n+ ip: serde_json::to_string(&identity.mesh_ip).unwrap(),\nroute_metric_to_exit: route.metric,\n- total_payments: debt_info\n- .total_payment_received\n- .clone(),\n+ total_payments: debt_info.total_payment_received.clone(),\ndebt: debt_info.debt.clone(),\nlink_cost: route.refmetric,\nprice_to_exit: route.price,\n@@ -122,40 +116,16 @@ impl Handler<GetNeighborInfo> for Dashboard {\n} else {\noutput.push(NodeInfo {\nnickname: nickname.to_string(),\n- ip: serde_json::to_string(\n- &identity.mesh_ip,\n- )\n- .unwrap(),\n+ ip: serde_json::to_string(&identity.mesh_ip).unwrap(),\nroute_metric_to_exit: u16::max_value(),\n- total_payments: debt_info\n- .total_payment_received\n- .clone(),\n+ total_payments: debt_info.total_payment_received.clone(),\ndebt: debt_info.debt.clone(),\nlink_cost: u16::max_value(),\nprice_to_exit: u32::max_value(),\n})\n}\n}\n-\n- Ok(output)\n- })\n- })\n- })\n- })\n- }),\n- )\n- }\n-}\n-\n-pub fn get_neighbor_info(\n- _req: HttpRequest,\n-) -> Box<dyn Future<Item = Json<Vec<NodeInfo>>, Error = Error>> {\n- debug!(\"Neighbors endpoint hit!\");\n- Dashboard::from_registry()\n- .send(GetNeighborInfo {})\n- .from_err()\n- .and_then(move |reply| Ok(Json(reply?)))\n- .responder()\n+ output\n}\n/// Takes a list of neighbors and debts, if an entry\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Clean up neighbors endpoint
20,244
31.05.2019 17:50:12
14,400
73ba25098eb5971fdbaae19bce9b4dea4bb4b1a1
Add slowdown to integraton test
[ { "change_type": "MODIFY", "old_path": "integration-tests/rita.py", "new_path": "integration-tests/rita.py", "diff": "@@ -945,6 +945,7 @@ def main():\n(time.time() - start_time, CONVERGENCE_DELAY, interval))\nprint(\"Test reachabibility and optimum routes...\")\n+ time.sleep(120)\nduration = time.time() - start_time\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add slowdown to integraton test
20,244
01.06.2019 09:25:20
14,400
e32778046ab232ea6245028069570b74315c3731
Don't panic during babel connection issues It's unwise to panic of babel is mometarily unavailable. My main concern here is that we don't check that babel is running properly on startup, which violates the 'fail fast' mantra you want on system startup.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/exits.rs", "new_path": "rita/src/rita_client/dashboard/exits.rs", "diff": "@@ -74,8 +74,7 @@ impl Handler<GetExitInfo> for Dashboard {\nopen_babel_stream(babel_port)\n.from_err()\n.and_then(move |stream| {\n- start_connection(stream).then(move |stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(move |stream| {\nparse_routes(stream).and_then(move |routes| {\nlet route_table_sample = routes.1;\nlet mut output = Vec::new();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/neighbors.rs", "new_path": "rita/src/rita_client/dashboard/neighbors.rs", "diff": "@@ -57,8 +57,7 @@ pub fn get_neighbor_info(\nopen_babel_stream(babel_port)\n.from_err()\n.and_then(move |stream| {\n- start_connection(stream).then(move |stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(move |stream| {\nparse_routes(stream)\n.and_then(move |routes| {\nlet route_table_sample = routes.1;\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/exit_manager/mod.rs", "new_path": "rita/src/rita_client/exit_manager/mod.rs", "diff": "@@ -411,8 +411,7 @@ impl Handler<Tick> for ExitManager {\nopen_babel_stream(babel_port)\n.from_err()\n.and_then(move |stream| {\n- start_connection(stream).then(move |stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(move |stream| {\nparse_routes(stream).and_then(move |routes| {\nTrafficWatcher::from_registry().do_send(Watch {\nexit_id,\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/fast_loop.rs", "new_path": "rita/src/rita_common/rita_loop/fast_loop.rs", "diff": "@@ -102,8 +102,7 @@ impl Handler<Tick> for RitaFastLoop {\nopen_babel_stream(babel_port)\n.from_err()\n.and_then(move |stream| {\n- start_connection(stream).then(move |stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(move |stream| {\nparse_routes(stream).and_then(move |routes| {\nTrafficWatcher::from_registry()\n.send(Watch::new(neighbors, routes.1))\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "new_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "diff": "@@ -101,10 +101,9 @@ fn set_babel_price() {\nlet metric_factor = SETTING.get_network().metric_factor;\nArbiter::spawn(\nopen_babel_stream(babel_port)\n- .then(move |stream| {\n+ .from_err()\n+ .and_then(move |stream| {\nprintln!(\"We opened the stream!\");\n- // if we can't get to babel here we panic\n- let stream = stream.expect(\"Can't reach Babel!\");\nstart_connection(stream).and_then(move |stream| {\nprintln!(\"We started the connection!\");\nset_local_fee(stream, local_fee).and_then(move |stream| {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/geoip.rs", "new_path": "rita/src/rita_exit/database/geoip.rs", "diff": "@@ -20,8 +20,7 @@ pub fn get_gateway_ip_single(mesh_ip: IpAddr) -> Box<Future<Item = IpAddr, Error\nopen_babel_stream(babel_port)\n.from_err()\n.and_then(move |stream| {\n- start_connection(stream).then(move |stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(move |stream| {\nparse_routes(stream).and_then(move |routes| {\nlet mut route_to_des = None;\nfor route in routes.1.iter() {\n@@ -61,8 +60,7 @@ pub fn get_gateway_ip_bulk(\nlet babel_port = SETTING.get_network().babel_port;\nBox::new(open_babel_stream(babel_port).from_err().and_then(|stream| {\n- start_connection(stream).then(|stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(|stream| {\nparse_routes(stream).and_then(|routes| {\nlet mut remote_ip_cache: HashMap<String, IpAddr> = HashMap::new();\nlet mut results = Vec::new();\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "@@ -142,8 +142,7 @@ impl Handler<Tick> for RitaSyncLoop {\nopen_babel_stream(babel_port)\n.from_err()\n.and_then(|stream| {\n- start_connection(stream).then(|stream| {\n- let stream = stream.expect(\"Unexpected babel version!\");\n+ start_connection(stream).and_then(|stream| {\nparse_routes(stream).and_then(|routes| {\nTrafficWatcher::from_registry().do_send(Watch {\nusers: ids,\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Don't panic during babel connection issues It's unwise to panic of babel is mometarily unavailable. My main concern here is that we don't check that babel is running properly on startup, which violates the 'fail fast' mantra you want on system startup.
20,244
01.06.2019 18:15:08
14,400
f89f3945104639560499530bfbe1d381d1684fd6
Add timeouts to all regularly spawned Babel operations Some babel operations, like a tunnel listen or unlisten we want to wait around forever if at all possible. Others like the regularly spawned listen operations can and should fail quickly.
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_client/exit_manager/mod.rs", "new_path": "rita/src/rita_client/exit_manager/mod.rs", "diff": "@@ -45,6 +45,7 @@ use std::time::Duration;\nuse syslog::Error as LogError;\nuse syslog::{init_udp, Facility};\nuse tokio::net::TcpStream as TokioTcpStream;\n+use tokio::util::FutureExt;\n/// enables remote logging if the user has configured it\nfn enable_remote_logging(server_internal_ip: IpAddr) -> Result<(), LogError> {\n@@ -422,7 +423,7 @@ impl Handler<Tick> for ExitManager {\n})\n})\n})\n- .then(|ret| {\n+ .timeout(Duration::from_secs(4)).then(|ret| {\nif let Err(e) = ret {\nerror!(\"Failed to watch client traffic with {:?}\", e)\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "new_path": "rita/src/rita_common/rita_loop/slow_loop.rs", "diff": "@@ -16,9 +16,11 @@ use failure::Error;\nuse futures::future::Future;\nuse settings::RitaCommonSettings;\nuse std::time::Duration;\n+use tokio::util::FutureExt;\n// the speed in seconds for the common loop\npub const SLOW_LOOP_SPEED: u64 = 60;\n+pub const SLOW_LOOP_TIMEOUT: Duration = Duration::from_secs(15);\npub struct RitaSlowLoop;\n@@ -112,6 +114,7 @@ fn set_babel_price() {\n})\n})\n})\n+ .timeout(SLOW_LOOP_TIMEOUT)\n.then(|res| {\nif let Err(e) = res {\nerror!(\"Failed to set babel price {:?}\", e);\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "@@ -48,6 +48,9 @@ use std::collections::HashMap;\nuse std::collections::HashSet;\nuse std::net::IpAddr;\nuse std::time::Duration;\n+use tokio::util::FutureExt;\n+\n+pub const EXIT_LOOP_TIMEOUT: Duration = Duration::from_secs(15);\n#[derive(Default)]\npub struct RitaLoop {}\n@@ -152,6 +155,7 @@ impl Handler<Tick> for RitaSyncLoop {\n})\n})\n})\n+ .timeout(EXIT_LOOP_TIMEOUT)\n.then(|ret| {\nif let Err(e) = ret {\nerror!(\"Failed to watch Exit traffic with {:?}\", e)\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Add timeouts to all regularly spawned Babel operations Some babel operations, like a tunnel listen or unlisten we want to wait around forever if at all possible. Others like the regularly spawned listen operations can and should fail quickly.
20,244
04.06.2019 09:38:46
14,400
02cc948060c8d1a2ccdb3a16954528aa1e0977f9
Refactor exit signup flow to avoid .wait() Exit signup and parts of the exit loop are now async to accomodate async babel
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -65,7 +65,7 @@ dependencies = [\n[[package]]\nname = \"actix-web\"\n-version = \"0.7.18\"\n+version = \"0.7.19\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -111,7 +111,7 @@ dependencies = [\n\"tokio-tcp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"tokio-timer 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"v_htmlescape 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"v_htmlescape 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n@@ -326,7 +326,7 @@ name = \"bounty_hunter\"\nversion = \"0.1.0\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"actix-web 0.7.19 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"clarity 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"diesel 1.4.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -1919,7 +1919,7 @@ name = \"rita\"\nversion = \"0.4.7\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"actix-web 0.7.19 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"actix_derive 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"althea_kernel_interface 0.1.0\",\n\"althea_types 0.1.0\",\n@@ -2710,16 +2710,16 @@ dependencies = [\n[[package]]\nname = \"v_escape\"\n-version = \"0.3.2\"\n+version = \"0.7.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\ndependencies = [\n- \"v_escape_derive 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"v_escape_derive 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n[[package]]\nname = \"v_escape_derive\"\n-version = \"0.2.1\"\n+version = \"0.5.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\ndependencies = [\n\"nom 4.2.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -2730,12 +2730,11 @@ dependencies = [\n[[package]]\nname = \"v_htmlescape\"\n-version = \"0.3.2\"\n+version = \"0.4.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\ndependencies = [\n\"cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"v_escape 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"v_escape 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n[[package]]\n@@ -2774,7 +2773,7 @@ version = \"0.4.3\"\nsource = \"git+https://github.com/althea-mesh/web30?rev=56b0068aa43eb563db996418eb96f3ade85ef73b#56b0068aa43eb563db996418eb96f3ade85ef73b\"\ndependencies = [\n\"actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\",\n+ \"actix-web 0.7.19 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"assert-json-diff 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"clarity 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -2877,7 +2876,7 @@ dependencies = [\n\"checksum MacTypes-sys 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"eaf9f0d0b1cc33a4d2aee14fb4b2eac03462ef4db29c8ac4057327d8a71ad86f\"\n\"checksum actix 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)\" = \"6c616db5fa4b0c40702fb75201c2af7f8aa8f3a2e2c1dda3b0655772aa949666\"\n\"checksum actix-net 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"8bebfbe6629e0131730746718c9e032b58f02c6ce06ed7c982b9fef6c8545acd\"\n-\"checksum actix-web 0.7.18 (registry+https://github.com/rust-lang/crates.io-index)\" = \"e9f33c941e5e69a58a6bfef33853228042ed3799fc4b5a4923a36a85776fb690\"\n+\"checksum actix-web 0.7.19 (registry+https://github.com/rust-lang/crates.io-index)\" = \"b0ac60f86c65a50b140139f499f4f7c6e49e4b5d88fbfba08e4e3975991f7bf4\"\n\"checksum actix_derive 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"4300e9431455322ae393d43a2ba1ef96b8080573c0fc23b196219efedfb6ba69\"\n\"checksum actix_derive 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"0bf5f6d7bf2d220ae8b4a7ae02a572bb35b7c4806b24049af905ab8110de156c\"\n\"checksum adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7e522997b529f05601e05166c07ed17789691f562762c7f3b987263d2dedee5c\"\n@@ -3147,9 +3146,9 @@ dependencies = [\n\"checksum url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a\"\n\"checksum utf8-ranges 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"796f7e48bef87609f7ade7e06495a87d5cd06c7866e6a5cbfceffc558a243737\"\n\"checksum uuid 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"0238db0c5b605dd1cf51de0f21766f97fba2645897024461d6a00c036819a768\"\n-\"checksum v_escape 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"c8b50688edb86f4c092a1a9fe8bda004b0faa3197100897653809e97e09a2814\"\n-\"checksum v_escape_derive 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7cd994c63b487fef7aad31e5394ec04b9e24de7b32ea5251c9fb499cd2cbf44c\"\n-\"checksum v_htmlescape 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"020cae817dc82693aa523f01087b291b1c7a9ac8cea5c12297963f21769fb27f\"\n+\"checksum v_escape 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"8865501b78eef9193c1b45486acf18ba889e5662eba98854d6fc59d8ecf3542d\"\n+\"checksum v_escape_derive 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"306896ff4b75998501263a1dc000456de442e21d68fe8c8bdf75c66a33a58e23\"\n+\"checksum v_htmlescape 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7fbbe0fa88dd36f9c8cf61a218d4b953ba669de4d0785832f33cc72bd081e1be\"\n\"checksum vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"def296d3eb3b12371b2c7d0e83bfe1403e4db2d7a0bba324a12b21c4ee13143d\"\n\"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd\"\n\"checksum walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)\" = \"9d9d7ed3431229a144296213105a390676cc49c9b6a72bd19f3176c98e129fa1\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/exit.rs", "new_path": "rita/src/exit.rs", "diff": "@@ -38,6 +38,8 @@ use settings::FileWrite;\nuse actix_web::http::Method;\nuse actix_web::{http, server, App};\n+use std::collections::HashMap;\n+use std::net::IpAddr;\nmod middleware;\nmod rita_common;\n@@ -121,6 +123,11 @@ lazy_static! {\n.unwrap_or_else(|e| e.exit());\n}\n+lazy_static! {\n+ pub static ref GEOIP_CACHE: Arc<RwLock<HashMap<IpAddr, String>>> =\n+ Arc::new(RwLock::new(HashMap::new()));\n+}\n+\n#[cfg(not(test))]\nlazy_static! {\npub static ref SETTING: Arc<RwLock<RitaExitSettingsStruct>> = {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/exit_manager/mod.rs", "new_path": "rita/src/rita_client/exit_manager/mod.rs", "diff": "@@ -423,7 +423,8 @@ impl Handler<Tick> for ExitManager {\n})\n})\n})\n- .timeout(Duration::from_secs(4)).then(|ret| {\n+ .timeout(Duration::from_secs(4))\n+ .then(|ret| {\nif let Err(e) = ret {\nerror!(\"Failed to watch client traffic with {:?}\", e)\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/geoip.rs", "new_path": "rita/src/rita_exit/database/geoip.rs", "diff": "+use crate::GEOIP_CACHE;\nuse crate::KI;\nuse crate::SETTING;\n+use actix_web::client as actix_client;\n+use actix_web::HttpMessage;\nuse babel_monitor::open_babel_stream;\nuse babel_monitor::parse_routes;\nuse babel_monitor::start_connection;\nuse failure::Error;\n+use future::Either;\n+use futures::future;\nuse futures::future::Future;\nuse ipnetwork::IpNetwork;\n-use reqwest;\nuse settings::exit::RitaExitSettings;\nuse settings::RitaCommonSettings;\nuse std::collections::HashMap;\n@@ -114,9 +118,9 @@ struct CountryDetails {\n}\n/// get ISO country code from ip, consults a in memory cache\n-pub fn get_country(ip: &IpAddr, cache: &mut HashMap<IpAddr, String>) -> Result<String, Error> {\n+pub fn get_country(ip: IpAddr) -> impl Future<Item = String, Error = Error> {\n+ // a function local cache for results, reset during every restart\ntrace!(\"get GeoIP country for {}\", ip.to_string());\n- let client = reqwest::Client::new();\nlet api_user = SETTING\n.get_exit_network()\n.geoip_api_user\n@@ -128,8 +132,8 @@ pub fn get_country(ip: &IpAddr, cache: &mut HashMap<IpAddr, String>) -> Result<S\n.clone()\n.expect(\"No api key configured!\");\n- match cache.get(ip) {\n- Some(code) => Ok(code.clone()),\n+ match GEOIP_CACHE.read().unwrap().get(&ip) {\n+ Some(code) => Either::A(future::ok(code.clone())),\nNone => {\nlet geo_ip_url = format!(\"https://geoip.maxmind.com/geoip/v2.1/country/{}\", ip);\ninfo!(\n@@ -137,40 +141,33 @@ pub fn get_country(ip: &IpAddr, cache: &mut HashMap<IpAddr, String>) -> Result<S\ngeo_ip_url,\nip.to_string()\n);\n-\n- let res: GeoIPRet = match client\n- .get(&geo_ip_url)\n+ Either::B(\n+ actix_client::get(&geo_ip_url)\n.basic_auth(api_user, Some(api_key))\n+ .finish()\n+ .unwrap()\n.send()\n- {\n- Ok(mut r) => match r.json() {\n- Ok(v) => v,\n- Err(e) => {\n- warn!(\"Failed to Jsonize GeoIP response {:?}\", e);\n- bail!(\"Failed to jsonize GeoIP response {:?}\", e)\n- }\n- },\n- Err(e) => {\n- warn!(\"Get request for GeoIP failed! {:?}\", e);\n- bail!(\"Get request for GeoIP failed {:?}\", e)\n- }\n- };\n- info!(\"Got {:?} from GeoIP request\", res);\n- cache.insert(*ip, res.country.iso_code.clone());\n-\n- Ok(res.country.iso_code)\n+ .from_err()\n+ .and_then(move |response| {\n+ response.json().from_err().and_then(move |result| {\n+ let value: GeoIPRet = result;\n+ let code = value.country.iso_code;\n+ GEOIP_CACHE.write().unwrap().insert(ip, code.clone());\n+ Ok(code)\n+ })\n+ }),\n+ )\n}\n}\n}\n/// Returns true or false if an ip is confirmed to be inside or outside the region and error\n/// if an api error is encountered trying to figure that out.\n-pub fn verify_ip(request_ip: &IpAddr, cache: &mut HashMap<IpAddr, String>) -> Result<bool, Error> {\n+pub fn verify_ip(request_ip: IpAddr) -> impl Future<Item = bool, Error = Error> {\nif SETTING.get_allowed_countries().is_empty() {\n- Ok(true)\n+ Either::A(future::ok(true))\n} else {\n- let country = get_country(request_ip, cache)?;\n-\n+ Either::B(get_country(request_ip).and_then(|country| {\nif !SETTING.get_allowed_countries().is_empty()\n&& !SETTING.get_allowed_countries().contains(&country)\n{\n@@ -178,11 +175,12 @@ pub fn verify_ip(request_ip: &IpAddr, cache: &mut HashMap<IpAddr, String>) -> Re\n}\nOk(true)\n+ }))\n}\n}\n#[test]\n#[ignore]\nfn test_get_country() {\n- get_country(&\"8.8.8.8\".parse().unwrap(), &mut HashMap::new()).unwrap();\n+ get_country(\"8.8.8.8\".parse().unwrap()).wait().unwrap();\n}\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -28,13 +28,14 @@ use crate::rita_exit::database::struct_tools::to_identity;\nuse crate::rita_exit::database::struct_tools::verif_done;\nuse crate::KI;\nuse crate::SETTING;\n-use ::actix::prelude::SystemService;\n+use ::actix::SystemService;\nuse althea_kernel_interface::ExitClient;\nuse althea_types::{ExitClientDetails, ExitClientIdentity, ExitDetails, ExitState, ExitVerifMode};\nuse diesel;\nuse diesel::prelude::{Connection, ConnectionError, PgConnection, RunQueryDsl};\nuse exit_db::{models, schema};\nuse failure::Error;\n+use futures::future::join_all;\nuse futures::Future;\nuse ipnetwork::IpNetwork;\nuse rand;\n@@ -128,57 +129,56 @@ fn client_to_new_db_client(\n}\n}\n-/// Handles a new client registration api call. Performs a geoip lookup\n-/// on their registration ip to make sure that they are coming from a valid gateway\n-/// ip and then sends out an email of phone message\n-pub fn signup_client(client: ExitClientIdentity) -> Result<ExitState, Error> {\n+fn create_or_update_user_record(\n+ conn: &PgConnection,\n+ client: &ExitClientIdentity,\n+ user_country: String,\n+) -> Result<models::Client, Error> {\nuse self::schema::clients::dsl::clients;\n- let mut tmp_cache = HashMap::new();\n- let conn = get_database_connection()?;\nlet client_mesh_ip = client.global.mesh_ip;\n- // this blocks but it's being run in a threadpool anyways\n- let gateway_ip = get_gateway_ip_single(client_mesh_ip).wait()?;\n-\n- trace!(\"got setup request {:?}\", client);\n-\n- // either update and grab an existing entry or create one\n- let their_record = if client_exists(&client_mesh_ip, &conn)? {\n- update_client(&client, &conn)?;\n- get_client(client_mesh_ip, &conn)?\n+ if client_exists(&client_mesh_ip, conn)? {\n+ update_client(&client, conn)?;\n+ Ok(get_client(client_mesh_ip, conn)?)\n} else {\ninfo!(\n\"record for {} does not exist, creating\",\nclient.global.wg_public_key\n);\n- let new_ip = get_next_client_ip(&conn)?;\n-\n- trace!(\"About to check country\");\n- let user_country = if SETTING.get_allowed_countries().is_empty() {\n- String::new()\n- } else {\n- get_country(&gateway_ip, &mut tmp_cache)?\n- };\n+ let new_ip = get_next_client_ip(conn)?;\nlet c = client_to_new_db_client(&client, new_ip, user_country);\ninfo!(\"Inserting new client {}\", client.global.wg_public_key);\n- diesel::insert_into(clients).values(&c).execute(&conn)?;\n-\n- c\n- };\n+ diesel::insert_into(clients).values(&c).execute(conn)?;\n- match (\n- verify_ip(&gateway_ip, &mut tmp_cache),\n- SETTING.get_verif_settings(),\n- ) {\n- (Ok(true), Some(ExitVerifSettings::Email(mailer))) => {\n- handle_email_registration(&client, &their_record, &conn, mailer.email_cooldown as i64)\n+ Ok(c)\n+ }\n}\n- (Ok(true), Some(ExitVerifSettings::Phone(phone))) => {\n+\n+/// Handles a new client registration api call. Performs a geoip lookup\n+/// on their registration ip to make sure that they are coming from a valid gateway\n+/// ip and then sends out an email of phone message\n+pub fn signup_client(client: ExitClientIdentity) -> impl Future<Item = ExitState, Error = Error> {\n+ trace!(\"got setup request {:?}\", client);\n+ get_gateway_ip_single(client.global.mesh_ip).and_then(move |gateway_ip| {\n+ verify_ip(gateway_ip).and_then(move |verify_status| {\n+ get_country(gateway_ip).and_then(move |user_country| {\n+ let conn = get_database_connection()?;\n+ let their_record = create_or_update_user_record(&conn, &client, user_country)?;\n+\n+ // either update and grab an existing entry or create one\n+ match (verify_status, SETTING.get_verif_settings()) {\n+ (true, Some(ExitVerifSettings::Email(mailer))) => handle_email_registration(\n+ &client,\n+ &their_record,\n+ &conn,\n+ mailer.email_cooldown as i64,\n+ ),\n+ (true, Some(ExitVerifSettings::Phone(phone))) => {\nhandle_sms_registration(&client, &their_record, phone.auth_api_key, &conn)\n}\n- (Ok(true), None) => {\n+ (true, None) => {\nverify_client(&client, true, &conn)?;\nOk(ExitState::Registered {\nour_details: ExitClientDetails {\n@@ -188,16 +188,16 @@ pub fn signup_client(client: ExitClientIdentity) -> Result<ExitState, Error> {\nmessage: \"Registration OK\".to_string(),\n})\n}\n- (Ok(false), _) => Ok(ExitState::Denied {\n+ (false, _) => Ok(ExitState::Denied {\nmessage: format!(\n\"This exit only accepts connections from {}\",\ndisplay_hashset(&SETTING.get_allowed_countries()),\n),\n}),\n- (Err(_e), _) => Ok(ExitState::Denied {\n- message: \"There was a problem signing up, please try again\".to_string(),\n- }),\n}\n+ })\n+ })\n+ })\n}\n/// Gets the status of a client and updates it in the database\n@@ -316,10 +316,9 @@ fn low_balance_notification(\n/// we also do this in the client status requests but we want to handle the edge case of a modified\n/// client that doesn't make status requests\npub fn validate_clients_region(\n- mut geoip_cache: &mut HashMap<IpAddr, String>,\n- clients_list: &[exit_db::models::Client],\n- conn: &PgConnection,\n-) -> Result<(), Error> {\n+ clients_list: Vec<exit_db::models::Client>,\n+ conn: PgConnection,\n+) -> impl Future<Item = (), Error = ()> {\ninfo!(\"Starting exit region validation\");\nlet start = Instant::now();\n@@ -335,37 +334,41 @@ pub fn validate_clients_region(\nErr(_e) => error!(\"Database entry with invalid mesh ip! {:?}\", item),\n}\n}\n-\n- let mesh_to_gateway_ip_list = get_gateway_ip_bulk(ip_vec).wait();\n-\n- match mesh_to_gateway_ip_list {\n- Ok(list) => {\n- for item in list {\n- match verify_ip(&item.gateway_ip, &mut geoip_cache) {\n- Ok(true) => trace!(\"{:?} is from an allowed ip\", item),\n- Ok(false) => {\n+ get_gateway_ip_bulk(ip_vec)\n+ .and_then(move |list| {\n+ let mut fut_vec = Vec::new();\n+ for item in list.iter() {\n+ fut_vec.push(verify_ip(item.gateway_ip));\n+ }\n+ join_all(fut_vec).and_then(move |client_verifications| {\n+ for (n, res) in client_verifications.iter().enumerate() {\n+ match res {\n+ true => trace!(\"{:?} is from an allowed ip\", list[n]),\n+ false => {\n// get_gateway_ip_bulk can't add new entires to the list\n// therefore client_map is strictly a superset of ip_bulk results\n- let client_to_deauth = &client_map[&item.mesh_ip];\n- if verify_db_client(client_to_deauth, false, conn).is_err() {\n+ let client_to_deauth = &client_map[&list[n].mesh_ip];\n+ if verify_db_client(client_to_deauth, false, &conn).is_err() {\nerror!(\"Failed to deauth client {:?}\", client_to_deauth);\n}\n}\n- Err(e) => error!(\"Failed to GeoIP {:?} to check region\", e),\n}\n}\n+\ninfo!(\n\"Exit region validation completed in {}s {}ms\",\nstart.elapsed().as_secs(),\nstart.elapsed().subsec_millis(),\n);\nOk(())\n+ })\n+ })\n+ .then(|output| {\n+ if output.is_err() {\n+ error!(\"Validate clients region failed with {:?}\", output);\n}\n- Err(e) => {\n- error!(\"Problem getting gateway ip's for clients! {:?}\", e);\n- bail!(\"Problem getting gateway ips for clients! {:?}\", e)\n- }\n- }\n+ Ok(())\n+ })\n}\n/// Iterates over the the database of clients, if a client's last_seen value\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/network_endpoints/mod.rs", "new_path": "rita/src/rita_exit/network_endpoints/mod.rs", "diff": "@@ -17,6 +17,7 @@ use actix_web::AsyncResponder;\nuse althea_types::Identity;\nuse althea_types::{ExitClientIdentity, ExitState, RTTimestamps};\nuse failure::Error;\n+use futures::future;\nuse futures::Future;\nuse num256::Int256;\nuse std::net::SocketAddr;\n@@ -24,7 +25,7 @@ use std::time::SystemTime;\npub fn setup_request(\ntheir_id: (Json<ExitClientIdentity>, HttpRequest),\n-) -> Result<Json<ExitState>, Error> {\n+) -> Box<Future<Item = Json<ExitState>, Error = Error>> {\ninfo!(\n\"Received setup request from, {}\",\ntheir_id.0.global.wg_public_key\n@@ -41,12 +42,20 @@ pub fn setup_request(\nlet remote_mesh_ip = remote_mesh_socket.ip();\nif remote_mesh_ip == client_mesh_ip {\n- Ok(Json(signup_client(client)?))\n- } else {\n+ Box::new(signup_client(client).then(|result| match result {\n+ Ok(exit_state) => Ok(Json(exit_state)),\n+ Err(e) => {\n+ error!(\"Signup client failed with {:?}\", e);\nOk(Json(ExitState::Denied {\n- message: \"The request ip does not match the signup ip\".to_string(),\n+ message: \"There was an internal server error!\".to_string(),\n}))\n}\n+ }))\n+ } else {\n+ Box::new(future::ok(Json(ExitState::Denied {\n+ message: \"The request ip does not match the signup ip\".to_string(),\n+ })))\n+ }\n}\npub fn status_request(their_id: Json<ExitClientIdentity>) -> Result<Json<ExitState>, Error> {\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/rita_loop/mod.rs", "new_path": "rita/src/rita_exit/rita_loop/mod.rs", "diff": "@@ -179,10 +179,7 @@ impl Handler<Tick> for RitaSyncLoop {\n// Make sure no one we are setting up is geoip unauthorized\nif !SETTING.get_allowed_countries().is_empty() {\n- let res = validate_clients_region(&mut self.geoip_cache, &clients_list, &conn);\n- if res.is_err() {\n- error!(\"Validate clients failed with {:?}\", res);\n- }\n+ Arbiter::spawn(validate_clients_region(clients_list.clone(), conn));\n}\n// handle enforcement on client tunnels by querying debt keeper\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Refactor exit signup flow to avoid .wait() Exit signup and parts of the exit loop are now async to accomodate async babel
20,244
04.06.2019 13:19:49
14,400
33d73a57c535bb14d7855f8c858ab1567a48b043
Async SMS sending This leaves only postgres as the remaining sync component
[ { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/email.rs", "new_path": "rita/src/rita_exit/database/email.rs", "diff": "@@ -9,6 +9,8 @@ use diesel;\nuse diesel::prelude::PgConnection;\nuse exit_db::models;\nuse failure::Error;\n+use futures::future;\n+use futures::future::Future;\nuse handlebars::Handlebars;\nuse lettre::file::FileTransport;\nuse lettre::smtp::authentication::{Credentials, Mechanism};\n@@ -66,20 +68,27 @@ pub fn handle_email_registration(\ntheir_record: &exit_db::models::Client,\nconn: &PgConnection,\ncooldown: i64,\n-) -> Result<ExitState, Error> {\n+) -> impl Future<Item = ExitState, Error = Error> {\nlet mut their_record = their_record.clone();\nif client.reg_details.email_code == Some(their_record.email_code.clone()) {\ninfo!(\"email verification complete for {:?}\", client);\n- verify_client(&client, true, &conn)?;\n+\n+ match verify_client(&client, true, &conn) {\n+ Ok(_) => (),\n+ Err(e) => return future::err(e),\n+ }\ntheir_record.verified = true;\n}\nif verif_done(&their_record) {\ninfo!(\"{:?} is now registered\", client);\n- Ok(ExitState::Registered {\n- our_details: ExitClientDetails {\n- client_internal_ip: their_record.internal_ip.parse()?,\n- },\n+\n+ let client_internal_ip = match their_record.internal_ip.parse() {\n+ Ok(ip) => ip,\n+ Err(e) => return future::err(format_err!(\"{:?}\", e)),\n+ };\n+ future::ok(ExitState::Registered {\n+ our_details: ExitClientDetails { client_internal_ip },\ngeneral_details: get_exit_info(),\nmessage: \"Registration OK\".to_string(),\n})\n@@ -87,7 +96,7 @@ pub fn handle_email_registration(\nlet time_since_last_email = secs_since_unix_epoch() - their_record.email_sent_time;\nif time_since_last_email < cooldown {\n- Ok(ExitState::GotInfo {\n+ future::ok(ExitState::GotInfo {\ngeneral_details: get_exit_info(),\nmessage: format!(\n\"Wait {} more seconds for verification cooldown\",\n@@ -96,9 +105,15 @@ pub fn handle_email_registration(\nauto_register: true,\n})\n} else {\n- update_mail_sent_time(&client, &conn)?;\n- send_mail(&their_record)?;\n- Ok(ExitState::Pending {\n+ match update_mail_sent_time(&client, &conn) {\n+ Ok(_) => (),\n+ Err(e) => return future::err(e),\n+ }\n+ match send_mail(&their_record) {\n+ Ok(_) => (),\n+ Err(e) => return future::err(e),\n+ }\n+ future::ok(ExitState::Pending {\ngeneral_details: get_exit_info(),\nmessage: \"awaiting email verification\".to_string(),\nemail_code: None,\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/mod.rs", "new_path": "rita/src/rita_exit/database/mod.rs", "diff": "@@ -35,6 +35,7 @@ use diesel;\nuse diesel::prelude::{Connection, ConnectionError, PgConnection, RunQueryDsl};\nuse exit_db::{models, schema};\nuse failure::Error;\n+use futures::future;\nuse futures::future::join_all;\nuse futures::Future;\nuse ipnetwork::IpNetwork;\n@@ -164,36 +165,54 @@ pub fn signup_client(client: ExitClientIdentity) -> impl Future<Item = ExitState\nget_gateway_ip_single(client.global.mesh_ip).and_then(move |gateway_ip| {\nverify_ip(gateway_ip).and_then(move |verify_status| {\nget_country(gateway_ip).and_then(move |user_country| {\n- let conn = get_database_connection()?;\n- let their_record = create_or_update_user_record(&conn, &client, user_country)?;\n+ let conn = match get_database_connection() {\n+ Ok(db) => db,\n+ Err(e) => {\n+ return Box::new(future::err(format_err!(\"{:?}\", e)))\n+ as Box<Future<Item = ExitState, Error = Error>>\n+ }\n+ };\n+ let their_record = match create_or_update_user_record(&conn, &client, user_country)\n+ {\n+ Ok(record) => record,\n+ Err(e) => return Box::new(future::err(e)),\n+ };\n// either update and grab an existing entry or create one\nmatch (verify_status, SETTING.get_verif_settings()) {\n- (true, Some(ExitVerifSettings::Email(mailer))) => handle_email_registration(\n+ (true, Some(ExitVerifSettings::Email(mailer))) => {\n+ Box::new(handle_email_registration(\n&client,\n&their_record,\n&conn,\nmailer.email_cooldown as i64,\n- ),\n- (true, Some(ExitVerifSettings::Phone(phone))) => {\n- handle_sms_registration(&client, &their_record, phone.auth_api_key, &conn)\n+ ))\n}\n+ (true, Some(ExitVerifSettings::Phone(phone))) => Box::new(\n+ handle_sms_registration(client, their_record, phone.auth_api_key, conn),\n+ ),\n(true, None) => {\n- verify_client(&client, true, &conn)?;\n- Ok(ExitState::Registered {\n- our_details: ExitClientDetails {\n- client_internal_ip: their_record.internal_ip.parse()?,\n- },\n+ match verify_client(&client, true, &conn) {\n+ Ok(_) => (),\n+ Err(e) => return Box::new(future::err(e)),\n+ }\n+ let client_internal_ip = match their_record.internal_ip.parse() {\n+ Ok(ip) => ip,\n+ Err(e) => return Box::new(future::err(format_err!(\"{:?}\", e))),\n+ };\n+\n+ Box::new(future::ok(ExitState::Registered {\n+ our_details: ExitClientDetails { client_internal_ip },\ngeneral_details: get_exit_info(),\nmessage: \"Registration OK\".to_string(),\n- })\n+ }))\n}\n- (false, _) => Ok(ExitState::Denied {\n+ (false, _) => Box::new(future::ok(ExitState::Denied {\nmessage: format!(\n\"This exit only accepts connections from {}\",\ndisplay_hashset(&SETTING.get_allowed_countries()),\n),\n- }),\n+ })),\n}\n})\n})\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_exit/database/sms.rs", "new_path": "rita/src/rita_exit/database/sms.rs", "diff": "@@ -2,14 +2,18 @@ use crate::rita_exit::database::database_tools::text_sent;\nuse crate::rita_exit::database::database_tools::verify_client;\nuse crate::rita_exit::database::get_exit_info;\nuse crate::rita_exit::database::struct_tools::texts_sent;\n+use actix::Arbiter;\n+use actix_web::client as actix_client;\n+use actix_web::client::ClientResponse;\nuse althea_types::{ExitClientDetails, ExitClientIdentity, ExitState};\nuse diesel;\nuse diesel::prelude::*;\nuse failure::Error;\n+use futures::future;\n+use futures::future::Either;\n+use futures::future::Future;\nuse phonenumber::PhoneNumber;\n-use reqwest;\nuse settings::exit::PhoneVerifSettings;\n-use std::time::Duration;\n#[derive(Serialize)]\npub struct SmsCheck {\n@@ -21,22 +25,33 @@ pub struct SmsCheck {\n/// Posts to the validation endpoint with the code, will return success if the code\n/// is the same as the one sent to the user\n-fn check_text(number: String, code: String, api_key: String) -> Result<bool, Error> {\n+fn check_text(\n+ number: String,\n+ code: String,\n+ api_key: String,\n+) -> impl Future<Item = bool, Error = Error> {\ntrace!(\"About to check text message status for {}\", number);\n- let number: PhoneNumber = number.parse()?;\n- let client = reqwest::Client::builder()\n- .timeout(Duration::from_secs(1))\n- .build()?;\n- let res = client\n- .get(\"https://api.authy.com/protected/json/phones/verification/check\")\n+ let number: PhoneNumber = match number.parse() {\n+ Ok(number) => number,\n+ Err(e) => return Either::A(future::err(e)),\n+ };\n+ let url = \"https://api.authy.com/protected/json/phones/verification/check\";\n+ Either::B(\n+ actix_client::get(&url)\n.form(&SmsCheck {\napi_key,\nverification_code: code,\nphone_number: number.national().to_string(),\ncountry_code: number.code().value().to_string(),\n})\n- .send()?;\n- Ok(res.status().is_success())\n+ .unwrap()\n+ .send()\n+ .from_err()\n+ .and_then(|value| {\n+ trace!(\"Got {} back from check text\", value.status());\n+ Ok(value.status().is_success())\n+ }),\n+ )\n}\n#[derive(Serialize)]\n@@ -48,40 +63,39 @@ pub struct SmsRequest {\n}\n/// Sends the authy verification text by hitting the api endpoint\n-fn send_text(number: String, api_key: String) -> Result<(), Error> {\n+fn send_text(number: String, api_key: String) -> impl Future<Item = ClientResponse, Error = Error> {\ninfo!(\"Sending message for {}\", number);\n- let number: PhoneNumber = number.parse()?;\n- let client = reqwest::Client::builder()\n- .timeout(Duration::from_secs(1))\n- .build()?;\n- let res = client\n- .post(\"https://api.authy.com/protected/json/phones/verification/start\")\n+ let url = \"https://api.authy.com/protected/json/phones/verification/start\";\n+ let number: PhoneNumber = match number.parse() {\n+ Ok(number) => number,\n+ Err(e) => return Either::A(future::err(e)),\n+ };\n+ Either::B(\n+ actix_client::post(&url)\n.form(&SmsRequest {\napi_key,\nvia: \"sms\".to_string(),\nphone_number: number.national().to_string(),\ncountry_code: number.code().value().to_string(),\n})\n- .send()?;\n- if res.status().is_success() {\n- Ok(())\n- } else {\n- bail!(\"SMS API failure! Maybe bad number?\")\n- }\n+ .unwrap()\n+ .send()\n+ .from_err(),\n+ )\n}\n/// Handles the minutia of phone registration states\npub fn handle_sms_registration(\n- client: &ExitClientIdentity,\n- their_record: &exit_db::models::Client,\n+ client: ExitClientIdentity,\n+ their_record: exit_db::models::Client,\napi_key: String,\n- conn: &PgConnection,\n-) -> Result<ExitState, Error> {\n+ conn: PgConnection,\n+) -> impl Future<Item = ExitState, Error = Error> {\ninfo!(\n\"Handling phone registration for {}\",\nclient.global.wg_public_key\n);\n- let text_num = texts_sent(their_record);\n+ let text_num = texts_sent(&their_record);\nlet sent_more_than_allowed_texts = text_num > 10;\nmatch (\nclient.reg_details.phone.clone(),\n@@ -90,8 +104,9 @@ pub fn handle_sms_registration(\n) {\n// all texts exhausted, but they can still submit the correct code\n(Some(number), Some(code), true) => {\n- if check_text(number, code, api_key)? {\n- verify_client(&client, true, conn)?;\n+ Box::new(check_text(number, code, api_key).and_then(move |result| {\n+ if result {\n+ verify_client(&client, true, &conn)?;\ninfo!(\n\"Phone registration complete for {}\",\n@@ -112,17 +127,18 @@ pub fn handle_sms_registration(\nphone_code: None,\n})\n}\n+ })) as Box<Future<Item = ExitState, Error = Error>>\n}\n// user has exhausted attempts but is still not submitting code\n- (Some(_number), None, true) => Ok(ExitState::Pending {\n+ (Some(_number), None, true) => Box::new(future::ok(ExitState::Pending {\ngeneral_details: get_exit_info(),\nmessage: \"awaiting phone verification\".to_string(),\nemail_code: None,\nphone_code: None,\n- }),\n+ })),\n// user has attempts remaining and is requesting the code be resent\n(Some(number), None, false) => {\n- send_text(number, api_key)?;\n+ Box::new(send_text(number, api_key).and_then(move |_result| {\ntext_sent(&client, &conn, text_num)?;\nOk(ExitState::Pending {\ngeneral_details: get_exit_info(),\n@@ -130,11 +146,14 @@ pub fn handle_sms_registration(\nemail_code: None,\nphone_code: None,\n})\n+ })) as Box<Future<Item = ExitState, Error = Error>>\n}\n// user has attempts remaining and is submitting a code\n(Some(number), Some(code), false) => {\n- if check_text(number, code, api_key)? {\n- verify_client(&client, true, conn)?;\n+ Box::new(check_text(number, code, api_key).and_then(move |result| {\n+ trace!(\"Check text returned {}\", result);\n+ if result {\n+ verify_client(&client, true, &conn)?;\ninfo!(\n\"Phone registration complete for {}\",\n@@ -155,11 +174,12 @@ pub fn handle_sms_registration(\nphone_code: None,\n})\n}\n+ })) as Box<Future<Item = ExitState, Error = Error>>\n}\n// user did not submit a phonenumber\n- (None, _, _) => Ok(ExitState::Denied {\n+ (None, _, _) => Box::new(future::ok(ExitState::Denied {\nmessage: \"This exit requires a phone number to register!\".to_string(),\n- }),\n+ })) as Box<Future<Item = ExitState, Error = Error>>,\n}\n}\n@@ -181,21 +201,25 @@ pub fn send_low_balance_sms(number: &str, phone: PhoneVerifSettings) -> Result<(\nphone.twillio_account_id\n);\nlet number: PhoneNumber = number.parse()?;\n- let client = reqwest::Client::builder()\n- .timeout(Duration::from_secs(1))\n- .build()?;\n- let res = client\n- .post(&url)\n+ let res = actix_client::post(&url)\n.basic_auth(phone.twillio_account_id, Some(phone.twillio_auth_token))\n.form(&SmsNotification {\nto: number.to_string(),\nfrom: phone.notification_number,\nbody: phone.balance_notification_body,\n})\n- .send()?;\n- if res.status().is_success() {\n- Ok(())\n- } else {\n- bail!(\"SMS API failure! Maybe bad number?\")\n+ .unwrap()\n+ .send()\n+ .then(move |result| {\n+ if result.is_err() {\n+ warn!(\n+ \"Low balance text to {} failed with {:?}\",\n+ number.to_string(),\n+ result\n+ );\n}\n+ Ok(())\n+ });\n+ Arbiter::spawn(res);\n+ Ok(())\n}\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Async SMS sending This leaves only postgres as the remaining sync component
20,244
04.06.2019 13:53:27
14,400
db9f9bc8ca048ad165b490255a1e3e60dbacc62a
Complete the removal of sync http code
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -135,11 +135,6 @@ dependencies = [\n\"syn 0.15.27 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n-[[package]]\n-name = \"adler32\"\n-version = \"1.0.3\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-\n[[package]]\nname = \"aho-corasick\"\nversion = \"0.6.10\"\n@@ -490,14 +485,6 @@ dependencies = [\n\"libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n-[[package]]\n-name = \"crc32fast\"\n-version = \"1.2.0\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-dependencies = [\n- \"cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)\",\n-]\n-\n[[package]]\nname = \"crossbeam-channel\"\nversion = \"0.3.8\"\n@@ -943,45 +930,6 @@ dependencies = [\n\"quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n-[[package]]\n-name = \"hyper\"\n-version = \"0.12.25\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-dependencies = [\n- \"bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"futures 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"h2 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"http 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-reactor 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-tcp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-threadpool 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-timer 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n-]\n-\n-[[package]]\n-name = \"hyper-tls\"\n-version = \"0.3.1\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-dependencies = [\n- \"bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"futures 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"hyper 0.12.25 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n-]\n-\n[[package]]\nname = \"idna\"\nversion = \"0.1.5\"\n@@ -1130,16 +1078,6 @@ name = \"libc\"\nversion = \"0.2.50\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-[[package]]\n-name = \"libflate\"\n-version = \"0.1.20\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-dependencies = [\n- \"adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n-]\n-\n[[package]]\nname = \"libsqlite3-sys\"\nversion = \"0.9.3\"\n@@ -1876,35 +1814,6 @@ dependencies = [\n\"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n-[[package]]\n-name = \"reqwest\"\n-version = \"0.9.11\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-dependencies = [\n- \"base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"encoding_rs 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"futures 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"http 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"hyper 0.12.25 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"hyper-tls 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"libflate 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"mime_guess 2.0.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"serde_urlencoded 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-threadpool 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"tokio-timer 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"uuid 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n-]\n-\n[[package]]\nname = \"resolv-conf\"\nversion = \"0.6.2\"\n@@ -1954,7 +1863,6 @@ dependencies = [\n\"phonenumber 0.2.3+8.10.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"regex 1.1.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"reqwest 0.9.11 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)\",\n\"serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)\",\n@@ -2622,11 +2530,6 @@ dependencies = [\n\"trust-dns-proto 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n-[[package]]\n-name = \"try-lock\"\n-version = \"0.2.2\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-\n[[package]]\nname = \"typeable\"\nversion = \"0.1.2\"\n@@ -2757,16 +2660,6 @@ dependencies = [\n\"winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n-[[package]]\n-name = \"want\"\n-version = \"0.0.6\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-dependencies = [\n- \"futures 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\",\n- \"try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)\",\n-]\n-\n[[package]]\nname = \"web30\"\nversion = \"0.4.3\"\n@@ -2879,7 +2772,6 @@ dependencies = [\n\"checksum actix-web 0.7.19 (registry+https://github.com/rust-lang/crates.io-index)\" = \"b0ac60f86c65a50b140139f499f4f7c6e49e4b5d88fbfba08e4e3975991f7bf4\"\n\"checksum actix_derive 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"4300e9431455322ae393d43a2ba1ef96b8080573c0fc23b196219efedfb6ba69\"\n\"checksum actix_derive 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"0bf5f6d7bf2d220ae8b4a7ae02a572bb35b7c4806b24049af905ab8110de156c\"\n-\"checksum adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7e522997b529f05601e05166c07ed17789691f562762c7f3b987263d2dedee5c\"\n\"checksum aho-corasick 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)\" = \"81ce3d38065e618af2d7b77e10c5ad9a069859b4be3c2250f674af3840d9c8a5\"\n\"checksum aho-corasick 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"e6f484ae0c99fec2e858eb6134949117399f222608d84cadb3f58c1f97c2364c\"\n\"checksum arc-swap 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)\" = \"1025aeae2b664ca0ea726a89d574fe8f4e77dd712d443236ad1de00379450cf6\"\n@@ -2912,7 +2804,6 @@ dependencies = [\n\"checksum cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"1465f8134efa296b4c19db34d909637cb2bf0f7aaf21299e23e18fa29ac557cf\"\n\"checksum core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"286e0b41c3a20da26536c6000a280585d519fd07b3956b43aed8a79e9edce980\"\n\"checksum core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"716c271e8613ace48344f723b60b900a93150271e5be206212d052bbc0883efa\"\n-\"checksum crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1\"\n\"checksum crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)\" = \"0f0ed1a4de2235cabda8558ff5840bffb97fcb64c97827f354a451307df5f72b\"\n\"checksum crossbeam-deque 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"b18cd2e169ad86297e6bc0ad9aa679aee9daa4f19e8163860faf7c164e4f5a71\"\n\"checksum crossbeam-epoch 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"04c9e3102cc2d69cd681412141b390abd55a362afc1540965dad0ad4d34280b4\"\n@@ -2964,8 +2855,6 @@ dependencies = [\n\"checksum http 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)\" = \"fe67e3678f2827030e89cc4b9e7ecd16d52f132c0b940ab5005f88e821500f6a\"\n\"checksum httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"e8734b0cfd3bc3e101ec59100e101c2eecd19282202e87808b3037b442777a83\"\n\"checksum humantime 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"3ca7e5f2e110db35f93b837c81797f3714500b81d517bf20c431b16d3ca4f114\"\n-\"checksum hyper 0.12.25 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7d5b6658b016965ae301fa995306db965c93677880ea70765a84235a96eae896\"\n-\"checksum hyper-tls 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"32cd73f14ad370d3b4d4b7dce08f69b81536c82e39fcc89731930fe5788cd661\"\n\"checksum idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e\"\n\"checksum indexmap 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7e81a7c05f79578dbc15793d8b619db9ba32b4577003ef3af1a91c416798c58d\"\n\"checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08\"\n@@ -2985,7 +2874,6 @@ dependencies = [\n\"checksum lettre 0.9.1 (git+https://github.com/lettre/lettre/)\" = \"<none>\"\n\"checksum lettre_email 0.9.1 (git+https://github.com/lettre/lettre/)\" = \"<none>\"\n\"checksum libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)\" = \"aab692d7759f5cd8c859e169db98ae5b52c924add2af5fbbca11d12fefb567c1\"\n-\"checksum libflate 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)\" = \"54d1ddf9c52870243c5689d7638d888331c1116aa5b398f3ba1acfa7d8758ca1\"\n\"checksum libsqlite3-sys 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"d3711dfd91a1081d2458ad2d06ea30a8755256e74038be2ad927d94e1c955ca8\"\n\"checksum linked-hash-map 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"6d262045c5b87c0861b3f004610afd0e2c851e2908d08b6c870cbb9d5f494ecd\"\n\"checksum linked-hash-map 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"70fb39025bc7cdd76305867c4eccf2f2dcf6e9a57f5b21a93e1c2d86cd03ec9e\"\n@@ -3067,7 +2955,6 @@ dependencies = [\n\"checksum regex-syntax 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7d707a4fa2637f2dca2ef9fd02225ec7661fe01a53623c1e6515b6916511f7a7\"\n\"checksum regex-syntax 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"dcfd8681eebe297b81d98498869d4aae052137651ad7b96822f09ceb690d0a96\"\n\"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5\"\n-\"checksum reqwest 0.9.11 (registry+https://github.com/rust-lang/crates.io-index)\" = \"e542d9f077c126af32536b6aacc75bb7325400eab8cd0743543be5d91660780d\"\n\"checksum resolv-conf 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"b263b4aa1b5de9ffc0054a2386f96992058bb6870aab516f8cdeb8a667d56dcb\"\n\"checksum rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)\" = \"f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a\"\n\"checksum rust-ini 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"3e52c148ef37f8c375d49d5a73aa70713125b7f19095948a923f80afdeb22ec2\"\n@@ -3133,7 +3020,6 @@ dependencies = [\n\"checksum trust-dns-proto 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"0838272e89f1c693b4df38dc353412e389cf548ceed6f9fd1af5a8d6e0e7cf74\"\n\"checksum trust-dns-proto 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"09144f0992b0870fa8d2972cc069cbf1e3c0fda64d1f3d45c4d68d0e0b52ad4e\"\n\"checksum trust-dns-resolver 0.10.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"8a9f877f7a1ad821ab350505e1f1b146a4960402991787191d6d8cab2ce2de2c\"\n-\"checksum try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382\"\n\"checksum typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"1410f6f91f21d1612654e7cc69193b0334f909dcf2c790c4826254fbb86f8887\"\n\"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169\"\n\"checksum ucd-trie 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"71a9c5b1fe77426cf144cc30e49e955270f5086e31a6441dfa8b32efc09b9d77\"\n@@ -3152,7 +3038,6 @@ dependencies = [\n\"checksum vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"def296d3eb3b12371b2c7d0e83bfe1403e4db2d7a0bba324a12b21c4ee13143d\"\n\"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd\"\n\"checksum walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)\" = \"9d9d7ed3431229a144296213105a390676cc49c9b6a72bd19f3176c98e129fa1\"\n-\"checksum want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"797464475f30ddb8830cc529aaaae648d581f99e2036a928877dfde027ddf6b3\"\n\"checksum web30 0.4.3 (git+https://github.com/althea-mesh/web30?rev=56b0068aa43eb563db996418eb96f3ade85ef73b)\" = \"<none>\"\n\"checksum widestring 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"7157704c2e12e3d2189c507b7482c52820a16dfa4465ba91add92f266667cadb\"\n\"checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)\" = \"167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a\"\n" }, { "change_type": "MODIFY", "old_path": "rita/Cargo.toml", "new_path": "rita/Cargo.toml", "diff": "@@ -44,7 +44,6 @@ minihttpse = \"0.1\"\nmockito = \"0.17\"\nmockstream = { git = \"https://github.com/lazy-bitfield/rust-mockstream.git\" }\nrand = \"0.6\"\n-reqwest = \"0.9\"\nserde = \"1.0\"\nserde_derive = \"1.0\"\nserde_json = \"1.0\"\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/dashboard/exits.rs", "new_path": "rita/src/rita_client/dashboard/exits.rs", "diff": "@@ -5,25 +5,27 @@ use crate::rita_common::dashboard::Dashboard;\nuse crate::ARGS;\nuse crate::KI;\nuse crate::SETTING;\n-use ::actix::*;\n+use ::actix::{Handler, Message, ResponseFuture, SystemService};\n+use ::actix_web::client;\nuse ::actix_web::http::StatusCode;\nuse ::actix_web::AsyncResponder;\nuse ::actix_web::Path;\nuse ::actix_web::{HttpRequest, HttpResponse, Json};\n+use actix_web::error::PayloadError;\n+use actix_web::HttpMessage;\nuse althea_types::ExitState;\nuse babel_monitor::do_we_have_route;\nuse babel_monitor::open_babel_stream;\nuse babel_monitor::parse_routes;\nuse babel_monitor::start_connection;\n+use bytes::Bytes;\nuse failure::Error;\nuse futures::{future, Future};\n-use reqwest;\nuse settings::client::{ExitServer, RitaClientSettings};\nuse settings::FileWrite;\nuse settings::RitaCommonSettings;\nuse std::boxed::Box;\nuse std::collections::HashMap;\n-use std::time::Duration;\n#[derive(Serialize)]\npub struct ExitInfo {\n@@ -159,58 +161,33 @@ pub fn exits_sync(\n.json(ret),\n));\n}\n- };\n-\n- let client = reqwest::Client::builder()\n- .timeout(Duration::from_secs(5))\n- .build()\n- .unwrap();\n-\n- let mut new_exits: HashMap<String, ExitServer> = match client.get(list_url).send() {\n- Ok(mut response) => match response.json() {\n- Ok(deserialized) => deserialized,\n- Err(e) => {\n- let mut ret = HashMap::<String, String>::new();\n-\n- error!(\n- \"Could not deserialize exit list at {:?} because of error: {:?}\",\n- list_url, e\n- );\n- ret.insert(\n- \"error\".to_owned(),\n- format!(\n- \"Could not deserialize exit list at URL {:?} because of error {:?}\",\n- list_url, e\n- ),\n- );\n-\n- return Box::new(future::ok(\n- HttpResponse::new(StatusCode::BAD_REQUEST)\n- .into_builder()\n- .json(ret),\n- ));\n}\n- },\n- Err(e) => {\n- let mut ret = HashMap::new();\n+ .to_string();\n- error!(\n- \"Could not make GET request vor URL {:?}, Rust error: {:?}\",\n- list_url, e\n- );\n- ret.insert(\n- \"error\".to_owned(),\n- format!(\"Could not make GET request for URL {:?}\", list_url),\n- );\n- ret.insert(\"rust_error\".to_owned(), format!(\"{:?}\", e));\n+ let res = client::get(list_url.clone())\n+ .header(\"User-Agent\", \"Actix-web\")\n+ .finish()\n+ .unwrap()\n+ .send()\n+ .from_err()\n+ .and_then(move |response| {\n+ response\n+ .body()\n+ .then(move |message_body: Result<Bytes, PayloadError>| {\n+ if let Err(e) = message_body {\nreturn Box::new(future::ok(\nHttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)\n.into_builder()\n- .json(ret),\n+ .json(format!(\"Actix encountered a payload error {:?}\", e)),\n));\n}\n- };\n+ let message_body = message_body.unwrap();\n+ // .json() only works on application/json content types unlike reqwest which handles bytes\n+ // transparently actix requests need to get the body and deserialize using serde_json in\n+ // an explicit fashion\n+ match serde_json::from_slice::<HashMap<String, ExitServer>>(&message_body) {\n+ Ok(mut new_exits) => {\ninfo!(\"exit_sync list: {:#?}\", new_exits);\nlet exits = &mut SETTING.get_exit_client_mut().exits;\n@@ -232,6 +209,33 @@ pub fn exits_sync(\nBox::new(future::ok(HttpResponse::Ok().json(exits.clone())))\n}\n+ Err(e) => {\n+ let mut ret = HashMap::<String, String>::new();\n+\n+ error!(\n+ \"Could not deserialize exit list at {:?} because of error: {:?}\",\n+ list_url, e\n+ );\n+ ret.insert(\n+ \"error\".to_owned(),\n+ format!(\n+ \"Could not deserialize exit list at URL {:?} because of error {:?}\",\n+ list_url, e\n+ ),\n+ );\n+\n+ Box::new(future::ok(\n+ HttpResponse::new(StatusCode::BAD_REQUEST)\n+ .into_builder()\n+ .json(ret),\n+ ))\n+ }\n+ }\n+ })\n+ });\n+\n+ Box::new(res)\n+}\npub fn get_exit_info(\n_req: HttpRequest,\n" }, { "change_type": "MODIFY", "old_path": "rita/src/rita_client/rita_loop/mod.rs", "new_path": "rita/src/rita_client/rita_loop/mod.rs", "diff": "//! tunnel if the signup was successful on the selected exit.\nuse crate::rita_client::exit_manager::ExitManager;\n-use crate::SETTING;\nuse actix::{\nActor, ActorContext, Addr, AsyncContext, Context, Handler, Message, Supervised, SystemService,\n};\n-use althea_types::RTTimestamps;\nuse failure::Error;\n-use reqwest;\n-use settings::client::RitaClientSettings;\nuse std::time::{Duration, Instant};\n#[derive(Default)]\n@@ -77,42 +73,6 @@ impl Handler<Tick> for RitaLoop {\n}\n}\n-pub fn _compute_verification_rtt() -> Result<RTTimestamps, Error> {\n- let exit = match SETTING.get_exit_client().get_current_exit() {\n- Some(current_exit) => current_exit.clone(),\n- None => {\n- return Err(format_err!(\n- \"No current exit even though an exit route is present\"\n- ));\n- }\n- };\n-\n- let client = reqwest::Client::builder()\n- .timeout(Duration::from_secs(1))\n- .build()?;\n-\n- let timestamps: RTTimestamps = client\n- .get(&format!(\n- \"http://[{}]:{}/rtt\",\n- exit.id.mesh_ip, exit.registration_port\n- ))\n- .send()?\n- .json()?;\n-\n- let exit_rx = timestamps.exit_rx;\n- let exit_tx = timestamps.exit_tx;\n- let client_tx = Instant::now();\n- let client_rx = Instant::now();\n-\n- let inner_rtt = client_rx.duration_since(client_tx) - exit_tx.duration_since(exit_rx)?;\n- let inner_rtt_millis =\n- inner_rtt.as_secs() as f32 * 1000.0 + inner_rtt.subsec_nanos() as f32 / 1_000_000.0;\n- // secs -> millis nanos -> millis\n-\n- info!(\"Computed RTTs: inner {}ms\", inner_rtt_millis);\n- Ok(timestamps)\n-}\n-\npub fn check_rita_client_actors() {\nassert!(crate::rita_client::rita_loop::RitaLoop::from_registry().connected());\nassert!(crate::rita_client::exit_manager::ExitManager::from_registry().connected());\n" } ]
Rust
Apache License 2.0
althea-net/althea_rs
Complete the removal of sync http code