invoice/network.rs
1// Modern, minimalistic & standard-compliant cold wallet library.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Written in 2020-2024 by
6// Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
7//
8// Copyright (C) 2020-2024 LNP/BP Standards Association. All rights reserved.
9// Copyright (C) 2020-2024 Dr Maxim Orlovsky. All rights reserved.
10//
11// Licensed under the Apache License, Version 2.0 (the "License");
12// you may not use this file except in compliance with the License.
13// You may obtain a copy of the License at
14//
15// http://www.apache.org/licenses/LICENSE-2.0
16//
17// Unless required by applicable law or agreed to in writing, software
18// distributed under the License is distributed on an "AS IS" BASIS,
19// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20// See the License for the specific language governing permissions and
21// limitations under the License.
22
23use std::str::FromStr;
24
25use crate::AddressNetwork;
26
27/// Bitcoin network used by the address
28#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display)]
29#[cfg_attr(
30 feature = "serde",
31 derive(serde::Serialize, serde::Deserialize),
32 serde(crate = "serde_crate", rename_all = "camelCase",)
33)]
34#[display(lowercase)]
35pub enum Network {
36 /// Bitcoin mainnet
37 #[display("bitcoin")]
38 Mainnet,
39
40 /// Bitcoin testnet3
41 Testnet3,
42
43 /// Bitcoin testnet4
44 Testnet4,
45
46 /// Bitcoin signet
47 Signet,
48
49 /// Bitcoin regtest networks
50 Regtest,
51}
52
53impl Network {
54 /// Detects whether the network is a kind of test network (testnet, signet,
55 /// regtest).
56 pub fn is_testnet(self) -> bool { self != Self::Mainnet }
57}
58
59impl From<Network> for AddressNetwork {
60 fn from(network: Network) -> Self {
61 match network {
62 Network::Mainnet => AddressNetwork::Mainnet,
63 Network::Testnet3 | Network::Testnet4 | Network::Signet => AddressNetwork::Testnet,
64 Network::Regtest => AddressNetwork::Regtest,
65 }
66 }
67}
68
69#[derive(Clone, Eq, PartialEq, Debug, Display, Error)]
70#[display("unknown bitcoin network '{0}'")]
71pub struct UnknownNetwork(pub String);
72
73impl FromStr for Network {
74 type Err = UnknownNetwork;
75
76 fn from_str(s: &str) -> Result<Self, Self::Err> {
77 Ok(match s {
78 "bitcoin" | "mainnet" => Network::Mainnet,
79 "testnet" | "testnet3" => Network::Testnet3,
80 "testnet4" => Network::Testnet4,
81 "signet" => Network::Signet,
82 "regtest" => Network::Regtest,
83 other => return Err(UnknownNetwork(other.to_owned())),
84 })
85 }
86}