Skip to content

Commit

Permalink
Merge pull request AleoNet#994 from ljedrz/add_connect_rpc
Browse files Browse the repository at this point in the history
Add a private RPC to connect to multiple peers
  • Loading branch information
ljedrz authored Jul 30, 2021
2 parents b1d210a + 2b8587d commit c9a17d9
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 1 deletion.
20 changes: 20 additions & 0 deletions rpc/documentation/private_endpoints/connect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Adds the given addresses to the node's list of peers and attempts to connect to them.

### Protected Endpoint

Yes

### Arguments

| Parameter | Type | Required | Description |
|:-------------------:|:------:|:--------:|:------------------------------------------------ |
| `addresses` | array | Yes | The addresses to connect to in an IP:port format |

### Response

null

### Example
```ignore
curl --user username:password --data-binary '{"jsonrpc": "2.0", "id":"1", "method": "connect", "params": ["127.0.0.1:4141", "127.0.0.1:4142"] }' -H 'content-type: application/json' http://127.0.0.1:3030/
```
10 changes: 9 additions & 1 deletion rpc/src/custom_rpc_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use tokio::task;

use std::{convert::Infallible, net::SocketAddr, sync::Arc};

const METHODS_EXPECTING_PARAMS: [&str; 14] = [
const METHODS_EXPECTING_PARAMS: [&str; 15] = [
// public
"getblock",
"getblockhash",
Expand All @@ -56,6 +56,7 @@ const METHODS_EXPECTING_PARAMS: [&str; 14] = [
"decoderecord",
"decryptrecord",
"disconnect",
"connect",
];

#[allow(clippy::too_many_arguments)]
Expand Down Expand Up @@ -287,6 +288,13 @@ async fn handle_rpc<S: Storage + Send + Sync + 'static>(
.map_err(convert_core_err);
result_to_response(&req, result)
}
"connect" => {
let result = rpc
.connect_protected(Params::Array(params), meta)
.await
.map_err(convert_core_err);
result_to_response(&req, result)
}
_ => {
let err = jrt::Error::from_code(jrt::ErrorCode::MethodNotFound);
jrt::Response::error(jrt::Version::V2, err, req.id.clone())
Expand Down
37 changes: 37 additions & 0 deletions rpc/src/rpc_impl_protected.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,29 @@ impl<S: Storage + Send + Sync + 'static> RpcImpl<S> {
Ok(Value::Null)
}

/// Connects to the given addresses
pub async fn connect_protected(self, params: Params, meta: Meta) -> Result<Value, JsonRPCError> {
self.validate_auth(meta)?;

let value = match params {
Params::Array(arr) => arr,
_ => return Err(JsonRPCError::invalid_request()),
};

let addresses: Vec<SocketAddr> = value
.into_iter()
.map(serde_json::from_value)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| JsonRPCError::invalid_params(format!("Invalid params: {}.", e)))?;

for addr in &addresses {
self.node.peer_book.add_peer(*addr, false).await;
}
self.node.connect_to_addresses(&addresses).await;

Ok(Value::Null)
}

/// Expose the protected functions as RPC enpoints
pub fn add_protected(&self, io: &mut MetaIoHandler<Meta>) {
let mut d = IoDelegate::<Self, Meta>::new(Arc::new(self.clone()));
Expand Down Expand Up @@ -311,6 +334,10 @@ impl<S: Storage + Send + Sync + 'static> RpcImpl<S> {
let rpc = rpc.clone();
rpc.disconnect_protected(params, meta)
});
d.add_method_with_meta("connect", |rpc, params, meta| {
let rpc = rpc.clone();
rpc.connect_protected(params, meta)
});

io.extend_with(d)
}
Expand Down Expand Up @@ -656,4 +683,14 @@ impl<S: Storage + Send + Sync + 'static> ProtectedRpcFunctions for RpcImpl<S> {
let node = self.node.clone();
tokio::spawn(async move { node.disconnect_from_peer(address).await });
}

fn connect(&self, addresses: Vec<SocketAddr>) {
let node = self.node.clone();
tokio::spawn(async move {
for addr in &addresses {
node.peer_book.add_peer(*addr, false).await;
}
node.connect_to_addresses(&addresses).await
});
}
}
4 changes: 4 additions & 0 deletions rpc/src/rpc_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,4 +159,8 @@ pub trait ProtectedRpcFunctions {
// todo: readd in Rust 1.54
// #[cfg_attr(nightly, doc(include = "../documentation/private_endpoints/disconnect.md"))]
fn disconnect(&self, address: SocketAddr);

// todo: readd in Rust 1.54
// #[cfg_attr(nightly, doc(include = "../documentation/private_endpoints/connect.md"))]
fn connect(&self, addresses: Vec<SocketAddr>);
}

0 comments on commit c9a17d9

Please sign in to comment.