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

cln-grpc-plugin: Secure access to your node over the network #5013

Merged
merged 15 commits into from
Mar 30, 2022
Merged
Show file tree
Hide file tree
Changes from 13 commits
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ members = [
"cln-rpc",
"cln-grpc",
"plugins",
"plugins/grpc-plugin",
]
14 changes: 13 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ WIRE_GEN_DEPS := $(WIRE_GEN) $(wildcard tools/gen/*_template)
# These are filled by individual Makefiles
ALL_PROGRAMS :=
ALL_TEST_PROGRAMS :=
ALL_TEST_GEN :=
ALL_FUZZ_TARGETS :=
ALL_C_SOURCES :=
ALL_C_HEADERS := header_versions_gen.h version_gen.h
Expand Down Expand Up @@ -358,6 +359,17 @@ endif
ifneq ($(RUST),0)
include cln-rpc/Makefile
include cln-grpc/Makefile

GRPC_GEN = tests/node_pb2.py \
tests/node_pb2_grpc.py \
tests/primitives_pb2.py

ALL_TEST_GEN += $(GRPC_GEN)

$(GRPC_GEN): cln-grpc/proto/node.proto cln-grpc/proto/primitives.proto
python -m grpc_tools.protoc -I cln-grpc/proto cln-grpc/proto/node.proto --python_out=tests/ --grpc_python_out=tests/ --experimental_allow_proto3_optional
python -m grpc_tools.protoc -I cln-grpc/proto cln-grpc/proto/primitives.proto --python_out=tests/ --grpc_python_out=tests/ --experimental_allow_proto3_optional

endif

# We make pretty much everything depend on these.
Expand Down Expand Up @@ -424,7 +436,7 @@ else
endif
endif

pytest: $(ALL_PROGRAMS) $(DEFAULT_TARGETS) $(ALL_TEST_PROGRAMS)
pytest: $(ALL_PROGRAMS) $(DEFAULT_TARGETS) $(ALL_TEST_PROGRAMS) $(ALL_TEST_GEN)
ifeq ($(PYTEST),)
@echo "py.test is required to run the integration tests, please install using 'pip3 install -r requirements.txt', and rerun 'configure'."
exit 1
Expand Down
33 changes: 33 additions & 0 deletions cln-grpc/proto/node.proto
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ service Node {
rpc AutoCleanInvoice(AutocleaninvoiceRequest) returns (AutocleaninvoiceResponse) {}
rpc CheckMessage(CheckmessageRequest) returns (CheckmessageResponse) {}
rpc Close(CloseRequest) returns (CloseResponse) {}
rpc ConnectPeer(ConnectRequest) returns (ConnectResponse) {}
}

message GetinfoRequest {
Expand Down Expand Up @@ -339,3 +340,35 @@ message CloseResponse {
optional bytes tx = 8;
optional bytes txid = 9;
}

message ConnectRequest {
bytes id = 1;
optional string host = 2;
optional uint32 port = 3;
}

message ConnectResponse {
// Connect.direction
enum ConnectDirection {
IN = 0;
OUT = 1;
}
bytes id = 1;
bytes features = 2;
ConnectDirection direction = 3;
}

message ConnectAddress {
// Connect.address.type
enum ConnectAddressType {
LOCAL_SOCKET = 0;
IPV4 = 1;
IPV6 = 2;
TORV2 = 3;
TORV3 = 4;
}
ConnectAddressType item_type = 1;
optional string socket = 2;
optional string address = 3;
optional uint32 port = 4;
}
22 changes: 22 additions & 0 deletions cln-grpc/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,17 @@ impl From<&responses::CloseResponse> for pb::CloseResponse {
}
}

#[allow(unused_variables)]
impl From<&responses::ConnectResponse> for pb::ConnectResponse {
fn from(c: &responses::ConnectResponse) -> Self {
Self {
id: hex::decode(&c.id).unwrap(),
features: hex::decode(&c.features).unwrap(),
direction: c.direction as i32,
}
}
}

#[allow(unused_variables)]
impl From<&pb::GetinfoRequest> for requests::GetinfoRequest {
fn from(c: &pb::GetinfoRequest) -> Self {
Expand Down Expand Up @@ -371,3 +382,14 @@ impl From<&pb::CloseRequest> for requests::CloseRequest {
}
}

#[allow(unused_variables)]
impl From<&pb::ConnectRequest> for requests::ConnectRequest {
fn from(c: &pb::ConnectRequest) -> Self {
Self {
id: hex::encode(&c.id),
host: c.host.clone(),
port: c.port.map(|i| i as u16),
}
}
}

30 changes: 30 additions & 0 deletions cln-grpc/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,4 +266,34 @@ async fn close(

}

async fn connect_peer(
&self,
request: tonic::Request<pb::ConnectRequest>,
) -> Result<tonic::Response<pb::ConnectResponse>, tonic::Status> {
let req = request.into_inner();
let req: requests::ConnectRequest = (&req).into();
debug!("Client asked for getinfo");
let mut rpc = ClnRpc::new(&self.rpc_path)
.await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?;
let result = rpc.call(Request::ConnectPeer(req))
.await
.map_err(|e| Status::new(
Code::Unknown,
format!("Error calling method ConnectPeer: {:?}", e)))?;
match result {
Response::ConnectPeer(r) => Ok(
tonic::Response::new((&r).into())
),
r => Err(Status::new(
Code::Internal,
format!(
"Unexpected result {:?} to method call ConnectPeer",
r
)
)),
}

}

}
55 changes: 55 additions & 0 deletions cln-rpc/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub enum Request {
AutoCleanInvoice(requests::AutocleaninvoiceRequest),
CheckMessage(requests::CheckmessageRequest),
Close(requests::CloseRequest),
ConnectPeer(requests::ConnectRequest),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
Expand All @@ -38,6 +39,7 @@ pub enum Response {
AutoCleanInvoice(responses::AutocleaninvoiceResponse),
CheckMessage(responses::CheckmessageResponse),
Close(responses::CloseResponse),
ConnectPeer(responses::ConnectResponse),
}

pub mod requests {
Expand Down Expand Up @@ -114,6 +116,16 @@ pub mod requests {
pub force_lease_closed: Option<bool>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConnectRequest {
#[serde(alias = "id")]
pub id: String,
#[serde(alias = "host", skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
#[serde(alias = "port", skip_serializing_if = "Option::is_none")]
pub port: Option<u16>,
}

}


Expand Down Expand Up @@ -731,5 +743,48 @@ pub mod responses {
pub txid: Option<String>,
}

/// Whether they initiated connection or we did
#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ConnectDirection {
IN,
OUT,
}

/// Type of connection (*torv2*/*torv3* only if **direction** is *out*)
#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ConnectAddressType {
LOCAL_SOCKET,
IPV4,
IPV6,
TORV2,
TORV3,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConnectAddress {
// Path `Connect.address.type`
#[serde(rename = "type")]
pub item_type: ConnectAddressType,
#[serde(alias = "socket", skip_serializing_if = "Option::is_none")]
pub socket: Option<String>,
#[serde(alias = "address", skip_serializing_if = "Option::is_none")]
pub address: Option<String>,
#[serde(alias = "port", skip_serializing_if = "Option::is_none")]
pub port: Option<u16>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConnectResponse {
#[serde(alias = "id")]
pub id: String,
#[serde(alias = "features")]
pub features: String,
// Path `Connect.direction`
#[serde(rename = "direction")]
pub direction: ConnectDirection,
}

}

10 changes: 8 additions & 2 deletions contrib/msggen/msggen/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
import json


# Sometimes we want to rename a method, due to a name clash
method_name_override = {
"Connect": "ConnectPeer",
}


def repo_root():
path = subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
return Path(path.strip().decode('UTF-8'))
Expand All @@ -26,7 +32,7 @@ def load_jsonrpc_method(name):
response.typename += "Response"

return Method(
name=name,
name=method_name_override.get(name, name),
request=request,
response=response,
)
Expand All @@ -44,7 +50,7 @@ def load_jsonrpc_service():
"CheckMessage",
# "check", # No point in mapping this one
"Close",
# "connect",
"Connect",
# "createinvoice",
# "createonion",
# "datastore",
Expand Down
21 changes: 21 additions & 0 deletions doc/schemas/connect.request.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "pubkey",
"description": ""
},
"host": {
"type": "string",
"description": "The hostname of the node."
},
"port": {
"type": "u16",
"description": "Port to try connecting to"
}
}
}
5 changes: 4 additions & 1 deletion plugins/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,11 @@ CLN_PLUGIN_SRC = $(shell find plugins/src -name "*.rs")
${CLN_PLUGIN_EXAMPLES}: ${CLN_PLUGIN_SRC}
(cd plugins; cargo build ${CARGO_OPTS} --examples)

target/${RUST_PROFILE}/cln-grpc: ${CLN_PLUGIN_SRC}
cargo build ${CARGO_OPTS} --bin cln-grpc

ifneq ($(RUST),0)
DEFAULT_TARGETS += $(CLN_PLUGIN_EXAMPLES)
DEFAULT_TARGETS += $(CLN_PLUGIN_EXAMPLES) target/${RUST_PROFILE}/cln-grpc
endif

include plugins/test/Makefile
31 changes: 31 additions & 0 deletions plugins/grpc-plugin/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
[package]
edition = "2021"
name = "cln-grpc-plugin"
version = "0.1.0"
cdecker marked this conversation as resolved.
Show resolved Hide resolved
cdecker marked this conversation as resolved.
Show resolved Hide resolved

[[bin]]
name = "cln-grpc"
path = "src/main.rs"

[dependencies]
anyhow = "1.0"
log = "0.4"
prost = "0.8"
rcgen = { version = "0.8", features = ["pem", "x509-parser"] }

[dependencies.cln-grpc]
path = "../../cln-grpc"

[dependencies.cln-plugin]
path = "../../plugins"

[dependencies.cln-rpc]
path = "../../cln-rpc"

[dependencies.tokio]
features = ["net", "rt-multi-thread"]
version = "1"

[dependencies.tonic]
features = ["tls", "transport"]
version = "^0.5"
Loading