Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/bip155 #13

Merged
merged 7 commits into from
Jul 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 37 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ anyhow = "1.0.34"
async-channel = "1.5.1"
base32 = "0.4.0"
base64 = "0.13.0"
bitcoin = { version = "0.25.2", features = ["use-serde"] }
bitcoin = { version = "0.26.0", features = ["use-serde"] }
configure_me = { version = "0.4.0" }
derive_more = "0.99.11"
enum_future = "0.1"
Kixunil marked this conversation as resolved.
Show resolved Hide resolved
futures = "0.3.8"
hex = "0.4.2"
http = "0.2.1"
Expand Down
61 changes: 20 additions & 41 deletions src/fetch_blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use bitcoin::{
consensus::{Decodable, Encodable},
hash_types::BlockHash,
network::{
address::Address,
constants::{Network::Bitcoin, ServiceFlags},
message::{NetworkMessage, RawNetworkMessage},
message_blockdata::Inventory,
Expand All @@ -21,18 +20,20 @@ use bitcoin::{
use futures::FutureExt;
use socks::Socks5Stream;

use crate::client::{RpcClient, RpcError, ClientError, RpcRequest, MISC_ERROR_CODE, PRUNE_ERROR_MESSAGE};
use crate::client::{
ClientError, RpcClient, RpcError, RpcRequest, MISC_ERROR_CODE, PRUNE_ERROR_MESSAGE,
};
use crate::rpc_methods::{GetBlock, GetBlockParams, GetPeerInfo, PeerAddressError};
use crate::state::{State, TorState};

type VersionMessageProducer = Box<dyn Fn(Address) -> RawNetworkMessage + Send + Sync>;
type VersionMessageProducer = Box<dyn Fn() -> RawNetworkMessage + Send + Sync>;

lazy_static::lazy_static! {
static ref VER_ACK: RawNetworkMessage = RawNetworkMessage {
magic: Bitcoin.magic(),
payload: NetworkMessage::Verack,
};
static ref VERSION_MESSAGE: VersionMessageProducer = Box::new(|addr| {
static ref VERSION_MESSAGE: VersionMessageProducer = Box::new(|| {
use std::time::SystemTime;
RawNetworkMessage {
magic: Bitcoin.magic(),
Expand All @@ -42,9 +43,8 @@ lazy_static::lazy_static! {
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs() as i64,
addr,
Address::new(&([127, 0, 0, 1], 8332).into(), ServiceFlags::NONE),
// This is OK because RPC proxy doesn't listen on P2P
bitcoin::network::Address::new(&([127, 0, 0, 1], 8332).into(), ServiceFlags::NONE),
bitcoin::network::Address::new(&([127, 0, 0, 1], 8332).into(), ServiceFlags::NONE),
0,
format!("BTC RPC Proxy v{}", env!("CARGO_PKG_VERSION")),
0,
Expand Down Expand Up @@ -83,8 +83,8 @@ impl Peers {
.into_iter()
.filter(|p| !p.inbound)
.filter(|p| p.servicesnames.contains("NETWORK"))
.map(|p| p.into_address().map(Peer::new))
.collect::<Result<_, _>>()?,
.map(|p| Peer::new(Arc::new(p.addr)))
.collect(),
fetched: Some(Instant::now()),
})
}
Expand Down Expand Up @@ -148,40 +148,19 @@ impl Write for BitcoinPeerConnection {
}
}
impl BitcoinPeerConnection {
pub async fn connect(state: Arc<State>, addr: Address) -> Result<Self, Error> {
pub async fn connect(state: Arc<State>, addr: Arc<String>) -> Result<Self, Error> {
tokio::time::timeout(
state.peer_timeout,
tokio::task::spawn_blocking(move || {
let mut stream = match (addr.socket_addr(), &state.tor) {
(Ok(addr), Some(TorState { only: false, .. })) | (Ok(addr), None) => {
BitcoinPeerConnection::ClearNet(TcpStream::connect(addr)?)
}
(Ok(addr), Some(tor)) => {
BitcoinPeerConnection::Tor(Socks5Stream::connect(tor.proxy, addr)?)
let mut stream = match &state.tor {
Some(TorState { only, proxy })
if *only || addr.split(":").next().unwrap().ends_with(".onion") =>
{
BitcoinPeerConnection::Tor(Socks5Stream::connect(proxy, &**addr)?)
}
(Err(_), Some(tor)) => BitcoinPeerConnection::Tor(Socks5Stream::connect(
tor.proxy,
(
format!(
"{}.onion",
base32::encode(
base32::Alphabet::RFC4648 { padding: false },
&addr
.address
.iter()
.map(|n| *n)
.flat_map(|n| u16::to_be_bytes(n).to_vec())
.collect::<Vec<_>>()
)
.to_lowercase()
)
.as_str(),
addr.port,
),
)?),
(Err(e), None) => return Err(e.into()),
_ => BitcoinPeerConnection::ClearNet(TcpStream::connect(&*addr)?),
};
VERSION_MESSAGE(addr).consensus_encode(&mut stream)?;
VERSION_MESSAGE().consensus_encode(&mut stream)?;
stream.flush()?;
let _ =
bitcoin::network::message::RawNetworkMessage::consensus_decode(&mut stream)?; // version
Expand All @@ -198,12 +177,12 @@ impl BitcoinPeerConnection {
}

pub struct Peer {
addr: Address,
addr: Arc<String>,
send: mpmc::Sender<BitcoinPeerConnection>,
recv: mpmc::Receiver<BitcoinPeerConnection>,
}
impl Peer {
pub fn new(addr: Address) -> Self {
pub fn new(addr: Arc<String>) -> Self {
let (send, recv) = mpmc::bounded(1);
Peer { addr, send, recv }
}
Expand All @@ -222,7 +201,7 @@ impl std::fmt::Debug for Peer {
}

pub struct PeerHandle {
addr: Address,
addr: Arc<String>,
conn: Option<BitcoinPeerConnection>,
send: mpmc::Sender<BitcoinPeerConnection>,
}
Expand Down