-
Notifications
You must be signed in to change notification settings - Fork 366
/
nonce.rs
79 lines (65 loc) · 2.19 KB
/
nonce.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! A number used only once.
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::*;
/// A 128-bit number used only once.
///
/// Needed when constructing [`Offer::metadata`] and deriving [`Offer::issuer_signing_pubkey`] from
/// [`ExpandedKey`]. Must not be reused for any other derivation without first hashing.
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::issuer_signing_pubkey`]: crate::offers::offer::Offer::issuer_signing_pubkey
/// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Nonce(pub(crate) [u8; Self::LENGTH]);
impl Nonce {
/// Number of bytes in the nonce.
pub const LENGTH: usize = 16;
/// Creates a `Nonce` from the given [`EntropySource`].
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)
}
/// Returns a slice of the underlying bytes of size [`Nonce::LENGTH`].
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)?))
}
}