Skip to content

Commit

Permalink
Merge pull request #29 from diba-io/verify-key
Browse files Browse the repository at this point in the history
Nostr Key Decoding
  • Loading branch information
rustchain64 authored Mar 2, 2024
2 parents ba836bf + 95e9039 commit b00096f
Show file tree
Hide file tree
Showing 9 changed files with 155 additions and 22 deletions.
7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "carbonado"
version = "0.3.6"
version = "0.4.1"
edition = "2021"
license = "MIT"
description = "An apocalypse-resistant data storage format for the truly paranoid."
Expand All @@ -11,7 +11,8 @@ include = ["src/**/*", "LICENSE", "README.md"]

[dependencies]
bao = "0.12.1"
bech32 = "0.9.1"
bech32 = "0.11.0"
blake3 = "1.5.0"
bitmask-enum = "2.1.0"
bytes = "1.4.0"
ecies = { version = "0.2.6", default-features = false, features = [
Expand All @@ -22,6 +23,8 @@ hex = "0.4.3"
libsecp256k1 = { version = "0.7.1", features = ["std"] }
log = "0.4.19"
nom = "7.1.3"
nostr = "0.28.1"
nostr-sdk = "0.28.0"
pretty_env_logger = "0.5.0"
secp256k1 = { version = "0.28.0", features = [
"global-context",
Expand Down
2 changes: 1 addition & 1 deletion src/decoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub fn decode(
padding: u32,
format: u8,
) -> Result<Vec<u8>, CarbonadoError> {
let format = Format::try_from(format)?;
let format = Format::from(format);

let verified = if format.contains(Format::Bao) {
bao(input, hash)?
Expand Down
2 changes: 1 addition & 1 deletion src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub fn zfec(input: &[u8]) -> Result<(Vec<u8>, u32, u32), CarbonadoError> {
/// `snap -> ecies -> zfec -> bao`
pub fn encode(pubkey: &[u8], input: &[u8], format: u8) -> Result<Encoded, CarbonadoError> {
let input_len = input.len() as u32;
let format = Format::try_from(format)?;
let format = Format::from(format);

let compressed;
let encrypted;
Expand Down
24 changes: 22 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,17 @@ pub enum CarbonadoError {
#[error(transparent)]
HexDecodeError(#[from] hex::FromHexError),

/// Bech32 error
/// Bech32 encode error
#[error(transparent)]
Bech32Error(#[from] bech32::Error),
Bech32EncodeError(#[from] bech32::EncodeError),

/// Bech32 decode error
#[error(transparent)]
Bech32DecodeError(#[from] bech32::DecodeError),

/// Bech32 hrp error
#[error(transparent)]
Bech32HrpError(#[from] bech32::primitives::hrp::Error),

/// snap error
#[error(transparent)]
Expand All @@ -42,6 +50,14 @@ pub enum CarbonadoError {
#[error(transparent)]
ZfecError(#[from] zfec_rs::Error),

/// nostr secp256k1 error
#[error(transparent)]
NostrSecp256k1Error(#[from] nostr::secp256k1::Error),

/// nostr NIP-19 / Bech32 error
#[error(transparent)]
NostrNip19Error(#[from] nostr::nips::nip19::Error),

/// An uneven number of input bytes were provided for zfec chunks
#[error("Input bytes must divide evenly over number of zfec chunks.")]
UnevenZfecChunks,
Expand Down Expand Up @@ -101,4 +117,8 @@ pub enum CarbonadoError {
/// Invalid header length calculation
#[error("Invalid header length calculation")]
InvalidHeaderLength,

/// Invalid header length calculation
#[error("Incorrect public key format")]
IncorrectPubKeyFormat,
}
18 changes: 9 additions & 9 deletions src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ impl TryFrom<&File> for Header {
// Verify hash against signature
signature.verify(&Message::from_digest_slice(&hash)?, &pubkey)?;

let hash = bao::Hash::try_from(hash)?;
let hash = bao::Hash::from(hash);

let format = Format::try_from(format[0])?;
let format = Format::from(format[0]);
let chunk_index = u8::from_le_bytes(chunk_index);
let encoded_len = u32::from_le_bytes(encoded_len);
let padding_len = u32::from_le_bytes(padding_len);
Expand Down Expand Up @@ -135,9 +135,9 @@ impl TryFrom<&[u8]> for Header {
signature.verify(&Message::from_digest_slice(hash)?, &pubkey)?;

let hash: [u8; 32] = hash[0..32].try_into()?;
let hash = bao::Hash::try_from(hash)?;
let hash = bao::Hash::from(hash);

let format = Format::try_from(format)?;
let format = Format::from(format);

Ok(Header {
pubkey,
Expand Down Expand Up @@ -183,9 +183,9 @@ impl TryFrom<Bytes> for Header {
signature.verify(&Message::from_digest_slice(hash)?, &pubkey)?;

let hash: [u8; 32] = hash[0..32].try_into()?;
let hash = bao::Hash::try_from(hash)?;
let hash = bao::Hash::from(hash);

let format = Format::try_from(format)?;
let format = Format::from(format);

Ok(Header {
pubkey,
Expand Down Expand Up @@ -231,9 +231,9 @@ impl TryFrom<&Bytes> for Header {
signature.verify(&Message::from_digest_slice(hash)?, &pubkey)?;

let hash: [u8; 32] = hash[0..32].try_into()?;
let hash = bao::Hash::try_from(hash)?;
let hash = bao::Hash::from(hash);

let format = Format::try_from(format)?;
let format = Format::from(format);

Ok(Header {
pubkey,
Expand Down Expand Up @@ -416,7 +416,7 @@ pub fn encode(

let Encoded(mut encoded, hash, encode_info) = encoding::encode(&pubkey, input, level)?;

let format = Format::try_from(level)?;
let format = Format::from(level);
let header = Header::new(
sk,
&pubkey,
Expand Down
97 changes: 97 additions & 0 deletions src/structs.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
use std::{
fmt::{self, Display},
str::FromStr,
};

use nostr::{FromBech32, PublicKey};
use serde::{Deserialize, Serialize};

use crate::error::CarbonadoError;

/// Information from the encoding step, some of which is needed for decoding.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct EncodeInfo {
Expand Down Expand Up @@ -38,3 +46,92 @@ pub struct EncodeInfo {
/// Tuple of verifiable bytes, bao hash, and encode info struct
/// i.e., Encoded(encoded_bytes, bao_hash, encode_info)
pub struct Encoded(pub Vec<u8>, pub bao::Hash, pub EncodeInfo);

pub struct Secp256k1PubKey {
pub pk: secp256k1::PublicKey,
pub x_only_pk: [u8; 32],
}

impl TryFrom<&str> for Secp256k1PubKey {
type Error = CarbonadoError;

fn try_from(value: &str) -> Result<Self, Self::Error> {
let pk = match value.get(0..2).expect("key is at least 2 characters long") {
"+n" => secp256k1::PublicKey::from_x_only_public_key(
secp256k1::XOnlyPublicKey::from_slice(
&PublicKey::from_bech32(value.get(1..).unwrap())?.to_bytes(),
)?,
secp256k1::Parity::Even,
),
"-n" => secp256k1::PublicKey::from_x_only_public_key(
secp256k1::XOnlyPublicKey::from_slice(
&PublicKey::from_bech32(value.get(1..).unwrap())?.to_bytes(),
)?,
secp256k1::Parity::Odd,
),
"02" => secp256k1::PublicKey::from_str(value)?,
"03" => secp256k1::PublicKey::from_str(value)?,
_ => return Err(CarbonadoError::IncorrectPubKeyFormat),
};

let (x_only_pk, _) = pk.x_only_public_key();
let x_only_pk = x_only_pk.serialize();

Ok(Self { pk, x_only_pk })
}
}

impl Display for Secp256k1PubKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { pk, .. } = self;

f.write_str(&pk.to_string())
}
}

impl AsRef<[u8; 32]> for Secp256k1PubKey {
fn as_ref(&self) -> &[u8; 32] {
&self.x_only_pk
}
}

impl Secp256k1PubKey {
pub fn new(pk: secp256k1::PublicKey) -> Self {
let (x_only_pk, _) = pk.x_only_public_key();
let x_only_pk = x_only_pk.serialize();

Self { pk, x_only_pk }
}

pub fn to_bytes(&self) -> Vec<u8> {
let Self { pk, .. } = self;

pk.serialize().to_vec()
}

pub fn into_inner(&self) -> secp256k1::PublicKey {
let Self { pk, .. } = self;

pk.to_owned()
}
}

#[test]
fn test_pubkey_decode() {
let result = Secp256k1PubKey::try_from(
"+npub14rnkcwkw0q5lnmjye7ffxvy7yxscyjl3u4mrr5qxsks76zctmz3qvuftjz",
);
assert!(result.is_ok());
assert_eq!(
result.unwrap().to_string(),
"02a8e76c3ace7829f9ee44cf9293309e21a1824bf1e57631d00685a1ed0b0bd8a2"
);
let result = Secp256k1PubKey::try_from(
"-npub14rnkcwkw0q5lnmjye7ffxvy7yxscyjl3u4mrr5qxsks76zctmz3qvuftjz",
);
assert!(result.is_ok());
assert_eq!(
result.unwrap().to_string(),
"03a8e76c3ace7829f9ee44cf9293309e21a1824bf1e57631d00685a1ed0b0bd8a2"
);
}
23 changes: 18 additions & 5 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Once;

use bao::Hash;
use bech32::{decode, encode, FromBase32, ToBase32, Variant};
use bech32::{decode, encode, Bech32m, Hrp};
use log::trace;

use crate::{
Expand Down Expand Up @@ -55,11 +55,24 @@ pub fn calc_padding_len(input_len: usize) -> (u32, u32) {

/// Helper for encoding data to bech32m.
pub fn bech32m_encode(hrp: &str, bytes: &[u8]) -> Result<String, CarbonadoError> {
Ok(encode(hrp, bytes.to_base32(), Variant::Bech32m)?)
Ok(encode::<Bech32m>(Hrp::parse(hrp)?, bytes)?)
}

/// Helper for decoding bech32-encoded data.
pub fn bech32_decode(bech32_str: &str) -> Result<(String, Vec<u8>, Variant), CarbonadoError> {
let (hrp, words, variant) = decode(bech32_str)?;
Ok((hrp, Vec::<u8>::from_base32(&words)?, variant))
pub fn bech32_decode(bech32_str: &str) -> Result<(String, Vec<u8>), CarbonadoError> {
let (hrp, words) = decode(bech32_str)?;
Ok((hrp.to_string(), words))
}

pub fn pub_keyed_hash(ss: &str, bytes: &[u8]) -> Result<String, CarbonadoError> {
let key = hex::decode(ss)?;
let key_bytes: [u8; 32] = key[0..32].try_into()?;
let secp = secp256k1::Secp256k1::new();
let secret_key = secp256k1::SecretKey::from_slice(key_bytes.as_slice())?;
let pk = secret_key.public_key(&secp);
let (pk, _parity) = pk.x_only_public_key();
let pub_keyed_hash = blake3::keyed_hash(&pk.serialize(), bytes)
.to_hex()
.to_string();
Ok(pub_keyed_hash)
}
2 changes: 1 addition & 1 deletion tests/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ fn codec(path: &str) -> Result<()> {
assert_eq!(decoded, input, "Decoded output is same as encoded input");

let carbonado_level = 15;
let format = Format::try_from(carbonado_level)?;
let format = Format::from(carbonado_level);
let header = Header::new(
&sk.secret_bytes(),
&pk.serialize(),
Expand Down
2 changes: 1 addition & 1 deletion tests/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn format() -> Result<()> {

let input = "Hello world!".as_bytes();
let carbonado_level = 15;
let format = Format::try_from(carbonado_level)?;
let format = Format::from(carbonado_level);

let (file_sk, file_pk) = generate_keypair(&mut thread_rng());
let (node_sk, node_pk) = generate_keypair(&mut thread_rng());
Expand Down

0 comments on commit b00096f

Please sign in to comment.