1#![warn(
2 missing_debug_implementations,
3 missing_docs,
4 rust_2018_idioms,
5 unreachable_pub
6)]
7
8pub mod bip32;
14pub mod prelude;
15pub mod transaction;
16pub mod var_int;
17
18use std::convert::TryFrom;
19
20use bytes::{Buf, BufMut};
21use serde::{Deserialize, Serialize};
22use thiserror::Error;
23
24#[derive(Clone, Debug, PartialEq, Eq, Error)]
26#[error("buffer has insufficient capacity")]
27pub struct InsufficientCapacity;
28
29pub trait Encodable: Sized {
31 fn encoded_len(&self) -> usize;
33
34 #[inline]
36 fn encode<B: BufMut>(&self, buf: &mut B) -> Result<(), InsufficientCapacity> {
37 if buf.remaining_mut() < self.encoded_len() {
38 return Err(InsufficientCapacity);
39 }
40 self.encode_raw(buf);
41 Ok(())
42 }
43
44 fn encode_raw<B: BufMut>(&self, buf: &mut B);
46}
47
48pub trait Decodable: Sized {
50 type Error;
52
53 fn decode<B: Buf>(buf: &mut B) -> Result<Self, Self::Error>;
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
59#[serde(rename_all = "lowercase")]
60pub enum Network {
61 Mainnet,
63 Testnet,
65 Regtest,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq, Error)]
71#[error("unexpected network given")]
72pub struct UnexpectedNetwork;
73
74impl TryFrom<String> for Network {
75 type Error = UnexpectedNetwork;
76
77 fn try_from(network: String) -> Result<Self, Self::Error> {
78 match network.as_str() {
79 "mainnet" => Ok(Self::Mainnet),
80 "testnet" => Ok(Self::Testnet),
81 "regtest" => Ok(Self::Regtest),
82 _ => Err(UnexpectedNetwork),
83 }
84 }
85}
86
87impl Into<String> for Network {
88 fn into(self) -> String {
89 match self {
90 Self::Mainnet => "mainnet".to_string(),
91 Self::Testnet => "testnet".to_string(),
92 Self::Regtest => "regtest".to_string(),
93 }
94 }
95}
96
97impl std::string::ToString for Network {
98 fn to_string(&self) -> String {
99 match self {
100 Self::Mainnet => "mainnet".to_string(),
101 Self::Testnet => "testnet".to_string(),
102 Self::Regtest => "regtest".to_string(),
103 }
104 }
105}