├── .gitignore ├── src ├── vendor │ ├── mod.rs │ └── solana_rpc.rs ├── rpc.rs ├── utils.rs ├── http_middleware.rs ├── store.rs ├── otel_tracer.rs ├── gossip_service.rs ├── shield.rs ├── broadcaster.rs ├── main.rs ├── tpu_next_client.rs ├── rpc_server.rs └── chain_state.rs ├── rust-toolchain.toml ├── .idea └── .gitignore ├── README.md ├── .env.sample ├── CHANGELOG.md ├── Cargo.toml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .env -------------------------------------------------------------------------------- /src/vendor/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod solana_rpc; 2 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.91.0" 3 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # iris-rs 2 | A fast and lightweight solana transaction sender, based on amazing previous works like [atlas](https://github.com/helius-labs/atlas-txn-sender), [yellowstone shield](https://github.com/rpcpool/yellowstone-shield) and agave's [tpu-client-next](https://github.com/anza-xyz/agave/blob/master/tpu-client-next) 3 | 4 | Change Log : https://github.com/Astralane/iris-rs/blob/main/CHANGELOG.md 5 | -------------------------------------------------------------------------------- /src/rpc.rs: -------------------------------------------------------------------------------- 1 | use jsonrpsee::core::RpcResult; 2 | use jsonrpsee::proc_macros::rpc; 3 | use solana_rpc_client_api::config::RpcSendTransactionConfig; 4 | 5 | #[rpc(server)] 6 | pub trait IrisRpc { 7 | #[method(name = "health")] 8 | async fn health(&self) -> String; 9 | #[method(name = "sendTransaction")] 10 | async fn send_transaction( 11 | &self, 12 | txn: String, 13 | params: Option, 14 | mev_protect: Option, 15 | ) -> RpcResult; 16 | 17 | #[method(name = "sendTransactionBatch")] 18 | async fn send_transaction_batch( 19 | &self, 20 | txns: Vec, 21 | params: Option, 22 | mev_protect: Option, 23 | ) -> RpcResult>; 24 | } 25 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use rand::distributions::Alphanumeric; 2 | use rand::Rng; 3 | 4 | pub const MEV_PROTECT_TRUE_PREFIX: &[u8] = &[0x01]; 5 | pub const MEV_PROTECT_FALSE_PREFIX: &[u8] = &[0x00]; 6 | 7 | pub trait SendTransactionClient: Send + Sync { 8 | fn send_transaction(&self, txn: bytes::Bytes, mev_protect: bool); 9 | fn send_transaction_batch(&self, wire_transaction: Vec, mev_protect: bool); 10 | } 11 | 12 | pub trait ChainStateClient: Send + Sync { 13 | fn get_slot(&self) -> u64; 14 | fn confirm_signature_status(&self, signature: &str) -> Option; 15 | } 16 | 17 | pub fn generate_random_string(len: usize) -> String { 18 | rand::thread_rng() 19 | .sample_iter(&Alphanumeric) 20 | .take(len) 21 | .map(char::from) 22 | .collect() 23 | } 24 | -------------------------------------------------------------------------------- /.env.sample: -------------------------------------------------------------------------------- 1 | RPC_URL=http://api.mainnet-beta.solana.com 2 | WS_URL=ws://api.mainnet-beta.solana.com 3 | ADDRESS=0.0.0.0:7000 4 | IDENTITY_KEYPAIR_FILE= 5 | # GRPC_URL=http://yellostone-rpc:10200 # (optional if --rpc-pubsub-enable-block-subscription is enabled on rpc) 6 | NUM_CONNECTIONS=4 7 | SKIP_CHECK_TRANSACTION_AGE=false 8 | WORKER_CHANNEL_SIZE=512 9 | MAX_RECONNECT_ATTEMPTS=5 10 | LEADERS_FANOUT=8 11 | TX_RETRY_INTERVAL_MS=1000 12 | TX_MAX_RETRIES=5 13 | OTPL_ENDPOINT= 14 | METRICS_UPDATE_INTERVAL_SECS= 1 15 | SHIELD_POLICY_KEY=4QXuzwHutRGjMHRfpGgZpaC9LEYR2wqVmLJBbPbK1zQo 16 | LOOKAHEAD_SLOTS=8 17 | USE_TPU_CLIENT_NEXT=true 18 | PROMETHEUS_ADDR=0.0.0.0:10025 19 | METRICS_UPDATE_INTERVAL_SECS=1 20 | DEDUP_CACHE_MAX_SIZE=1000 21 | #gossip_keypair_file=/home/sol/dummy.json #(DO NOT SET IT TO THE SAME FILE AS THE IDENTITY KEYPAIR must be a dummy file) 22 | #gossip_port_range=[11000,11025] 23 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Change Log 2.0 ( 26th October) 2 | 3 | ### ENV variables changed 4 | * GOSSIP_KEYPAIR_FILE [OPTIONAL] 5 | * GOSSIP_PORT_RANGE [OPTIONAL] 6 | * DEDUP_CACHE_MAX_SIZE 7 | ### Summary of changes 8 | * Added support to deduplicate transactions before sending them to the validator. 9 | * Modified TPU-level reconnections to minimize connection timeout errors [https://github.com/Astralane/iris-rs/pull/25] 10 | * Introduced GOSSIP support, allowing Iris nodes to be available on the network. If set make sure to whitelist the 25 ports range specified in the gossip_port_range 11 | * GOSSIP_KEYPAIR_FILE is optional as well or you can set it to a random key of your choice via solana-keygen (DO NOT SET IT TO THE SAME FILE AS THE IDENTITY KEYPAIR) 12 | --- 13 | 14 | ## Change Log (17th june) 15 | 16 | ### ENV variables changed 17 | 18 | * TX_MAX_RETRIES (**Renamed** from MAX_RETRIES) 19 | * METRICS_UPDATE_INTERVAL_SECS (**ADDED**) 20 | * LEADERS_FANOUT (**ADDED**) 21 | * OTPL_ENDPOINT (**ADDED**) 22 | * TX_RETRY_INTERVAL_MS (**Renamed** from RETRY_INTERVAL_SECONDS) 23 | * SHIELD_POLICY_KEY(**ADDED**) 24 | 25 | **IRIS needs to be run with RUST_LOG="solana_tpu_client_next=debug"** 26 | 27 | ### Summary of changes 28 | 29 | 30 | * otpl is used to send logs to us , in order to do analysis and debug issues on iris which include leaders iris cannot connect to (endpoint will be provided) 31 | * metrics update interval secs is how fast you update metrics, 1 second is good for this 32 | * added an mev protect feature to prevent users from sending transactions to malicious leaders we are using the following contract address from yellow stone 4QXuzwHutRGjMHRfpGgZpaC9LEYR2wqVmLJBbPbK1zQo 33 | -------------------------------------------------------------------------------- /src/vendor/solana_rpc.rs: -------------------------------------------------------------------------------- 1 | use crate::rpc_server::invalid_request; 2 | use base64::prelude::BASE64_STANDARD; 3 | use base64::Engine; 4 | use jsonrpsee::core::RpcResult; 5 | use solana_packet::PACKET_DATA_SIZE; 6 | use solana_sdk::bs58; 7 | use solana_transaction_status::TransactionBinaryEncoding; 8 | 9 | const MAX_BASE58_SIZE: usize = 1683; // Golden, bump if PACKET_DATA_SIZE changes 10 | const MAX_BASE64_SIZE: usize = 1644; // Golden, bump if PACKET_DATA_SIZE changes 11 | pub fn decode_transaction( 12 | encoded: String, 13 | encoding: TransactionBinaryEncoding, 14 | ) -> RpcResult { 15 | let wire_output = match encoding { 16 | TransactionBinaryEncoding::Base58 => { 17 | if encoded.len() > MAX_BASE58_SIZE { 18 | return Err(invalid_request(&format!( 19 | "base58 encoded {} too large: bytes (max: encoded/raw {}/{})", 20 | encoded.len(), 21 | MAX_BASE58_SIZE, 22 | PACKET_DATA_SIZE, 23 | ))); 24 | } 25 | bs58::decode(encoded) 26 | .into_vec() 27 | .map_err(|e| invalid_request(&format!("invalid base58 encoding: {e:?}")))? 28 | } 29 | TransactionBinaryEncoding::Base64 => { 30 | if encoded.len() > MAX_BASE64_SIZE { 31 | return Err(invalid_request(&format!( 32 | "base64 encoded {} too large: bytes (max: encoded/raw {}/{})", 33 | encoded.len(), 34 | MAX_BASE64_SIZE, 35 | PACKET_DATA_SIZE, 36 | ))); 37 | } 38 | BASE64_STANDARD 39 | .decode(encoded) 40 | .map_err(|e| invalid_request(&format!("invalid base64 encoding: {e:?}")))? 41 | } 42 | }; 43 | let wire_output = bytes::Bytes::from(wire_output); 44 | if wire_output.len() > PACKET_DATA_SIZE { 45 | return Err(invalid_request(&format!( 46 | "decoded {} too large: bytes (max: {} bytes)", 47 | wire_output.len(), 48 | PACKET_DATA_SIZE 49 | ))); 50 | } 51 | Ok(wire_output) 52 | } 53 | -------------------------------------------------------------------------------- /src/http_middleware.rs: -------------------------------------------------------------------------------- 1 | use jsonrpsee::core::http_helpers::{Body, Request, Response}; 2 | use jsonrpsee::core::BoxError; 3 | use metrics::{counter, histogram}; 4 | use tracing::debug; 5 | 6 | #[derive(Clone)] 7 | pub struct HttpLoggingMiddleware(pub S); 8 | 9 | impl tower::Service> for HttpLoggingMiddleware 10 | where 11 | S: tower::Service, Response = Response, Error = BoxError> + Clone, 12 | { 13 | type Response = S::Response; 14 | type Error = S::Error; 15 | type Future = S::Future; 16 | 17 | fn poll_ready( 18 | &mut self, 19 | cx: &mut std::task::Context<'_>, 20 | ) -> std::task::Poll> { 21 | self.0.poll_ready(cx) 22 | } 23 | 24 | fn call(&mut self, req: Request) -> Self::Future { 25 | // Extract the X-Timestamp header 26 | let timestamp = req 27 | .headers() 28 | .get("X-Transaction-Timestamp") 29 | .and_then(|value| value.to_str().ok()) 30 | .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok()); 31 | 32 | let origin_header = req 33 | .headers() 34 | .get("X-Client-IP") 35 | .and_then(|value| value.to_str().ok()) 36 | .unwrap_or("unknown") 37 | .to_string(); 38 | 39 | // Log the request details 40 | match timestamp { 41 | Some(ts) => { 42 | let now = chrono::Utc::now(); 43 | let latency = now.signed_duration_since(ts.with_timezone(&chrono::Utc)); 44 | match latency.num_microseconds() { 45 | Some(latency_us) => { 46 | histogram!("iris_http_request_receive_latency_us", "origin" => origin_header) 47 | .record(latency_us as f64); 48 | } 49 | None => { 50 | counter!("iris_http_request_timestamp_invalid", "origin" => origin_header) 51 | .increment(1); 52 | } 53 | } 54 | } 55 | None => { 56 | debug!("No X-Transaction-Timestamp header found in the request"); 57 | counter!("iris_http_request_timestamp_missing", "origin" => origin_header) 58 | .increment(1); 59 | } 60 | } 61 | 62 | // Pass the request to the inner service 63 | self.0.call(req) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "iris" 3 | version = "2.0.1" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | solana-tpu-client-next = { git = "https://github.com/Astralane/agave.git", branch = "reduce-quic-timeouts", features = ["agave-unstable-api"] } 8 | solana-client = { git = "https://github.com/Astralane/agave.git", branch = "reduce-quic-timeouts" } 9 | solana-transaction-status = { git = "https://github.com/Astralane/agave.git", branch = "reduce-quic-timeouts" } 10 | solana-rpc-client-api = { git = "https://github.com/Astralane/agave.git", branch = "reduce-quic-timeouts" } 11 | agave-transaction-view = { git = "https://github.com/Astralane/agave.git", branch = "reduce-quic-timeouts" } 12 | solana-gossip = { git = "https://github.com/Astralane/agave.git", branch = "reduce-quic-timeouts", features = ["agave-unstable-api"] } 13 | solana-streamer = { git = "https://github.com/Astralane/agave.git", branch = "reduce-quic-timeouts" } 14 | solana-net-utils = { git = "https://github.com/Astralane/agave.git", branch = "reduce-quic-timeouts" } 15 | 16 | solana-sdk = "3.0.0" 17 | solana-commitment-config = "3.0.0" 18 | solana-packet = "3.0.0" 19 | 20 | yellowstone-grpc-client = { git = "https://github.com/rpcpool/yellowstone-grpc.git", tag = "v10.0.0+solana.3.0.0" } 21 | yellowstone-grpc-proto = { git = "https://github.com/rpcpool/yellowstone-grpc.git", tag = "v10.0.0+solana.3.0.0", default-features = false } 22 | 23 | jsonrpsee = { version = "0.26.0", features = ["server", "http-client", "macros"] } 24 | tokio = "1.40.0" 25 | tokio-util = "0.7.12" 26 | dashmap = "6.1.0" 27 | bytes = "1.10.1" 28 | figment = { version = "0.10.19", features = ["env"] } 29 | serde = { version = "1.0.188", features = ["derive"] } 30 | anyhow = "1.0.91" 31 | tracing = "0.1.40" 32 | tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } 33 | dotenv = "0.15.0" 34 | base64 = "0.22.1" 35 | metrics = "0.24.0" 36 | metrics-exporter-prometheus = "0.16.0" 37 | futures-util = "0.3.31" 38 | rustls = { version = "0.23.17", features = ["ring"] } 39 | rand = "0.8.5" 40 | arc-swap = "1.7.1" 41 | async-trait = "0.1.88" 42 | once_cell = "1.21.3" 43 | borsh = "1.5.7" 44 | opentelemetry = { version = "0.30.0" } 45 | opentelemetry-otlp = { version = "0.30.0", features = ["default", "grpc-tonic"] } 46 | tracing-opentelemetry = "0.31.0" 47 | opentelemetry_sdk = "0.30.0" 48 | opentelemetry-appender-tracing = "0.30.1" 49 | tracing-log = "0.2.0" 50 | reqwest = "0.12.19" 51 | moka = { version = "0.12.10", features = ["future"] } 52 | tower = "0.5.2" 53 | chrono = "0.4.42" 54 | 55 | [package.metadata.docs.rs] 56 | targets = ["x86_64-unknown-linux-gnu"] 57 | -------------------------------------------------------------------------------- /src/store.rs: -------------------------------------------------------------------------------- 1 | use dashmap::DashMap; 2 | use solana_sdk::signature::Signature; 3 | use std::sync::Arc; 4 | use std::time::Instant; 5 | use tracing::error; 6 | 7 | #[derive(Clone, Debug)] 8 | pub struct TransactionContext { 9 | pub wire_transaction: bytes::Bytes, 10 | pub signature: Signature, 11 | pub sent_at: Instant, 12 | pub slot: u64, 13 | pub retry_count: usize, 14 | pub mev_protect: bool, 15 | } 16 | 17 | impl TransactionContext { 18 | pub fn new( 19 | wire_transaction: bytes::Bytes, 20 | signature: Signature, 21 | slot: u64, 22 | retry_count: usize, 23 | mev_protect: bool, 24 | ) -> Self { 25 | Self { 26 | wire_transaction, 27 | signature, 28 | sent_at: Instant::now(), 29 | slot, 30 | retry_count, 31 | mev_protect, 32 | } 33 | } 34 | } 35 | 36 | pub trait TransactionStore: Send + Sync { 37 | fn add_transaction(&self, transaction: TransactionContext); 38 | fn remove_transaction(&self, signature: String) -> Option; 39 | fn get_transactions(&self) -> Arc>; 40 | fn has_signature(&self, signature: &str) -> bool; 41 | } 42 | 43 | pub struct TransactionStoreImpl { 44 | transactions: Arc>, 45 | } 46 | 47 | impl TransactionStoreImpl { 48 | pub fn new() -> Self { 49 | let transaction_store = Self { 50 | transactions: Arc::new(DashMap::new()), 51 | }; 52 | transaction_store 53 | } 54 | } 55 | 56 | impl TransactionStore for TransactionStoreImpl { 57 | fn add_transaction(&self, transaction: TransactionContext) { 58 | if let Some(signature) = get_signature(&transaction) { 59 | if self.transactions.contains_key(&signature) { 60 | return; 61 | } 62 | self.transactions.insert(signature.to_string(), transaction); 63 | } else { 64 | error!("Transaction has no signatures"); 65 | } 66 | } 67 | fn remove_transaction(&self, signature: String) -> Option { 68 | let transaction = self.transactions.remove(&signature); 69 | transaction.map_or(None, |t| Some(t.1)) 70 | } 71 | fn get_transactions(&self) -> Arc> { 72 | self.transactions.clone() 73 | } 74 | fn has_signature(&self, signature: &str) -> bool { 75 | self.transactions.contains_key(signature) 76 | } 77 | } 78 | 79 | pub fn get_signature(transaction: &TransactionContext) -> Option { 80 | transaction.signature.to_string().parse().ok() 81 | } 82 | -------------------------------------------------------------------------------- /src/otel_tracer.rs: -------------------------------------------------------------------------------- 1 | use opentelemetry::trace::TracerProvider; 2 | use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge; 3 | use opentelemetry_otlp::{LogExporter, WithExportConfig}; 4 | use opentelemetry_sdk::logs::SdkLoggerProvider; 5 | use opentelemetry_sdk::Resource; 6 | use serde::Deserialize; 7 | use tracing::subscriber::set_global_default; 8 | use tracing::Subscriber; 9 | use tracing_log::LogTracer; 10 | use tracing_subscriber::fmt::MakeWriter; 11 | use tracing_subscriber::layer::SubscriberExt; 12 | use tracing_subscriber::{fmt, EnvFilter, Registry}; 13 | 14 | pub async fn get_subscriber_with_otpl( 15 | env_filter: EnvFilter, 16 | otpl_endpoint: String, 17 | bind_port: u16, 18 | sink: Sink, 19 | ) -> impl Subscriber + Send + Sync 20 | where 21 | Sink: for<'a> MakeWriter<'a> + Send + Sync + 'static, 22 | { 23 | let service_name = format!( 24 | "iris_{}:{}", 25 | get_server_public_ip() 26 | .await 27 | .unwrap_or(String::from("CANT_GET_IP")), 28 | bind_port 29 | ); 30 | let tracer = opentelemetry_sdk::trace::SdkTracerProvider::builder() 31 | .with_batch_exporter( 32 | opentelemetry_otlp::SpanExporter::builder() 33 | .with_tonic() 34 | .with_endpoint(otpl_endpoint.clone()) 35 | .build() 36 | .expect("Couldn't create OTLP tracer"), 37 | ) 38 | .with_resource( 39 | Resource::builder() 40 | .with_service_name(service_name.clone()) 41 | .build(), 42 | ) 43 | .build() 44 | .tracer("iris"); 45 | 46 | let telemetry_layer: tracing_opentelemetry::OpenTelemetryLayer< 47 | Registry, 48 | opentelemetry_sdk::trace::Tracer, 49 | > = tracing_opentelemetry::layer().with_tracer(tracer); 50 | 51 | let log_tracer = SdkLoggerProvider::builder() 52 | .with_batch_exporter( 53 | LogExporter::builder() 54 | .with_tonic() 55 | .with_endpoint(otpl_endpoint) 56 | .build() 57 | .expect("Couldn't create OTL tracer"), 58 | ) 59 | .with_resource(Resource::builder().with_service_name(service_name).build()) 60 | .build(); 61 | 62 | let logging_layer = OpenTelemetryTracingBridge::new(&log_tracer); 63 | 64 | let format_layer = fmt::Layer::default().with_writer(sink); 65 | 66 | Registry::default() 67 | .with(telemetry_layer) 68 | .with(logging_layer) 69 | .with(env_filter) 70 | .with(format_layer) 71 | } 72 | 73 | pub fn init_subscriber(subscriber: impl Subscriber + Send + Sync) { 74 | LogTracer::init().expect("Failed to set log filter"); 75 | set_global_default(subscriber).expect("Failed to set subscriber"); 76 | } 77 | 78 | pub fn init_subscriber_without_signoz(sink: Sink) 79 | where 80 | Sink: for<'a> MakeWriter<'a> + Send + Sync + 'static, 81 | { 82 | let env_filter = EnvFilter::try_from_default_env().unwrap_or(EnvFilter::new("info")); 83 | let format_layer = fmt::Layer::default().with_writer(sink); 84 | let subscriber = Registry::default().with(format_layer).with(env_filter); 85 | LogTracer::init().expect("Failed to set log filter"); 86 | set_global_default(subscriber).expect("Failed to set subscriber"); 87 | } 88 | 89 | #[derive(Deserialize)] 90 | struct IpResponse { 91 | ip: String, 92 | } 93 | 94 | async fn get_server_public_ip() -> Result { 95 | let url = "https://api.ipify.org?format=json"; 96 | let response = reqwest::get(url).await?; 97 | let ip_data: IpResponse = response.json().await?; 98 | Ok(ip_data.ip) 99 | } 100 | -------------------------------------------------------------------------------- /src/gossip_service.rs: -------------------------------------------------------------------------------- 1 | use solana_gossip::cluster_info::{ 2 | ClusterInfo, NodeConfig, DEFAULT_CONTACT_DEBUG_INTERVAL_MILLIS, 3 | DEFAULT_CONTACT_SAVE_INTERVAL_MILLIS, 4 | }; 5 | use solana_gossip::contact_info::ContactInfo; 6 | use solana_gossip::gossip_service::GossipService; 7 | use solana_gossip::node::Node; 8 | use solana_net_utils::multihomed_sockets::BindIpAddrs; 9 | use solana_sdk::signature::{Keypair, Signer}; 10 | use solana_sdk::timing::timestamp; 11 | use std::net::SocketAddr; 12 | use std::path::Path; 13 | use std::sync::atomic::AtomicBool; 14 | use std::sync::Arc; 15 | use solana_net_utils::SocketAddrSpace; 16 | use tracing::info; 17 | 18 | const ENTRYPOINTS: [&str; 5] = [ 19 | "entrypoint.mainnet-beta.solana.com:8001", 20 | "entrypoint2.mainnet-beta.solana.com:8001", 21 | "entrypoint3.mainnet-beta.solana.com:8001", 22 | "entrypoint4.mainnet-beta.solana.com:8001", 23 | "entrypoint5.mainnet-beta.solana.com:8001", 24 | ]; 25 | 26 | pub fn run_gossip_service( 27 | port_range: (u16, u16), 28 | gossip_keypair: Option, 29 | exit: Arc, 30 | ) -> tokio::task::JoinHandle<()> { 31 | let gossip_hdl = std::thread::Builder::new() 32 | .name("iris-gossip-t".to_string()) 33 | .spawn(move || { 34 | let gossip_service = make_gossip_service(port_range, gossip_keypair, exit); 35 | gossip_service.join().expect("gossip service handle"); 36 | }) 37 | .expect("failed to spawn gossip service thread"); 38 | 39 | tokio::spawn(async move { 40 | while !gossip_hdl.is_finished() { 41 | tokio::time::sleep(std::time::Duration::from_secs(1)).await; 42 | } 43 | }) 44 | } 45 | 46 | fn make_gossip_service( 47 | port_range: (u16, u16), 48 | gossip_keypair: Option, 49 | exit: Arc, 50 | ) -> GossipService { 51 | let gossip_keypair = Arc::new(gossip_keypair.unwrap_or(Keypair::new())); 52 | let bind_address = solana_net_utils::parse_host("0.0.0.0").expect("invalid bind address"); 53 | 54 | let cluster_endpoints_sockets = ENTRYPOINTS 55 | .iter() 56 | .flat_map(|entry| solana_net_utils::parse_host_port(entry)) 57 | .collect::>(); 58 | 59 | assert_eq!(cluster_endpoints_sockets.len(), 5, "invalid entrypoints"); 60 | 61 | let cluster_endpoints = cluster_endpoints_sockets 62 | .iter() 63 | .map(ContactInfo::new_gossip_entry_point) 64 | .collect::>(); 65 | 66 | let advertised_ip = solana_net_utils::get_public_ip_addr_with_binding( 67 | &cluster_endpoints_sockets[0], 68 | bind_address, 69 | ) 70 | .unwrap(); 71 | 72 | info!("Advertised IP: {:?}", advertised_ip); 73 | 74 | let ledger_path = Path::new("ledger"); 75 | let node_config = NodeConfig { 76 | advertised_ip, 77 | gossip_port: port_range.0, 78 | port_range, 79 | bind_ip_addrs: BindIpAddrs::new(vec![bind_address]).unwrap(), 80 | public_tpu_addr: None, 81 | public_tpu_forwards_addr: None, 82 | public_tvu_addr: None, 83 | vortexor_receiver_addr: None, 84 | num_tvu_receive_sockets: 1.try_into().unwrap(), 85 | num_tvu_retransmit_sockets: 1.try_into().unwrap(), 86 | num_quic_endpoints: 1.try_into().unwrap(), 87 | }; 88 | 89 | let my_shred_version = solana_net_utils::get_cluster_shred_version_with_binding( 90 | &cluster_endpoints_sockets[0], 91 | bind_address, 92 | ) 93 | .unwrap(); 94 | info!("Shred version: {:?}", my_shred_version); 95 | let socket_addr_space = SocketAddrSpace::Unspecified; 96 | 97 | let mut node = Node::new_with_external_ip(&gossip_keypair.pubkey(), node_config); 98 | node.info.set_shred_version(my_shred_version); 99 | node.info.set_wallclock(timestamp()); 100 | 101 | let mut cluster_info = 102 | ClusterInfo::new(node.info.clone(), gossip_keypair.clone(), socket_addr_space); 103 | cluster_info.set_entrypoints(cluster_endpoints); 104 | cluster_info.set_bind_ip_addrs(node.bind_ip_addrs.clone()); 105 | cluster_info.set_contact_debug_interval(DEFAULT_CONTACT_DEBUG_INTERVAL_MILLIS); 106 | cluster_info.restore_contact_info(ledger_path, DEFAULT_CONTACT_SAVE_INTERVAL_MILLIS); 107 | let cluster_info = Arc::new(cluster_info); 108 | 109 | let gossip_service = GossipService::new( 110 | &cluster_info, 111 | None, 112 | node.sockets.gossip.clone(), 113 | None, 114 | true, 115 | None, 116 | exit.clone(), 117 | ); 118 | gossip_service 119 | } 120 | -------------------------------------------------------------------------------- /src/shield.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Context; 2 | use borsh::{BorshDeserialize, BorshSerialize}; 3 | use solana_client::nonblocking::rpc_client::RpcClient; 4 | use solana_sdk::pubkey::Pubkey; 5 | use std::net::SocketAddr; 6 | use std::sync::Arc; 7 | use tracing::warn; 8 | 9 | #[derive(BorshSerialize, BorshDeserialize, Clone, Debug, Eq, PartialEq)] 10 | pub enum PermissionStrategy { 11 | Deny, 12 | Allow, 13 | } 14 | 15 | impl TryFrom for PermissionStrategy { 16 | type Error = std::io::Error; 17 | fn try_from(value: u8) -> Result { 18 | match value { 19 | 0 => Ok(PermissionStrategy::Deny), 20 | 1 => Ok(PermissionStrategy::Allow), 21 | _ => Err(std::io::Error::new( 22 | std::io::ErrorKind::InvalidData, 23 | "Invalid permission strategy", 24 | )), 25 | } 26 | } 27 | } 28 | #[derive(BorshSerialize, BorshDeserialize, Clone, Debug, Eq, PartialEq)] 29 | pub struct Policy { 30 | pub kind: u8, 31 | pub strategy: u8, 32 | pub nonce: u8, 33 | pub identities_len: [u8; 4], 34 | } 35 | impl Policy { 36 | pub const LEN: usize = 7; 37 | 38 | pub fn from_slice(data: &[u8]) -> Result { 39 | let mut data = data; 40 | Self::deserialize(&mut data) 41 | } 42 | pub fn try_strategy(&self) -> Result { 43 | self.strategy.try_into() 44 | } 45 | pub fn try_deserialize_identities(data: &[u8]) -> Vec { 46 | let identities_data = &data[Policy::LEN..]; 47 | identities_data 48 | .chunks_exact(32) 49 | .filter_map(|chunk| Pubkey::try_from_slice(chunk).ok()) 50 | .collect::>() 51 | } 52 | } 53 | #[derive(BorshSerialize, BorshDeserialize, Clone, Debug, Eq, PartialEq)] 54 | pub struct PolicyV2 { 55 | pub kind: u8, 56 | pub strategy: u8, 57 | pub nonce: u8, 58 | pub mint: Pubkey, 59 | pub identities_len: [u8; 4], 60 | } 61 | 62 | impl PolicyV2 { 63 | pub const LEN: usize = 39; 64 | 65 | pub fn from_slice(data: &[u8]) -> Result { 66 | let mut data = data; 67 | Self::deserialize(&mut data) 68 | } 69 | pub fn try_strategy(&self) -> Result { 70 | self.strategy.try_into() 71 | } 72 | pub fn try_deserialize_identities(data: &[u8]) -> Vec { 73 | let identities_data = &data[PolicyV2::LEN..]; 74 | identities_data 75 | .chunks_exact(32) 76 | .filter_map(|chunk| Pubkey::try_from_slice(chunk).ok()) 77 | .collect::>() 78 | } 79 | } 80 | pub struct YellowstoneShieldProvider { 81 | key: Pubkey, 82 | rpc: Arc, 83 | } 84 | 85 | impl YellowstoneShieldProvider { 86 | pub fn new(key: Pubkey, rpc: Arc) -> Self { 87 | Self { key, rpc } 88 | } 89 | pub async fn get_blocked_ips(&self) -> anyhow::Result> { 90 | let cluster_nodes = self.rpc.get_cluster_nodes().await?; 91 | let blocked_identities = self.get_blocked_identities().await?; 92 | let tpu_quics_addrs = cluster_nodes 93 | .iter() 94 | .filter_map(|node| { 95 | if blocked_identities.contains(&node.pubkey) { 96 | node.tpu_quic 97 | } else { 98 | None 99 | } 100 | }) 101 | .collect(); 102 | Ok(tpu_quics_addrs) 103 | } 104 | 105 | async fn get_blocked_identities(&self) -> anyhow::Result> { 106 | let data = self 107 | .rpc 108 | .get_account_data(&self.key) 109 | .await 110 | .context("cannot fetch")?; 111 | 112 | let (strategy, identities) = match &data[0] { 113 | 0 => { 114 | let policy = Policy::from_slice(&data).context("cannot deserialize policy")?; 115 | let strategy = policy 116 | .try_strategy() 117 | .context("invalid permission strategy")?; 118 | let identities = Policy::try_deserialize_identities(&data); 119 | (strategy, identities) 120 | } 121 | 1 => { 122 | let policy = PolicyV2::from_slice(&data).context("cannot deserialize policy_v2")?; 123 | let strategy = policy.try_strategy()?; 124 | let identities = PolicyV2::try_deserialize_identities(&data); 125 | (strategy, identities) 126 | } 127 | _ => return Err(anyhow::anyhow!("Unknown policy type")), 128 | }; 129 | 130 | if matches!(strategy, PermissionStrategy::Allow) { 131 | return Err(anyhow::anyhow!( 132 | "Shield policy for key {} is set to Allow, which is not supported", 133 | &self.key, 134 | )); 135 | }; 136 | 137 | if identities.is_empty() { 138 | warn!( 139 | "Yellowstone shield is enabled, but no identities found for key: {}", 140 | &self.key 141 | ); 142 | } 143 | Ok(identities 144 | .iter() 145 | .map(Pubkey::to_string) 146 | .collect::>()) 147 | } 148 | } 149 | 150 | #[cfg(test)] 151 | pub mod test { 152 | use solana_client::nonblocking::rpc_client::RpcClient; 153 | use std::str::FromStr; 154 | use std::sync::Arc; 155 | 156 | #[tokio::test] 157 | pub async fn test_get_identities_for_key() { 158 | let rpc_provider = Arc::new(RpcClient::new("http://rpc:8899".to_string())); 159 | let key = 160 | solana_sdk::pubkey::Pubkey::from_str("8LXyNpkdnCKCCaUWBku1wD2B1HHaZ41FRgFEN6jNmytv") 161 | .unwrap(); 162 | let provider = super::YellowstoneShieldProvider::new(key, rpc_provider); 163 | let identities = provider.get_blocked_identities().await.unwrap(); 164 | assert_eq!(identities.len() > 0, true); 165 | let addresses = provider.get_blocked_ips().await.unwrap(); 166 | assert_eq!(addresses.len() > 0, true); 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/broadcaster.rs: -------------------------------------------------------------------------------- 1 | use crate::shield::YellowstoneShieldProvider; 2 | use arc_swap::ArcSwap; 3 | use async_trait::async_trait; 4 | use once_cell::sync::Lazy; 5 | use solana_client::nonblocking::rpc_client::RpcClient; 6 | use solana_sdk::pubkey::Pubkey; 7 | use solana_tpu_client_next::connection_workers_scheduler::WorkersBroadcaster; 8 | use solana_tpu_client_next::transaction_batch::TransactionBatch; 9 | use solana_tpu_client_next::workers_cache::{shutdown_worker, WorkersCache, WorkersCacheError}; 10 | use solana_tpu_client_next::ConnectionWorkersSchedulerError; 11 | use std::net::SocketAddr; 12 | use std::sync::Arc; 13 | use std::time::Duration; 14 | use tokio::time::timeout; 15 | use tokio_util::sync::CancellationToken; 16 | use tracing::{debug, info, warn}; 17 | 18 | static BLOCKED_LEADERS: Lazy>> = 19 | Lazy::new(|| ArcSwap::from_pointee(vec![])); 20 | 21 | const TIMEOUT: Duration = Duration::from_secs(10); 22 | 23 | const REFRESH_LIST_DURATION: std::time::Duration = std::time::Duration::from_secs(1 * 60 * 60); // 1 hour 24 | pub struct MevProtectedBroadcaster; 25 | pub fn run( 26 | key: Pubkey, 27 | rpc: Arc, 28 | cancel: CancellationToken, 29 | ) -> tokio::task::JoinHandle<()> { 30 | let shield = YellowstoneShieldProvider::new(key, rpc); 31 | let mut interval = tokio::time::interval(REFRESH_LIST_DURATION); 32 | tokio::spawn(async move { 33 | loop { 34 | tokio::select! { 35 | _ = cancel.cancelled() => { 36 | warn!("Cancel signal received, exiting"); 37 | break; 38 | } 39 | _ = interval.tick() => { 40 | match timeout(TIMEOUT, shield.get_blocked_ips()).await { 41 | Ok(Ok(blocked_leaders)) => { 42 | BLOCKED_LEADERS.store(Arc::new(blocked_leaders)); 43 | info!("Updated blocked leaders: {:?}", BLOCKED_LEADERS.load()); 44 | } 45 | Ok(Err(e)) => { 46 | warn!("Failed to fetch blocked leaders {:?}", e); 47 | } 48 | Err(_) => { 49 | warn!("Timeout fetching blocked leaders"); 50 | continue; 51 | } 52 | } 53 | } 54 | } 55 | } 56 | info!("Exiting blocked leaders refresh task"); 57 | }) 58 | } 59 | 60 | #[async_trait] 61 | impl WorkersBroadcaster for MevProtectedBroadcaster { 62 | async fn send_to_workers( 63 | workers: &mut WorkersCache, 64 | leaders: &[SocketAddr], 65 | transaction_batch: TransactionBatch, 66 | ) -> Result<(), ConnectionWorkersSchedulerError> { 67 | // the last element value shows if this transaction requires MEV protection, 68 | // the actual transactions are everything, but the last element 69 | // not the best way but done due to limitation on tpu-client-next. 70 | let tx_batch = transaction_batch.clone().into_iter(); 71 | let Some((prefix_bytes, wire_transactions)) = tx_batch.as_slice().split_last() else { 72 | // nothing in the slice, nothing to send 73 | return Ok(()); 74 | }; 75 | // convert the bytes to a boolean 76 | let mev_protect = matches!(prefix_bytes.first(), Some(1)); 77 | let transaction_batch = TransactionBatch::new(wire_transactions.to_vec()); 78 | let blocked_leaders = BLOCKED_LEADERS.load().clone(); 79 | 80 | //if the current or next leader is in the blocklist don't send the transactions 81 | if mev_protect { 82 | if let Some(leader) = leaders.first() { 83 | if blocked_leaders.contains(leader) { 84 | return Ok(()); 85 | } 86 | } 87 | } 88 | 89 | for (_, new_leader) in leaders.iter().enumerate() { 90 | if !workers.contains(new_leader) { 91 | warn!("No existing worker for {new_leader:?}, skip sending to this leader."); 92 | continue; 93 | } 94 | 95 | let send_res = 96 | workers.try_send_transactions_to_address(new_leader, transaction_batch.clone()); 97 | 98 | match send_res { 99 | Ok(()) => (), 100 | Err(WorkersCacheError::ShutdownError) => { 101 | debug!("Connection to {new_leader} was closed, worker cache shutdown"); 102 | } 103 | Err(WorkersCacheError::ReceiverDropped) => { 104 | // Remove the worker from the cache if the peer has disconnected. 105 | if let Some(pop_worker) = workers.pop(*new_leader) { 106 | shutdown_worker(pop_worker) 107 | } 108 | } 109 | Err(err) => { 110 | warn!("Connection to {new_leader} was closed, worker error: {err}"); 111 | // If we have failed to send a batch, it will be dropped. 112 | } 113 | } 114 | } 115 | Ok(()) 116 | } 117 | } 118 | 119 | #[cfg(test)] 120 | pub mod test { 121 | use bytes::Bytes; 122 | use solana_tpu_client_next::transaction_batch::TransactionBatch; 123 | 124 | #[test] 125 | pub fn test_mev_protect_serialization_deserialization_case_true() { 126 | let test_transaction = [0u8, 128].to_vec(); 127 | let wire_transaction: Vec> = vec![test_transaction, vec![true as u8]]; 128 | let txn_batch = TransactionBatch::new(wire_transaction); 129 | let batch_iter = txn_batch.into_iter(); 130 | 131 | let Some((mev_protect, wire_transactions)) = batch_iter.as_slice().split_last() else { 132 | // nothing in the slice, nothing to send 133 | panic!("cannot get back last elemenet") 134 | }; 135 | let decoded = mev_protect.first().map(|b| *b == 1).unwrap_or(false); 136 | assert_eq!(true, decoded); 137 | assert_eq!(mev_protect, &Bytes::from_static(&[1])); 138 | for txn in wire_transactions { 139 | assert_eq!(txn, &Bytes::from_static(&[0, 128])); 140 | } 141 | } 142 | 143 | #[test] 144 | pub fn test_mev_protect_serialization_deserialization_case_false() { 145 | let test_transaction = [0u8, 128].to_vec(); 146 | let wire_transaction: Vec> = vec![test_transaction, vec![false as u8]]; 147 | let txn_batch = TransactionBatch::new(wire_transaction); 148 | let batch_iter = txn_batch.into_iter(); 149 | 150 | let Some((mev_protect, wire_transactions)) = batch_iter.as_slice().split_last() else { 151 | // nothing in the slice, nothing to send 152 | panic!("cannot get back last elemenet") 153 | }; 154 | let decoded = mev_protect.first().map(|b| *b == 1).unwrap_or(false); 155 | assert_eq!(false, decoded); 156 | assert_eq!(mev_protect, &Bytes::from_static(&[0])); 157 | for txn in wire_transactions { 158 | assert_eq!(txn, &Bytes::from_static(&[0, 128])); 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #![warn(unused_crate_dependencies)] 2 | use crate::chain_state::ChainStateWsClient; 3 | use crate::http_middleware::HttpLoggingMiddleware; 4 | use crate::otel_tracer::{ 5 | get_subscriber_with_otpl, init_subscriber, init_subscriber_without_signoz, 6 | }; 7 | use crate::rpc::IrisRpcServer; 8 | use crate::rpc_server::IrisRpcServerImpl; 9 | use anyhow::anyhow; 10 | use figment::providers::Env; 11 | use figment::Figment; 12 | use jsonrpsee::server::{ServerBuilder, ServerConfig}; 13 | use metrics_exporter_prometheus::PrometheusBuilder; 14 | use rustls::crypto::CryptoProvider; 15 | use serde::{Deserialize, Serialize}; 16 | use solana_client::nonblocking::pubsub_client::PubsubClient; 17 | use solana_client::nonblocking::rpc_client::RpcClient; 18 | use solana_sdk::pubkey::Pubkey; 19 | use solana_sdk::signature::read_keypair_file; 20 | use solana_tpu_client_next::leader_updater::create_leader_updater; 21 | use std::fmt::Debug; 22 | use std::net::SocketAddr; 23 | use std::process; 24 | use std::str::FromStr; 25 | use std::sync::atomic::AtomicBool; 26 | use std::sync::Arc; 27 | use std::time::Duration; 28 | use tokio::runtime::Handle; 29 | use tokio_util::sync::CancellationToken; 30 | use tracing::{info, warn}; 31 | use tracing_subscriber::EnvFilter; 32 | 33 | mod broadcaster; 34 | mod chain_state; 35 | mod gossip_service; 36 | mod http_middleware; 37 | mod otel_tracer; 38 | mod rpc; 39 | mod rpc_server; 40 | mod shield; 41 | mod store; 42 | mod tpu_next_client; 43 | mod utils; 44 | mod vendor; 45 | 46 | #[derive(Debug, Serialize, Deserialize)] 47 | pub struct Config { 48 | rpc_url: String, 49 | ws_url: String, 50 | address: SocketAddr, 51 | identity_keypair_file: Option, 52 | grpc_url: Option, 53 | tx_max_retries: u32, 54 | //The number of connections to be maintained by the scheduler. 55 | num_connections: usize, 56 | //Whether to skip checking the transaction blockhash expiration. 57 | skip_check_transaction_age: bool, 58 | //The size of the channel used to transmit transaction batches to the worker tasks. 59 | worker_channel_size: usize, 60 | //The maximum number of reconnection attempts allowed in case of connection failure. 61 | max_reconnect_attempts: usize, 62 | //The number of slots to look ahead during the leader estimation procedure. 63 | //Determines how far into the future leaders are estimated, 64 | //allowing connections to be established with those leaders in advance. 65 | leaders_fanout: u64, 66 | use_tpu_client_next: bool, 67 | prometheus_addr: SocketAddr, 68 | metrics_update_interval_secs: u64, 69 | tx_retry_interval_ms: u32, 70 | shield_policy_key: Option, 71 | otpl_endpoint: Option, 72 | dedup_cache_max_size: usize, 73 | gossip_keypair_file: Option, 74 | gossip_port_range: Option<(u16, u16)>, 75 | } 76 | 77 | #[tokio::main] 78 | async fn main() -> anyhow::Result<()> { 79 | //for some reason ths is required to make rustls work 80 | CryptoProvider::install_default(rustls::crypto::ring::default_provider()) 81 | .expect("Failed to install default crypto provider"); 82 | 83 | dotenv::dotenv().ok(); 84 | let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); 85 | 86 | //read config from env variables 87 | let config: Config = Figment::new() 88 | .merge(Env::raw()) 89 | .extract() 90 | .expect("config not valid"); 91 | 92 | match config.otpl_endpoint.clone() { 93 | Some(endpoint) => { 94 | let subscriber = get_subscriber_with_otpl( 95 | env_filter, 96 | endpoint, 97 | config.address.port().clone(), 98 | std::io::stdout, 99 | ) 100 | .await; 101 | init_subscriber(subscriber) 102 | } 103 | None => init_subscriber_without_signoz(std::io::stdout), 104 | } 105 | 106 | info!("config: {:?}", config); 107 | 108 | let identity_keypair = config 109 | .identity_keypair_file 110 | .as_ref() 111 | .and_then(|file| read_keypair_file(file).ok()) 112 | .expect("No identity keypair file"); 113 | 114 | let shield_policy_key = config 115 | .shield_policy_key 116 | .map(|s| Pubkey::from_str(&s)) 117 | .and_then(|p| p.ok()) 118 | .expect("Failed to parse shield policy key"); 119 | 120 | PrometheusBuilder::new() 121 | .with_http_listener(config.prometheus_addr) 122 | .install() 123 | .expect("failed to install recorder/exporter"); 124 | 125 | let shutdown = Arc::new(AtomicBool::new(false)); 126 | let tpu_client_cancel = CancellationToken::new(); 127 | 128 | let mut gossip_task = if let Some(port_range) = config.gossip_port_range { 129 | let gossip_keypair = config 130 | .gossip_keypair_file 131 | .as_ref() 132 | .and_then(|file| read_keypair_file(file).ok()); 133 | Some(gossip_service::run_gossip_service( 134 | port_range, 135 | gossip_keypair, 136 | shutdown.clone(), 137 | )) 138 | } else { 139 | None 140 | }; 141 | 142 | let rpc = Arc::new(RpcClient::new(config.rpc_url.to_owned())); 143 | info!("creating leader updater..."); 144 | let leader_updater = create_leader_updater(rpc.clone(), config.ws_url.to_owned(), None) 145 | .await 146 | .map_err(|e| anyhow!(e))?; 147 | info!("leader updater created"); 148 | let txn_store = Arc::new(store::TransactionStoreImpl::new()); 149 | let (tx_client, tpu_client_jh) = tpu_next_client::spawn_tpu_client_send_txs( 150 | leader_updater, 151 | config.leaders_fanout, 152 | identity_keypair, 153 | rpc.clone(), 154 | shield_policy_key, 155 | config.metrics_update_interval_secs, 156 | config.worker_channel_size, 157 | config.max_reconnect_attempts, 158 | tpu_client_cancel.clone(), 159 | ); 160 | let ws_client = PubsubClient::new(&config.ws_url) 161 | .await 162 | .expect("Failed to connect to websocket"); 163 | 164 | let chain_state = ChainStateWsClient::new( 165 | Handle::current(), 166 | shutdown.clone(), 167 | 800, // around 4 mins 168 | Arc::new(ws_client), 169 | config.grpc_url, 170 | ); 171 | 172 | let iris = IrisRpcServerImpl::new( 173 | Arc::new(tx_client), 174 | txn_store, 175 | Arc::new(chain_state), 176 | Duration::from_millis(config.tx_retry_interval_ms as u64), 177 | shutdown.clone(), 178 | config.tx_max_retries, 179 | config.dedup_cache_max_size, 180 | ); 181 | 182 | let server_config = ServerConfig::builder() 183 | .max_request_body_size(10 * 1024 * 1024) 184 | .max_connections(10_000) 185 | .set_keep_alive(Some(Duration::from_secs(60))) 186 | .set_tcp_no_delay(true) 187 | .build(); 188 | 189 | let http_middleware = tower::ServiceBuilder::new().layer_fn(HttpLoggingMiddleware); 190 | let server = ServerBuilder::with_config(server_config) 191 | .set_http_middleware(http_middleware) 192 | .build(config.address) 193 | .await?; 194 | 195 | info!("server starting in {:?}", config.address); 196 | let server_hdl = server.start(iris.into_rpc()); 197 | // if the solana rpc server connection is lost, the server will exit 198 | info!("waiting for shutdown signal"); 199 | while !shutdown.load(std::sync::atomic::Ordering::Relaxed) { 200 | tokio::time::sleep(Duration::from_secs(1)).await; 201 | } 202 | process::exit(0); 203 | } 204 | -------------------------------------------------------------------------------- /src/tpu_next_client.rs: -------------------------------------------------------------------------------- 1 | use crate::broadcaster::MevProtectedBroadcaster; 2 | use crate::utils::{SendTransactionClient, MEV_PROTECT_FALSE_PREFIX, MEV_PROTECT_TRUE_PREFIX}; 3 | use futures_util::future::TryJoin; 4 | use metrics::{counter, gauge}; 5 | use solana_client::nonblocking::rpc_client::RpcClient; 6 | use solana_sdk::pubkey::Pubkey; 7 | use solana_sdk::signature::Keypair; 8 | use solana_tpu_client_next::connection_workers_scheduler::{ 9 | BindTarget, ConnectionWorkersSchedulerConfig, Fanout, StakeIdentity, 10 | }; 11 | use solana_tpu_client_next::leader_updater::LeaderUpdater; 12 | use solana_tpu_client_next::transaction_batch::TransactionBatch; 13 | use solana_tpu_client_next::{ConnectionWorkersScheduler, SendTransactionStats}; 14 | use std::sync::{atomic, Arc}; 15 | use std::time::Duration; 16 | use tokio::sync::watch; 17 | use tokio_util::sync::CancellationToken; 18 | use tracing::{error, info}; 19 | 20 | pub struct TpuClientNextSender { 21 | sender: tokio::sync::mpsc::Sender, 22 | } 23 | 24 | pub fn spawn_tpu_client_send_txs( 25 | leader_updater: Box, 26 | leader_forward_count: u64, 27 | validator_identity: Keypair, 28 | rpc: Arc, 29 | blocklist_key: Pubkey, 30 | metrics_update_interval_secs: u64, 31 | worker_channel_size: usize, 32 | max_reconnect_attempts: usize, 33 | cancel: CancellationToken, 34 | ) -> ( 35 | TpuClientNextSender, 36 | TryJoin, tokio::task::JoinHandle<()>>, 37 | ) { 38 | let (sender, receiver) = tokio::sync::mpsc::channel(16); 39 | let (_update_certificate_sender, update_certificate_receiver) = watch::channel(None); 40 | let udp_sock = std::net::UdpSocket::bind("0.0.0.0:0").expect("cannot bind tpu client endpoint"); 41 | let broadcaster_task = crate::broadcaster::run(blocklist_key, rpc, cancel.clone()); 42 | let tpu_scheduler_task = tokio::spawn({ 43 | async move { 44 | let config = ConnectionWorkersSchedulerConfig { 45 | bind: BindTarget::Socket(udp_sock), 46 | stake_identity: Some(StakeIdentity::new(&validator_identity)), 47 | // to match MAX_CONNECTIONS from ConnectionCache 48 | num_connections: 1024, 49 | skip_check_transaction_age: true, 50 | worker_channel_size, 51 | max_reconnect_attempts, 52 | leaders_fanout: Fanout { 53 | connect: leader_forward_count as usize + 1, 54 | send: leader_forward_count as usize, 55 | }, 56 | }; 57 | let scheduler = ConnectionWorkersScheduler::new( 58 | leader_updater, 59 | receiver, 60 | update_certificate_receiver, 61 | cancel.clone(), 62 | ); 63 | let _metrics_handle = tokio::spawn(send_metrics_stats( 64 | scheduler.get_stats().clone(), 65 | metrics_update_interval_secs, 66 | )); 67 | tokio::select! { 68 | _ = cancel.cancelled() => {}, 69 | _ = scheduler.run_with_broadcaster::(config) => { 70 | info!("tpu client next scheduler exited"); 71 | } 72 | }; 73 | info!("exiting tpu client next scheduler") 74 | } 75 | }); 76 | let tasks = futures_util::future::try_join(tpu_scheduler_task, broadcaster_task); 77 | (TpuClientNextSender { sender }, tasks) 78 | } 79 | 80 | impl SendTransactionClient for TpuClientNextSender { 81 | fn send_transaction(&self, wire_transaction: bytes::Bytes, mev_protected: bool) { 82 | self.send_transaction_batch(vec![wire_transaction], mev_protected); 83 | } 84 | 85 | fn send_transaction_batch( 86 | &self, 87 | mut wire_transactions: Vec, 88 | mev_protected: bool, 89 | ) { 90 | counter!("iris_tx_send_to_tpu_client_next").increment(wire_transactions.len() as u64); 91 | if wire_transactions.is_empty() { 92 | return; 93 | } 94 | let prefix = if mev_protected { 95 | MEV_PROTECT_TRUE_PREFIX 96 | } else { 97 | MEV_PROTECT_FALSE_PREFIX 98 | }; 99 | wire_transactions.push(bytes::Bytes::from(prefix)); 100 | let txn_batch = TransactionBatch::new(wire_transactions); 101 | let sender = self.sender.clone(); 102 | tokio::spawn(async move { 103 | if let Err(e) = sender.send(txn_batch).await { 104 | error!("Failed to send transaction: {:?}", e); 105 | counter!("iris_error", "type" => "cannot_send_local").increment(1); 106 | } 107 | }); 108 | } 109 | } 110 | 111 | pub async fn send_metrics_stats( 112 | stats: Arc, 113 | metrics_update_interval_secs: u64, 114 | ) { 115 | let mut tick = tokio::time::interval(Duration::from_secs(metrics_update_interval_secs)); 116 | loop { 117 | tick.tick().await; 118 | gauge!("iris_tpu_client_next_successfully_sent") 119 | .set(stats.successfully_sent.load(atomic::Ordering::Relaxed) as f64); 120 | gauge!("iris_tpu_client_next_connect_error_cids_exhausted").set( 121 | stats 122 | .connect_error_cids_exhausted 123 | .load(atomic::Ordering::Relaxed) as f64, 124 | ); 125 | gauge!("iris_tpu_client_next_connect_error_invalid_remote_address").set( 126 | stats 127 | .connect_error_invalid_remote_address 128 | .load(atomic::Ordering::Relaxed) as f64, 129 | ); 130 | gauge!("iris_tpu_client_next_connect_error_other") 131 | .set(stats.connect_error_other.load(atomic::Ordering::Relaxed) as f64); 132 | gauge!("iris_tpu_client_next_connection_error_application_closed").set( 133 | stats 134 | .connection_error_application_closed 135 | .load(atomic::Ordering::Relaxed) as f64, 136 | ); 137 | gauge!("iris_tpu_client_next_connection_error_cids_exhausted").set( 138 | stats 139 | .connection_error_cids_exhausted 140 | .load(atomic::Ordering::Relaxed) as f64, 141 | ); 142 | gauge!("iris_tpu_client_next_connection_error_connection_closed").set( 143 | stats 144 | .connection_error_connection_closed 145 | .load(atomic::Ordering::Relaxed) as f64, 146 | ); 147 | gauge!("iris_tpu_client_next_connection_error_locally_closed").set( 148 | stats 149 | .connection_error_locally_closed 150 | .load(atomic::Ordering::Relaxed) as f64, 151 | ); 152 | gauge!("iris_tpu_client_next_connection_error_reset") 153 | .set(stats.connection_error_reset.load(atomic::Ordering::Relaxed) as f64); 154 | gauge!("iris_tpu_client_next_connection_error_timed_out").set( 155 | stats 156 | .connection_error_timed_out 157 | .load(atomic::Ordering::Relaxed) as f64, 158 | ); 159 | gauge!("iris_tpu_client_next_connection_error_transport_error").set( 160 | stats 161 | .connection_error_transport_error 162 | .load(atomic::Ordering::Relaxed) as f64, 163 | ); 164 | gauge!("iris_tpu_client_next_connection_error_version_mismatch").set( 165 | stats 166 | .connection_error_version_mismatch 167 | .load(atomic::Ordering::Relaxed) as f64, 168 | ); 169 | gauge!("iris_tpu_client_next_write_error_closed_stream").set( 170 | stats 171 | .write_error_closed_stream 172 | .load(atomic::Ordering::Relaxed) as f64, 173 | ); 174 | gauge!("iris_tpu_client_next_write_error_connection_lost").set( 175 | stats 176 | .write_error_connection_lost 177 | .load(atomic::Ordering::Relaxed) as f64, 178 | ); 179 | gauge!("iris_tpu_client_next_write_error_stopped") 180 | .set(stats.write_error_stopped.load(atomic::Ordering::Relaxed) as f64); 181 | gauge!("iris_tpu_client_next_write_error_zero_rtt_rejected").set( 182 | stats 183 | .write_error_zero_rtt_rejected 184 | .load(atomic::Ordering::Relaxed) as f64, 185 | ); 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /src/rpc_server.rs: -------------------------------------------------------------------------------- 1 | use crate::rpc::IrisRpcServer; 2 | use crate::store::{TransactionContext, TransactionStore}; 3 | use crate::utils::{ChainStateClient, SendTransactionClient}; 4 | use crate::vendor::solana_rpc::decode_transaction; 5 | use agave_transaction_view::transaction_view::TransactionView; 6 | use jsonrpsee::core::{async_trait, RpcResult}; 7 | use jsonrpsee::types::error::INVALID_PARAMS_CODE; 8 | use jsonrpsee::types::ErrorObjectOwned; 9 | use metrics::{counter, gauge, histogram}; 10 | use moka::future::{Cache, CacheBuilder}; 11 | use moka::policy::EvictionPolicy; 12 | use solana_rpc_client_api::config::RpcSendTransactionConfig; 13 | use solana_sdk::signature::Signature; 14 | use solana_transaction_status::UiTransactionEncoding; 15 | use std::sync::atomic::AtomicBool; 16 | use std::sync::Arc; 17 | use std::time::Duration; 18 | use tracing::{error, info}; 19 | 20 | pub struct IrisRpcServerImpl { 21 | txn_sender: Arc, 22 | retry_cache: Arc, 23 | chain_state: Arc, 24 | dedup_cache: Cache, 25 | retry_interval: Duration, 26 | max_retries: u32, 27 | } 28 | 29 | pub fn invalid_request(reason: &str) -> ErrorObjectOwned { 30 | ErrorObjectOwned::owned( 31 | INVALID_PARAMS_CODE, 32 | format!("Invalid Request: {reason}"), 33 | None::, 34 | ) 35 | } 36 | 37 | impl IrisRpcServerImpl { 38 | pub fn new( 39 | txn_sender: Arc, 40 | store: Arc, 41 | chain_state: Arc, 42 | retry_interval: Duration, 43 | shutdown: Arc, 44 | max_retries: u32, 45 | dedup_cache_size: usize, 46 | ) -> Self { 47 | let client = IrisRpcServerImpl { 48 | txn_sender, 49 | retry_cache: store, 50 | chain_state, 51 | dedup_cache: CacheBuilder::new(dedup_cache_size as u64) 52 | .eviction_policy(EvictionPolicy::lru()) 53 | .build(), 54 | retry_interval, 55 | max_retries, 56 | }; 57 | client.spawn_retry_transactions_loop(shutdown); 58 | client 59 | } 60 | 61 | fn spawn_retry_transactions_loop(&self, shutdown: Arc) { 62 | let store = self.retry_cache.clone(); 63 | let chain_state = self.chain_state.clone(); 64 | let txn_sender = self.txn_sender.clone(); 65 | let retry_interval = self.retry_interval; 66 | 67 | tokio::spawn(async move { 68 | loop { 69 | if shutdown.load(std::sync::atomic::Ordering::Relaxed) { 70 | break; 71 | } 72 | 73 | let transactions_map = store.get_transactions(); 74 | let mut to_remove = vec![]; 75 | let mut to_retry = vec![]; 76 | let mut to_retry_mev_protected = vec![]; 77 | gauge!("iris_retry_transactions").set(transactions_map.len() as f64); 78 | 79 | for mut txn in transactions_map.iter_mut() { 80 | if let Some(slot) = chain_state.confirm_signature_status(&txn.key()) { 81 | info!( 82 | "Transaction confirmed at slot: {slot} latency {:}", 83 | slot.saturating_sub(txn.slot) 84 | ); 85 | counter!("iris_txn_landed").increment(1); 86 | histogram!("iris_txn_slot_latency") 87 | .record(slot.saturating_sub(txn.slot) as f64); 88 | to_remove.push(txn.key().clone()); 89 | } 90 | //check if transaction has been in the store for too long 91 | if txn.value().sent_at.elapsed() > Duration::from_secs(60) { 92 | to_remove.push(txn.key().clone()); 93 | } 94 | //check if max retries has been reached 95 | if txn.retry_count == 0usize { 96 | to_remove.push(txn.key().clone()); 97 | } 98 | if txn.retry_count > 0usize { 99 | if !txn.mev_protect { 100 | to_retry.push(txn.wire_transaction.clone()); 101 | } else { 102 | to_retry_mev_protected.push(txn.wire_transaction.clone()); 103 | } 104 | } 105 | txn.retry_count = txn.retry_count.saturating_sub(1); 106 | } 107 | 108 | gauge!("iris_transactions_removed").increment(to_remove.len() as f64); 109 | for signature in to_remove { 110 | store.remove_transaction(signature); 111 | } 112 | 113 | if !to_retry.is_empty() { 114 | info!("retrying {} tranasctions", to_retry.iter().len()); 115 | } 116 | 117 | if !to_retry_mev_protected.is_empty() { 118 | info!( 119 | "retrying {} mev protected transactions", 120 | to_retry_mev_protected.iter().len() 121 | ); 122 | } 123 | 124 | for batch in to_retry.chunks(10).clone() { 125 | txn_sender.send_transaction_batch(batch.to_vec(), false); 126 | } 127 | for batch in to_retry_mev_protected.chunks(10).clone() { 128 | txn_sender.send_transaction_batch(batch.to_vec(), true); 129 | } 130 | 131 | tokio::time::sleep(retry_interval).await; 132 | } 133 | }); 134 | } 135 | } 136 | #[async_trait] 137 | impl IrisRpcServer for IrisRpcServerImpl { 138 | async fn health(&self) -> String { 139 | "Ok(1.2)".to_string() 140 | } 141 | 142 | async fn send_transaction( 143 | &self, 144 | txn: String, 145 | params: Option, 146 | mev_protect: Option, 147 | ) -> RpcResult { 148 | info!("Received transaction on rpc connection loop"); 149 | counter!("iris_txn_total_transactions").increment(1); 150 | let mev_protect = mev_protect.unwrap_or(false); 151 | let encoding = params 152 | .and_then(|params| params.encoding) 153 | .unwrap_or(UiTransactionEncoding::Base64); 154 | let binary_encoding = encoding.into_binary_encoding().ok_or_else(|| { 155 | counter!("iris_error", "type" => "invalid_encoding").increment(1); 156 | invalid_request(&format!( 157 | "unsupported encoding: {encoding}. Supported encodings: base58, base64" 158 | )) 159 | })?; 160 | let wire_transaction = match decode_transaction(txn, binary_encoding) { 161 | Ok(wire_transaction) => wire_transaction, 162 | Err(e) => { 163 | counter!("iris_error", "type" => "cannot_decode_transaction").increment(1); 164 | error!("cannot decode transaction: {:?}", e); 165 | return Err(invalid_request(&e.to_string())); 166 | } 167 | }; 168 | let tx_view = 169 | TransactionView::try_new_unsanitized(wire_transaction.as_ref()).map_err(|e| { 170 | counter!("iris_error", "type" => "cannot_deserialize_transaction").increment(1); 171 | error!("cannot deserialize transaction: {:?}", e); 172 | invalid_request("cannot deserialize transaction") 173 | })?; 174 | let signature = tx_view.signatures()[0].clone(); 175 | if self.dedup_cache.contains_key(&signature) { 176 | counter!("iris_error", "type" => "duplicate_transaction").increment(1); 177 | return Err(invalid_request("duplicate transaction")); 178 | } 179 | info!("processing transaction with signature: {signature}"); 180 | let slot = self.chain_state.get_slot(); 181 | let transaction = TransactionContext::new( 182 | wire_transaction, 183 | signature, 184 | slot, 185 | params 186 | .and_then(|params| params.max_retries) 187 | .unwrap_or(self.max_retries as usize), 188 | mev_protect, 189 | ); 190 | // add to store 191 | self.retry_cache.add_transaction(transaction.clone()); 192 | self.dedup_cache.insert(signature, ()).await; 193 | self.txn_sender 194 | .send_transaction(transaction.wire_transaction, mev_protect); 195 | Ok(signature.to_string()) 196 | } 197 | 198 | async fn send_transaction_batch( 199 | &self, 200 | batch: Vec, 201 | params: Option, 202 | mev_protect: Option, 203 | ) -> RpcResult> { 204 | let mev_protect = mev_protect.unwrap_or(false); 205 | if batch.len() > 10 { 206 | counter!("iris_error", "type" => "batch_size_exceeded").increment(1); 207 | return Err(invalid_request("batch size exceeded")); 208 | } 209 | counter!("iris_txn_total_batches").increment(1); 210 | let mut wired_transactions = Vec::new(); 211 | let mut signatures = Vec::new(); 212 | for txn in batch { 213 | if self.retry_cache.has_signature(&txn) { 214 | counter!("iris_error", "type" => "duplicate_transaction_in_batch").increment(1); 215 | return Err(invalid_request("duplicate transaction")); 216 | } 217 | let encoding = params 218 | .and_then(|params| params.encoding) 219 | .unwrap_or(UiTransactionEncoding::Base64); 220 | let binary_encoding = encoding.into_binary_encoding().ok_or_else(|| { 221 | counter!("iris_error", "type" => "invalid_encoding").increment(1); 222 | invalid_request(&format!( 223 | "unsupported encoding: {encoding}. Supported encodings: base58, base64" 224 | )) 225 | })?; 226 | let wire_transaction = match decode_transaction(txn, binary_encoding) { 227 | Ok(wire_transaction) => wire_transaction, 228 | Err(e) => { 229 | counter!("iris_error", "type" => "cannot_decode_transaction").increment(1); 230 | error!("cannot decode transaction: {:?}", e); 231 | return Err(invalid_request("cannot decode transaction")); 232 | } 233 | }; 234 | let tx_view = 235 | TransactionView::try_new_unsanitized(wire_transaction.as_ref()).map_err(|e| { 236 | counter!("iris_error", "type" => "cannot_deserialize_transaction").increment(1); 237 | error!("cannot deserialize transaction: {:?}", e); 238 | invalid_request("cannot deserialize transaction") 239 | })?; 240 | 241 | let signature = tx_view.signatures()[0].clone(); 242 | if self.dedup_cache.contains_key(&signature) { 243 | counter!("iris_error", "type" => "duplicate_transaction").increment(1); 244 | return Err(invalid_request("duplicate transaction")); 245 | } 246 | let slot = self.chain_state.get_slot(); 247 | let transaction = TransactionContext::new( 248 | wire_transaction, 249 | signature, 250 | slot, 251 | params 252 | .and_then(|params| params.max_retries) 253 | .unwrap_or(self.max_retries as usize), 254 | mev_protect, 255 | ); 256 | // add to store 257 | self.dedup_cache.insert(signature, ()).await; 258 | self.retry_cache.add_transaction(transaction.clone()); 259 | wired_transactions.push(transaction.wire_transaction); 260 | signatures.push(signature.to_string()); 261 | } 262 | self.txn_sender 263 | .send_transaction_batch(wired_transactions, mev_protect); 264 | Ok(signatures) 265 | } 266 | } 267 | -------------------------------------------------------------------------------- /src/chain_state.rs: -------------------------------------------------------------------------------- 1 | use crate::utils::{generate_random_string, ChainStateClient}; 2 | use dashmap::DashMap; 3 | use futures_util::{SinkExt, StreamExt}; 4 | use metrics::gauge; 5 | use solana_client::nonblocking::pubsub_client::PubsubClient; 6 | use solana_rpc_client_api::config::{RpcBlockSubscribeConfig, RpcBlockSubscribeFilter}; 7 | use solana_rpc_client_api::response::SlotUpdate; 8 | use solana_sdk::signature::Signature; 9 | use solana_transaction_status::TransactionDetails::Signatures; 10 | use solana_transaction_status::UiTransactionEncoding::Base64; 11 | use std::collections::HashMap; 12 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; 13 | use std::sync::Arc; 14 | use std::time::Duration; 15 | use tokio::runtime::Handle; 16 | use tokio::task::JoinHandle; 17 | use tokio::time::timeout; 18 | use tracing::{debug, error, info, warn}; 19 | use yellowstone_grpc_client::GeyserGrpcClient; 20 | use yellowstone_grpc_proto::geyser::{CommitmentLevel, SubscribeRequestFilterBlocks}; 21 | use yellowstone_grpc_proto::prelude::subscribe_update::UpdateOneof; 22 | use yellowstone_grpc_proto::prelude::{SubscribeRequest, SubscribeRequestPing}; 23 | 24 | const TIMEOUT: Duration = Duration::from_secs(5); 25 | 26 | macro_rules! ping_request { 27 | () => { 28 | SubscribeRequest { 29 | ping: Some(SubscribeRequestPing { id: 1 }), 30 | ..Default::default() 31 | } 32 | }; 33 | } 34 | 35 | macro_rules! block_subscribe_request { 36 | () => { 37 | SubscribeRequest { 38 | blocks: HashMap::from_iter(vec![( 39 | generate_random_string(20).to_string(), 40 | SubscribeRequestFilterBlocks { 41 | account_include: vec![], 42 | include_transactions: Some(true), 43 | include_accounts: Some(false), 44 | include_entries: Some(false), 45 | }, 46 | )]), 47 | commitment: Some(CommitmentLevel::Confirmed as i32), 48 | ..Default::default() 49 | } 50 | }; 51 | } 52 | 53 | //Signature and slot number the transaction was confirmed 54 | type SignatureStore = DashMap; 55 | 56 | pub struct ChainStateWsClient { 57 | slot: Arc, 58 | // signature -> (block_time, slot) 59 | signature_store: Arc, 60 | _thread_hdls: Vec>, 61 | } 62 | 63 | impl ChainStateWsClient { 64 | pub fn new( 65 | runtime: Handle, 66 | shutdown: Arc, 67 | retain_slot_count: u64, 68 | ws_client: Arc, 69 | grpc_url: Option, 70 | ) -> Self { 71 | let current_slot = Arc::new(AtomicU64::new(0)); 72 | let signature_store = Arc::new(DashMap::new()); 73 | let mut hdl = Vec::new(); 74 | let block_listener_hdl = if let Some(grpc_url) = grpc_url { 75 | spawn_grpc_block_listener( 76 | runtime.clone(), 77 | shutdown.clone(), 78 | signature_store.clone(), 79 | retain_slot_count, 80 | grpc_url, 81 | ) 82 | } else { 83 | spawn_ws_block_listener( 84 | runtime.clone(), 85 | shutdown.clone(), 86 | signature_store.clone(), 87 | retain_slot_count, 88 | ws_client.clone(), 89 | ) 90 | }; 91 | hdl.push(block_listener_hdl); 92 | hdl.push(spawn_ws_slot_listener( 93 | runtime.clone(), 94 | shutdown, 95 | current_slot.clone(), 96 | ws_client, 97 | )); 98 | 99 | Self { 100 | slot: current_slot, 101 | signature_store, 102 | _thread_hdls: hdl, 103 | } 104 | } 105 | } 106 | 107 | impl ChainStateClient for ChainStateWsClient { 108 | fn get_slot(&self) -> u64 { 109 | self.slot.load(Ordering::Relaxed) 110 | } 111 | 112 | fn confirm_signature_status(&self, signature: &str) -> Option { 113 | self.signature_store.get(signature).map(|v| *v) 114 | } 115 | } 116 | fn spawn_ws_block_listener( 117 | runtime: Handle, 118 | shutdown: Arc, 119 | signature_store: Arc, 120 | retain_slot_count: u64, 121 | ws_client: Arc, 122 | ) -> JoinHandle<()> { 123 | runtime.spawn(async move { 124 | let config = Some(RpcBlockSubscribeConfig { 125 | commitment: Some(solana_commitment_config::CommitmentConfig::confirmed()), 126 | encoding: Some(Base64), 127 | transaction_details: Some(Signatures), 128 | show_rewards: Some(false), 129 | max_supported_transaction_version: Some(0), 130 | }); 131 | info!("Subscribing to ws block updates"); 132 | match ws_client 133 | .block_subscribe(RpcBlockSubscribeFilter::All, config) 134 | .await 135 | { 136 | Ok((mut stream, unsub)) => { 137 | while !shutdown.load(Ordering::Relaxed) { 138 | let block = match timeout(TIMEOUT, stream.next()).await { 139 | Ok(Some(block)) => block, 140 | Ok(None) => { 141 | error!("block updates ended!"); 142 | shutdown.store(true, Ordering::Relaxed); 143 | break; 144 | } 145 | Err(_) => { 146 | error!("Timeout waiting for block update"); 147 | shutdown.store(true, Ordering::Relaxed); 148 | break; 149 | } 150 | }; 151 | let block_update = block.value; 152 | if let Some(block) = block_update.block { 153 | let slot = block_update.slot; 154 | let _block_time = block.block_time; 155 | debug!("Block update: {:?}", slot); 156 | if let Some(signatures) = block.signatures { 157 | for signature in signatures { 158 | signature_store.insert(signature, slot); 159 | } 160 | } 161 | // remove old signatures to prevent leak of memory < slot - retain_slot_count 162 | signature_store.retain(|_, v| *v > slot - retain_slot_count); 163 | gauge!("iris_signature_store_size").set(signature_store.len() as f64); 164 | } 165 | } 166 | if let Err(e) = timeout(TIMEOUT, unsub()).await { 167 | error!("Error unsubscribing from ws block updates: {:?}", e); 168 | } 169 | } 170 | Err(e) => { 171 | error!("Error subscribing to block updates {:?}", e); 172 | shutdown.store(true, Ordering::Relaxed); 173 | return; 174 | } 175 | } 176 | warn!("Shutting down ws block listener thread"); 177 | }) 178 | } 179 | 180 | fn spawn_ws_slot_listener( 181 | runtime: Handle, 182 | shutdown: Arc, 183 | current_slot: Arc, 184 | ws_client: Arc, 185 | ) -> JoinHandle<()> { 186 | runtime.spawn(async move { 187 | let subscription = ws_client.slot_updates_subscribe().await.unwrap(); 188 | let (mut stream, unsub) = subscription; 189 | while !shutdown.load(Ordering::Relaxed) { 190 | let slot_update = match timeout(TIMEOUT, stream.next()).await { 191 | Ok(Some(update)) => update, 192 | Ok(None) => { 193 | error!("slot updates ended"); 194 | shutdown.store(true, Ordering::Relaxed); 195 | break; 196 | } 197 | Err(_) => { 198 | error!("Timeout waiting for slot update"); 199 | shutdown.store(true, Ordering::Relaxed); 200 | break; 201 | } 202 | }; 203 | info!("Slot update: {:?}", slot_update); 204 | let slot = match slot_update { 205 | SlotUpdate::FirstShredReceived { slot, .. } => slot, 206 | SlotUpdate::Completed { slot, .. } => slot.saturating_add(1), 207 | _ => continue, 208 | }; 209 | debug!("Slot update: {}", slot); 210 | gauge!("iris_current_slot").set(slot as f64); 211 | current_slot.store(slot, Ordering::Relaxed); 212 | } 213 | error!("Slot stream ended unexpectedly!!"); 214 | if let Err(e) = timeout(TIMEOUT, unsub()).await { 215 | error!("Error unsubscribing from ws slot updates: {:?}", e); 216 | } 217 | warn!("Shutting down ws slot listener thread"); 218 | }) 219 | } 220 | 221 | fn spawn_grpc_block_listener( 222 | runtime: Handle, 223 | shutdown: Arc, 224 | signature_store: Arc, 225 | retain_slot_count: u64, 226 | endpoint: String, 227 | ) -> JoinHandle<()> { 228 | let max_retries = 5; 229 | runtime.spawn(async move { 230 | let mut connection_retries = 0; 231 | while !shutdown.load(Ordering::Relaxed) { 232 | connection_retries += 1; 233 | if connection_retries > max_retries { 234 | error!("Max retries reached, shutting down geyser grpc block listener"); 235 | shutdown.store(true, Ordering::Relaxed); 236 | return; 237 | } 238 | 239 | let client = GeyserGrpcClient::build_from_shared(endpoint.clone()); 240 | if let Err(e) = client { 241 | error!("Error creating geyser grpc client: {:?}", e); 242 | tokio::time::sleep(Duration::from_secs(2)).await; 243 | continue; 244 | } 245 | 246 | let client = client 247 | .unwrap() 248 | .max_encoding_message_size(64 * 1024 * 1024) 249 | .max_decoding_message_size(64 * 1024 * 1024); 250 | 251 | let mut connection = match client.connect().await { 252 | Ok(connection) => connection, 253 | Err(e) => { 254 | error!("Error connecting to geyser grpc: {:?}", e); 255 | tokio::time::sleep(Duration::from_secs(2)).await; 256 | continue; 257 | } 258 | }; 259 | 260 | let subscription = match connection.subscribe().await { 261 | Ok(subscription) => subscription, 262 | Err(e) => { 263 | error!("Error subscribing to geyser grpc: {:?}", e); 264 | tokio::time::sleep(Duration::from_secs(2)).await; 265 | continue; 266 | } 267 | }; 268 | 269 | let (mut grpc_tx, mut grpc_rx) = subscription; 270 | info!("Subscribing to grpc block updates.."); 271 | if let Err(e) = grpc_tx.send(block_subscribe_request!()).await { 272 | error!("Error sending subscription request: {:?}", e); 273 | tokio::time::sleep(Duration::from_secs(2)).await; 274 | continue; 275 | } 276 | connection_retries = 0; 277 | while !shutdown.load(Ordering::Relaxed) { 278 | let update = match timeout(TIMEOUT, grpc_rx.next()).await { 279 | Ok(Some(update)) => update, 280 | Ok(None) => { 281 | error!("grpc block updates ended"); 282 | break; 283 | } 284 | Err(_) => { 285 | error!("Timeout waiting for grpc block update"); 286 | break; 287 | } 288 | }; 289 | match update { 290 | Ok(message) => match message.update_oneof { 291 | Some(UpdateOneof::Block(block)) => { 292 | let slot = block.slot; 293 | debug!("Block update: {:?}", slot); 294 | for transaction in block.transactions { 295 | let signature = Signature::try_from(transaction.signature) 296 | .expect("Invalid signature"); 297 | signature_store.insert(signature.to_string(), slot); 298 | } 299 | // remove old signatures to prevent leak of memory < slot - retain_slot_count 300 | signature_store.retain(|_, v| *v > slot - retain_slot_count); 301 | gauge!("iris_signature_store_size").set(signature_store.len() as f64); 302 | } 303 | Some(UpdateOneof::Ping(_)) => { 304 | if let Err(e) = grpc_tx.send(ping_request!()).await { 305 | error!("Error sending ping: {}", e); 306 | break; 307 | } 308 | } 309 | Some(UpdateOneof::Pong(_)) => {} 310 | _ => { 311 | debug!("pong"); 312 | } 313 | }, 314 | Err(e) => { 315 | error!("Error block updates subscription {:?}", e); 316 | tokio::time::sleep(Duration::from_secs(2)).await; 317 | break; 318 | } 319 | } 320 | } 321 | } 322 | warn!("Shutting down grpc block listener thread"); 323 | }) 324 | } 325 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------