From d24401ada8604dae53c145f6738831adc9362690 Mon Sep 17 00:00:00 2001 From: Sosthene00 <674694@protonmail.ch> Date: Wed, 17 Apr 2024 08:27:46 +0200 Subject: [PATCH] Add AnkSharedSecret --- src/crypto.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/src/crypto.rs b/src/crypto.rs index 3873b1d..71eb324 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -6,26 +6,71 @@ use sp_backend::{ consensus::serde::hex, hex::DisplayHex, key::constants::SECRET_KEY_SIZE, - secp256k1::{ecdh::SharedSecret, SecretKey}, + secp256k1::{ecdh::SharedSecret, PublicKey, SecretKey}, Txid, }, - silentpayments::sending::SilentPaymentAddress, + silentpayments::{ + sending::SilentPaymentAddress, + bitcoin_hashes::{sha256t_hash_newtype, HashEngine, Hash} + }, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use aes_gcm::{ - aead::{Aead, AeadInPlace, KeyInit, Nonce}, - AeadCore, Aes256Gcm, AesGcm, Key, TagSize, - aes::{Aes256, cipher::{generic_array::GenericArray, consts::{U32, U8}}}, + aead::{Aead, AeadInPlace, Nonce}, + aes::{ + cipher::{ + consts::{U32, U8}, + generic_array::GenericArray, + }, + Aes256, + }, + AesGcm, Key, TagSize, }; +pub use aes_gcm::{AeadCore, Aes256Gcm, KeyInit}; use rand::thread_rng; const HALFKEYSIZE: usize = SECRET_KEY_SIZE / 2; const THIRTYTWO: usize = 32; +type SharedPublicKey = PublicKey; + +#[derive(Debug)] +pub struct AnkSharedSecret(SharedSecret); + +impl AnkSharedSecret { + pub fn new_from_public_key(public_key: SharedPublicKey) -> Self { + let t_hash = SharedPublicKeyHash::from_shared_pubkey(public_key); + Self(SharedSecret::from_bytes(t_hash.to_byte_array())) + } + + pub fn to_byte_array(&self) -> [u8;SECRET_KEY_SIZE] { + self.0.secret_bytes() + } + + pub fn to_string(&self) -> String { + format!("{}", self.0.display_secret()) + } +} + +sha256t_hash_newtype! { + pub struct SharedPublicKeyTag = hash_str("4nk/SharedPublicKey"); + + #[hash_newtype(forward)] + pub struct SharedPublicKeyHash(_); +} + +impl SharedPublicKeyHash { + pub fn from_shared_pubkey(shared_pubkey: SharedPublicKey) -> Self { + let mut eng = SharedPublicKeyHash::engine(); + eng.input(&shared_pubkey.serialize()); + SharedPublicKeyHash::from_engine(eng) + } +} + pub struct HalfKey([u8; HALFKEYSIZE]); impl TryFrom> for HalfKey {