use crate::io::{self, Read};
use crate::ln::msgs::DecodeError;
use crate::sign::EntropySource;
use crate::util::ser::{Readable, Writeable, Writer};
use core::ops::Deref;
#[allow(unused_imports)]
use crate::prelude::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Nonce(pub(crate) [u8; Self::LENGTH]);
impl Nonce {
pub const LENGTH: usize = 16;
pub fn from_entropy_source<ES: Deref>(entropy_source: ES) -> Self
where
ES::Target: EntropySource,
{
let mut bytes = [0u8; Self::LENGTH];
let rand_bytes = entropy_source.get_secure_random_bytes();
bytes.copy_from_slice(&rand_bytes[..Self::LENGTH]);
Nonce(bytes)
}
pub fn as_slice(&self) -> &[u8] {
&self.0
}
}
impl TryFrom<&[u8]> for Nonce {
type Error = ();
fn try_from(bytes: &[u8]) -> Result<Self, ()> {
if bytes.len() != Self::LENGTH {
return Err(());
}
let mut copied_bytes = [0u8; Self::LENGTH];
copied_bytes.copy_from_slice(bytes);
Ok(Self(copied_bytes))
}
}
impl Writeable for Nonce {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
self.0.write(w)
}
}
impl Readable for Nonce {
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
Ok(Nonce(Readable::read(r)?))
}
}