serai/coins/monero/src/wallet/address.rs

326 lines
9.3 KiB
Rust
Raw Normal View History

use core::{marker::PhantomData, fmt};
use std_shims::string::ToString;
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
use zeroize::Zeroize;
use curve25519_dalek::edwards::EdwardsPoint;
use monero_generators::decompress_point;
use base58_monero::base58::{encode_check, decode_check};
/// The network this address is for.
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
pub enum Network {
Mainnet,
Testnet,
2022-07-15 05:26:07 +00:00
Stagenet,
}
/// The address type, supporting the officially documented addresses, along with
/// [Featured Addresses](https://gist.github.com/kayabaNerve/01c50bbc35441e0bbdcee63a9d823789).
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
pub enum AddressType {
Standard,
Integrated([u8; 8]),
2022-07-15 05:26:07 +00:00
Subaddress,
Featured { subaddress: bool, payment_id: Option<[u8; 8]>, guaranteed: bool },
}
2023-01-07 09:44:23 +00:00
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
pub struct SubaddressIndex {
pub(crate) account: u32,
pub(crate) address: u32,
}
impl SubaddressIndex {
pub const fn new(account: u32, address: u32) -> Option<SubaddressIndex> {
if (account == 0) && (address == 0) {
return None;
}
Some(SubaddressIndex { account, address })
}
pub fn account(&self) -> u32 {
self.account
}
pub fn address(&self) -> u32 {
self.address
}
}
Squashed commit of the following: commit e0a9e8825d6c22c797fb84e26ed6ef10136ca9c2 Author: Luke Parker <lukeparker5132@gmail.com> Date: Fri Jan 6 04:24:08 2023 -0500 Remove Scanner::address It either needed to return an Option, panic on misconfiguration, or return a distinct Scanner type based on burning bug immunity to offer this API properly. Panicking wouldn't be proper, and the Option<Address> would've been... awkward. The new register_subaddress function, maintaining the needed functionality, also provides further clarity on the intended side effect of the previously present Scanner::address function. commit 7359360ab2fc8c9255c6f58250c214252ce217a4 Author: Luke Parker <lukeparker5132@gmail.com> Date: Fri Jan 6 01:35:02 2023 -0500 fmt/clippy from last commit commit 80d912fc19cd268f3b019a9d9961a48b2c45e828 Author: Luke Parker <lukeparker5132@gmail.com> Date: Thu Jan 5 19:36:49 2023 -0500 Add Substrate "assets" pallet While over-engineered for our purposes, it's still usable. Also cleans the runtime a bit. commit 2ed2944b6598d75bdc3c995aaf39b717846207de Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 23:09:58 2023 -0500 Remove the timestamp pallet It was needed for contracts, which has since been removed. We now no longer need it. commit 7fc1fc2dccecebe1d94cb7b4c00f2b5cb271c87b Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 22:52:41 2023 -0500 Initial validator sets pallet (#187) * Initial work on a Validator Sets pallet * Update Validator Set docs per current discussions * Update validator-sets primitives and storage handling * Add validator set pallets to deny.toml * Remove Curve from primitives Since we aren't reusing keys across coins, there's no reason for it to be on-chain (as previously planned). * Update documentation on Validator Sets * Use Twox64Concat instead of Identity Ensures an even distribution of keys. While xxhash is breakable, these keys aren't manipulatable by users. * Add math ops on Amount and define a coin as 1e8 * Add validator-sets to the runtime and remove contracts Also removes the randomness pallet which was only required by the contracts runtime. Does not remove the contracts folder yet so they can still be referred to while validator-sets is under development. Does remove them from Cargo.toml. * Add vote function to validator-sets * Remove contracts folder * Create an event for the Validator Sets pallet * Remove old contracts crates from deny.toml * Remove line from staking branch * Remove staking from runtime * Correct VS Config in runtime * cargo update * Resolve a few PR comments on terminology * Create a serai-primitives crate Move types such as Amount/Coin out of validator-sets. Will be expanded in the future. * Fixes for last commit * Don't reserve set 0 * Further fixes * Add files meant for last commit * Remove Staking transfer commit 3309295911d22177bd68972d138aea2f8658eb5f Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 06:17:00 2023 -0500 Reorder coins in README by market cap commit db5d19cad33ccf067d876b7f5b7cca47c228e2fc Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 06:07:58 2023 -0500 Update README commit 606484d744b1c6cc408382994c77f1def25d3e7d Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 03:17:36 2023 -0500 cargo update commit 3a319b229fabd110cc28e5cc0cf718aa88b908bf Author: akildemir <aeg_asd@hotmail.com> Date: Wed Jan 4 16:26:25 2023 +0300 update address public API design commit d9fa88fa76eb361da79f81a1f7758ad19432aca7 Author: akildemir <aeg_asd@hotmail.com> Date: Mon Jan 2 13:35:06 2023 +0300 fix clippy error commit cc722e897b34afc1e517ece2fc5020d190d97804 Merge: cafa9b3 eeca440 Author: akildemir <aeg_asd@hotmail.com> Date: Mon Jan 2 11:39:04 2023 +0300 Merge https://github.com/serai-dex/serai into develop commit cafa9b361e16a37981d45bf3031573c7bc48c5a0 Author: akildemir <aeg_asd@hotmail.com> Date: Mon Jan 2 11:38:26 2023 +0300 fix build errors commit ce5b5f2b37e7cc5a8ca84cbe64e3cefdbf0fe104 Merge: f502d67 49c4acf Author: akildemir <aeg_asd@hotmail.com> Date: Sun Jan 1 15:16:25 2023 +0300 Merge https://github.com/serai-dex/serai into develop commit f502d67282fe4951e3756f041e240c089a945a85 Author: akildemir <aeg_asd@hotmail.com> Date: Thu Dec 22 13:13:09 2022 +0300 fix pr issues commit 26ffb226d457ebf0d2f222c4ee6608971b4a8ffc Author: akildemir <aeg_asd@hotmail.com> Date: Thu Dec 22 13:11:43 2022 +0300 remove extraneous rpc call commit 0e829f853151c06c54d9077b2477e59ac7a1e6e4 Author: akildemir <aeg_asd@hotmail.com> Date: Thu Dec 15 13:56:53 2022 +0300 add scan tests commit 5123c7f121a6823d5e03eeae7eff024a6b6d38c8 Author: akildemir <aeg_asd@hotmail.com> Date: Thu Dec 15 13:56:13 2022 +0300 add new address functions & comments
2023-01-06 09:33:17 +00:00
/// Address specification. Used internally to create addresses.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
pub enum AddressSpec {
Standard,
Integrated([u8; 8]),
2023-01-07 09:44:23 +00:00
Subaddress(SubaddressIndex),
Featured { subaddress: Option<SubaddressIndex>, payment_id: Option<[u8; 8]>, guaranteed: bool },
Squashed commit of the following: commit e0a9e8825d6c22c797fb84e26ed6ef10136ca9c2 Author: Luke Parker <lukeparker5132@gmail.com> Date: Fri Jan 6 04:24:08 2023 -0500 Remove Scanner::address It either needed to return an Option, panic on misconfiguration, or return a distinct Scanner type based on burning bug immunity to offer this API properly. Panicking wouldn't be proper, and the Option<Address> would've been... awkward. The new register_subaddress function, maintaining the needed functionality, also provides further clarity on the intended side effect of the previously present Scanner::address function. commit 7359360ab2fc8c9255c6f58250c214252ce217a4 Author: Luke Parker <lukeparker5132@gmail.com> Date: Fri Jan 6 01:35:02 2023 -0500 fmt/clippy from last commit commit 80d912fc19cd268f3b019a9d9961a48b2c45e828 Author: Luke Parker <lukeparker5132@gmail.com> Date: Thu Jan 5 19:36:49 2023 -0500 Add Substrate "assets" pallet While over-engineered for our purposes, it's still usable. Also cleans the runtime a bit. commit 2ed2944b6598d75bdc3c995aaf39b717846207de Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 23:09:58 2023 -0500 Remove the timestamp pallet It was needed for contracts, which has since been removed. We now no longer need it. commit 7fc1fc2dccecebe1d94cb7b4c00f2b5cb271c87b Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 22:52:41 2023 -0500 Initial validator sets pallet (#187) * Initial work on a Validator Sets pallet * Update Validator Set docs per current discussions * Update validator-sets primitives and storage handling * Add validator set pallets to deny.toml * Remove Curve from primitives Since we aren't reusing keys across coins, there's no reason for it to be on-chain (as previously planned). * Update documentation on Validator Sets * Use Twox64Concat instead of Identity Ensures an even distribution of keys. While xxhash is breakable, these keys aren't manipulatable by users. * Add math ops on Amount and define a coin as 1e8 * Add validator-sets to the runtime and remove contracts Also removes the randomness pallet which was only required by the contracts runtime. Does not remove the contracts folder yet so they can still be referred to while validator-sets is under development. Does remove them from Cargo.toml. * Add vote function to validator-sets * Remove contracts folder * Create an event for the Validator Sets pallet * Remove old contracts crates from deny.toml * Remove line from staking branch * Remove staking from runtime * Correct VS Config in runtime * cargo update * Resolve a few PR comments on terminology * Create a serai-primitives crate Move types such as Amount/Coin out of validator-sets. Will be expanded in the future. * Fixes for last commit * Don't reserve set 0 * Further fixes * Add files meant for last commit * Remove Staking transfer commit 3309295911d22177bd68972d138aea2f8658eb5f Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 06:17:00 2023 -0500 Reorder coins in README by market cap commit db5d19cad33ccf067d876b7f5b7cca47c228e2fc Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 06:07:58 2023 -0500 Update README commit 606484d744b1c6cc408382994c77f1def25d3e7d Author: Luke Parker <lukeparker5132@gmail.com> Date: Wed Jan 4 03:17:36 2023 -0500 cargo update commit 3a319b229fabd110cc28e5cc0cf718aa88b908bf Author: akildemir <aeg_asd@hotmail.com> Date: Wed Jan 4 16:26:25 2023 +0300 update address public API design commit d9fa88fa76eb361da79f81a1f7758ad19432aca7 Author: akildemir <aeg_asd@hotmail.com> Date: Mon Jan 2 13:35:06 2023 +0300 fix clippy error commit cc722e897b34afc1e517ece2fc5020d190d97804 Merge: cafa9b3 eeca440 Author: akildemir <aeg_asd@hotmail.com> Date: Mon Jan 2 11:39:04 2023 +0300 Merge https://github.com/serai-dex/serai into develop commit cafa9b361e16a37981d45bf3031573c7bc48c5a0 Author: akildemir <aeg_asd@hotmail.com> Date: Mon Jan 2 11:38:26 2023 +0300 fix build errors commit ce5b5f2b37e7cc5a8ca84cbe64e3cefdbf0fe104 Merge: f502d67 49c4acf Author: akildemir <aeg_asd@hotmail.com> Date: Sun Jan 1 15:16:25 2023 +0300 Merge https://github.com/serai-dex/serai into develop commit f502d67282fe4951e3756f041e240c089a945a85 Author: akildemir <aeg_asd@hotmail.com> Date: Thu Dec 22 13:13:09 2022 +0300 fix pr issues commit 26ffb226d457ebf0d2f222c4ee6608971b4a8ffc Author: akildemir <aeg_asd@hotmail.com> Date: Thu Dec 22 13:11:43 2022 +0300 remove extraneous rpc call commit 0e829f853151c06c54d9077b2477e59ac7a1e6e4 Author: akildemir <aeg_asd@hotmail.com> Date: Thu Dec 15 13:56:53 2022 +0300 add scan tests commit 5123c7f121a6823d5e03eeae7eff024a6b6d38c8 Author: akildemir <aeg_asd@hotmail.com> Date: Thu Dec 15 13:56:13 2022 +0300 add new address functions & comments
2023-01-06 09:33:17 +00:00
}
impl AddressType {
pub fn is_subaddress(&self) -> bool {
matches!(self, AddressType::Subaddress) ||
matches!(self, AddressType::Featured { subaddress: true, .. })
}
pub fn payment_id(&self) -> Option<[u8; 8]> {
if let AddressType::Integrated(id) = self {
Some(*id)
} else if let AddressType::Featured { payment_id, .. } = self {
*payment_id
} else {
None
}
}
pub fn is_guaranteed(&self) -> bool {
matches!(self, AddressType::Featured { guaranteed: true, .. })
}
}
/// A type which returns the byte for a given address.
pub trait AddressBytes: Clone + Copy + PartialEq + Eq + fmt::Debug {
fn network_bytes(network: Network) -> (u8, u8, u8, u8);
}
/// Address bytes for Monero.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct MoneroAddressBytes;
impl AddressBytes for MoneroAddressBytes {
fn network_bytes(network: Network) -> (u8, u8, u8, u8) {
match network {
Network::Mainnet => (18, 19, 42, 70),
Network::Testnet => (53, 54, 63, 111),
Network::Stagenet => (24, 25, 36, 86),
}
}
}
/// Address metadata.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct AddressMeta<B: AddressBytes> {
_bytes: PhantomData<B>,
pub network: Network,
pub kind: AddressType,
}
impl<B: AddressBytes> Zeroize for AddressMeta<B> {
fn zeroize(&mut self) {
self.network.zeroize();
self.kind.zeroize();
}
}
/// Error when decoding an address.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
pub enum AddressError {
#[cfg_attr(feature = "std", error("invalid address byte"))]
InvalidByte,
#[cfg_attr(feature = "std", error("invalid address encoding"))]
InvalidEncoding,
#[cfg_attr(feature = "std", error("invalid length"))]
InvalidLength,
#[cfg_attr(feature = "std", error("invalid key"))]
2022-07-15 05:26:07 +00:00
InvalidKey,
#[cfg_attr(feature = "std", error("unknown features"))]
UnknownFeatures,
#[cfg_attr(feature = "std", error("different network than expected"))]
DifferentNetwork,
}
impl<B: AddressBytes> AddressMeta<B> {
#[allow(clippy::wrong_self_convention)]
fn to_byte(&self) -> u8 {
let bytes = B::network_bytes(self.network);
match self.kind {
AddressType::Standard => bytes.0,
AddressType::Integrated(_) => bytes.1,
2022-07-15 05:26:07 +00:00
AddressType::Subaddress => bytes.2,
AddressType::Featured { .. } => bytes.3,
}
}
/// Create an address's metadata.
pub fn new(network: Network, kind: AddressType) -> Self {
AddressMeta { _bytes: PhantomData, network, kind }
}
// Returns an incomplete instantiation in the case of Integrated/Featured addresses
fn from_byte(byte: u8) -> Result<Self, AddressError> {
let mut meta = None;
for network in [Network::Mainnet, Network::Testnet, Network::Stagenet] {
let (standard, integrated, subaddress, featured) = B::network_bytes(network);
if let Some(kind) = match byte {
_ if byte == standard => Some(AddressType::Standard),
_ if byte == integrated => Some(AddressType::Integrated([0; 8])),
_ if byte == subaddress => Some(AddressType::Subaddress),
_ if byte == featured => {
Some(AddressType::Featured { subaddress: false, payment_id: None, guaranteed: false })
}
2022-07-15 05:26:07 +00:00
_ => None,
} {
meta = Some(AddressMeta::new(network, kind));
break;
}
}
meta.ok_or(AddressError::InvalidByte)
}
pub fn is_subaddress(&self) -> bool {
self.kind.is_subaddress()
}
pub fn payment_id(&self) -> Option<[u8; 8]> {
self.kind.payment_id()
}
pub fn is_guaranteed(&self) -> bool {
self.kind.is_guaranteed()
}
}
/// A Monero address, composed of metadata and a spend/view key.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Address<B: AddressBytes> {
pub meta: AddressMeta<B>,
pub spend: EdwardsPoint,
2022-07-15 05:26:07 +00:00
pub view: EdwardsPoint,
}
impl<B: AddressBytes> fmt::Debug for Address<B> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
fmt
.debug_struct("Address")
.field("meta", &self.meta)
.field("spend", &hex::encode(self.spend.compress().0))
.field("view", &hex::encode(self.view.compress().0))
// This is not a real field yet is the most valuable thing to know when debugging
.field("(address)", &self.to_string())
.finish()
}
}
impl<B: AddressBytes> Zeroize for Address<B> {
fn zeroize(&mut self) {
self.meta.zeroize();
self.spend.zeroize();
self.view.zeroize();
}
}
impl<B: AddressBytes> fmt::Display for Address<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut data = vec![self.meta.to_byte()];
data.extend(self.spend.compress().to_bytes());
data.extend(self.view.compress().to_bytes());
if let AddressType::Featured { subaddress, payment_id, guaranteed } = self.meta.kind {
// Technically should be a VarInt, yet we don't have enough features it's needed
data.push(
2022-09-17 08:35:08 +00:00
u8::from(subaddress) + (u8::from(payment_id.is_some()) << 1) + (u8::from(guaranteed) << 2),
);
}
if let Some(id) = self.meta.kind.payment_id() {
data.extend(id);
}
write!(f, "{}", encode_check(&data).unwrap())
}
}
impl<B: AddressBytes> Address<B> {
pub fn new(meta: AddressMeta<B>, spend: EdwardsPoint, view: EdwardsPoint) -> Self {
Address { meta, spend, view }
}
pub fn from_str_raw(s: &str) -> Result<Self, AddressError> {
let raw = decode_check(s).map_err(|_| AddressError::InvalidEncoding)?;
if raw.len() < (1 + 32 + 32) {
Err(AddressError::InvalidLength)?;
}
let mut meta = AddressMeta::from_byte(raw[0])?;
let spend =
decompress_point(raw[1 .. 33].try_into().unwrap()).ok_or(AddressError::InvalidKey)?;
let view =
decompress_point(raw[33 .. 65].try_into().unwrap()).ok_or(AddressError::InvalidKey)?;
let mut read = 65;
if matches!(meta.kind, AddressType::Featured { .. }) {
if raw[read] >= (2 << 3) {
Err(AddressError::UnknownFeatures)?;
}
let subaddress = (raw[read] & 1) == 1;
let integrated = ((raw[read] >> 1) & 1) == 1;
let guaranteed = ((raw[read] >> 2) & 1) == 1;
meta.kind = AddressType::Featured {
subaddress,
payment_id: Some([0; 8]).filter(|_| integrated),
guaranteed,
};
read += 1;
}
// Update read early so we can verify the length
if meta.kind.payment_id().is_some() {
read += 8;
}
if raw.len() != read {
Err(AddressError::InvalidLength)?;
}
if let AddressType::Integrated(ref mut id) = meta.kind {
id.copy_from_slice(&raw[(read - 8) .. read]);
}
if let AddressType::Featured { payment_id: Some(ref mut id), .. } = meta.kind {
id.copy_from_slice(&raw[(read - 8) .. read]);
}
Ok(Address { meta, spend, view })
}
pub fn from_str(network: Network, s: &str) -> Result<Self, AddressError> {
Self::from_str_raw(s).and_then(|addr| {
if addr.meta.network == network {
Ok(addr)
} else {
Err(AddressError::DifferentNetwork)?
}
})
}
pub fn network(&self) -> Network {
self.meta.network
}
pub fn is_subaddress(&self) -> bool {
self.meta.is_subaddress()
}
pub fn payment_id(&self) -> Option<[u8; 8]> {
self.meta.payment_id()
}
pub fn is_guaranteed(&self) -> bool {
self.meta.is_guaranteed()
}
}
/// Instantiation of the Address type with Monero's network bytes.
pub type MoneroAddress = Address<MoneroAddressBytes>;
// Allow re-interpreting of an arbitrary address as a monero address so it can be used with the
// rest of this library. Doesn't use From as it was conflicting with From<T> for T.
impl MoneroAddress {
pub fn from<B: AddressBytes>(address: Address<B>) -> MoneroAddress {
MoneroAddress::new(
AddressMeta::new(address.meta.network, address.meta.kind),
address.spend,
address.view,
)
}
}