MCPcopy Create free account
hub / github.com/ElementsProject/lightning / generate_or_load_identity

Function generate_or_load_identity

plugins/grpc-plugin/src/tls.rs:56–107  ·  view source on GitHub ↗

Generate a given identity

(
    name: &str,
    directory: &Path,
    filename: &str,
    parent: Option<&Identity>,
)

Source from the content-addressed store, hash-verified

54
55/// Generate a given identity
56fn generate_or_load_identity(
57 name: &str,
58 directory: &Path,
59 filename: &str,
60 parent: Option<&Identity>,
61) -> Result<Identity> {
62 // Just our naming convention here.
63 let cert_path = directory.join(format!("{}.pem", filename));
64 let key_path = directory.join(format!("{}-key.pem", filename));
65 // Did we have to generate a new key? In that case we also need to
66 // regenerate the certificate
67 if !key_path.exists() || !cert_path.exists() {
68 debug!(
69 "Generating a new keypair in {:?}, it didn't exist",
70 &key_path
71 );
72 let keypair = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
73 std::fs::write(&key_path, keypair.serialize_pem())?;
74 debug!(
75 "Generating a new certificate for key {:?} at {:?}",
76 &key_path, &cert_path
77 );
78
79 // Configure the certificate we want.
80 let subject_alt_names = vec!["cln".to_string(), "localhost".to_string()];
81 let mut params = rcgen::CertificateParams::new(subject_alt_names);
82 params.key_pair = Some(keypair);
83 params.alg = &rcgen::PKCS_ECDSA_P256_SHA256;
84 if parent.is_none() {
85 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
86 } else {
87 params.is_ca = rcgen::IsCa::SelfSignedOnly;
88 }
89 params
90 .distinguished_name
91 .push(rcgen::DnType::CommonName, name);
92
93 let cert = Certificate::from_params(params)?;
94 std::fs::write(
95 &cert_path,
96 match parent {
97 None => cert.serialize_pem()?,
98 Some(ca) => cert.serialize_pem_with_signer(&ca.to_certificate()?)?,
99 },
100 )
101 .context("writing certificate to file")?;
102 }
103
104 let key = std::fs::read(&key_path)?;
105 let certificate = std::fs::read(cert_path)?;
106 Ok(Identity { certificate, key })
107}

Callers 1

initFunction · 0.85

Calls 2

joinMethod · 0.80
to_certificateMethod · 0.80

Tested by

no test coverage detected