Skip to content

Commit accfdae

Browse files
authored
Merge pull request #2180 from benthecarman/impl-pk-to-node-id
Implement to and from for PublicKey and NodeId
2 parents b3ab1cb + 7a37e2c commit accfdae

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

lightning/src/routing/gossip.rs

+31
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use bitcoin::secp256k1;
1616

1717
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1818
use bitcoin::hashes::Hash;
19+
use bitcoin::hashes::hex::FromHex;
1920
use bitcoin::hash_types::BlockHash;
2021

2122
use bitcoin::network::constants::Network;
@@ -38,11 +39,13 @@ use crate::io;
3839
use crate::io_extras::{copy, sink};
3940
use crate::prelude::*;
4041
use core::{cmp, fmt};
42+
use core::convert::TryFrom;
4143
use crate::sync::{RwLock, RwLockReadGuard};
4244
#[cfg(feature = "std")]
4345
use core::sync::atomic::{AtomicUsize, Ordering};
4446
use crate::sync::Mutex;
4547
use core::ops::{Bound, Deref};
48+
use core::str::FromStr;
4649

4750
#[cfg(feature = "std")]
4851
use std::time::{SystemTime, UNIX_EPOCH};
@@ -76,6 +79,11 @@ impl NodeId {
7679
pub fn as_slice(&self) -> &[u8] {
7780
&self.0
7881
}
82+
83+
/// Get the public key from this NodeId
84+
pub fn as_pubkey(&self) -> Result<PublicKey, secp256k1::Error> {
85+
PublicKey::from_slice(&self.0)
86+
}
7987
}
8088

8189
impl fmt::Debug for NodeId {
@@ -130,6 +138,29 @@ impl Readable for NodeId {
130138
}
131139
}
132140

141+
impl From<PublicKey> for NodeId {
142+
fn from(pubkey: PublicKey) -> Self {
143+
Self::from_pubkey(&pubkey)
144+
}
145+
}
146+
147+
impl TryFrom<NodeId> for PublicKey {
148+
type Error = secp256k1::Error;
149+
150+
fn try_from(node_id: NodeId) -> Result<Self, Self::Error> {
151+
node_id.as_pubkey()
152+
}
153+
}
154+
155+
impl FromStr for NodeId {
156+
type Err = bitcoin::hashes::hex::Error;
157+
158+
fn from_str(s: &str) -> Result<Self, Self::Err> {
159+
let data: [u8; PUBLIC_KEY_SIZE] = FromHex::from_hex(s)?;
160+
Ok(NodeId(data))
161+
}
162+
}
163+
133164
/// Represents the network as nodes and channels between them
134165
pub struct NetworkGraph<L: Deref> where L::Target: Logger {
135166
secp_ctx: Secp256k1<secp256k1::VerifyOnly>,

0 commit comments

Comments
 (0)