|
3 | 3 | use alloc::string::String; |
4 | 4 | use alloc::vec::Vec; |
5 | 5 | use core::fmt; |
| 6 | +use core::str::FromStr; |
6 | 7 |
|
7 | 8 | use bitcoin_hashes::{hash160, Hash}; |
8 | 9 | use secp256k1::{PublicKey, Secp256k1}; |
@@ -97,7 +98,39 @@ impl Address { |
97 | 98 | } |
98 | 99 |
|
99 | 100 | /// Parse an address from a string (network is inferred from version byte) |
100 | | - pub fn from_str(s: &str) -> Result<Self> { |
| 101 | + pub fn from_string(s: &str) -> Result<Self> { |
| 102 | + s.parse() |
| 103 | + } |
| 104 | + |
| 105 | + /// Get the script pubkey for this address |
| 106 | + pub fn script_pubkey(&self) -> Vec<u8> { |
| 107 | + match self.address_type { |
| 108 | + AddressType::P2PKH => { |
| 109 | + let mut script = Vec::with_capacity(25); |
| 110 | + script.push(0x76); // OP_DUP |
| 111 | + script.push(0xa9); // OP_HASH160 |
| 112 | + script.push(0x14); // Push 20 bytes |
| 113 | + script.extend_from_slice(&self.hash[..]); |
| 114 | + script.push(0x88); // OP_EQUALVERIFY |
| 115 | + script.push(0xac); // OP_CHECKSIG |
| 116 | + script |
| 117 | + } |
| 118 | + AddressType::P2SH => { |
| 119 | + let mut script = Vec::with_capacity(23); |
| 120 | + script.push(0xa9); // OP_HASH160 |
| 121 | + script.push(0x14); // Push 20 bytes |
| 122 | + script.extend_from_slice(&self.hash[..]); |
| 123 | + script.push(0x87); // OP_EQUAL |
| 124 | + script |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +impl FromStr for Address { |
| 131 | + type Err = Error; |
| 132 | + |
| 133 | + fn from_str(s: &str) -> Result<Self> { |
101 | 134 | let data = base58ck::decode_check(s) |
102 | 135 | .map_err(|_| Error::InvalidAddress("Invalid base58 encoding".into()))?; |
103 | 136 |
|
@@ -132,30 +165,6 @@ impl Address { |
132 | 165 | hash, |
133 | 166 | }) |
134 | 167 | } |
135 | | - |
136 | | - /// Get the script pubkey for this address |
137 | | - pub fn script_pubkey(&self) -> Vec<u8> { |
138 | | - match self.address_type { |
139 | | - AddressType::P2PKH => { |
140 | | - let mut script = Vec::with_capacity(25); |
141 | | - script.push(0x76); // OP_DUP |
142 | | - script.push(0xa9); // OP_HASH160 |
143 | | - script.push(0x14); // Push 20 bytes |
144 | | - script.extend_from_slice(&self.hash[..]); |
145 | | - script.push(0x88); // OP_EQUALVERIFY |
146 | | - script.push(0xac); // OP_CHECKSIG |
147 | | - script |
148 | | - } |
149 | | - AddressType::P2SH => { |
150 | | - let mut script = Vec::with_capacity(23); |
151 | | - script.push(0xa9); // OP_HASH160 |
152 | | - script.push(0x14); // Push 20 bytes |
153 | | - script.extend_from_slice(&self.hash[..]); |
154 | | - script.push(0x87); // OP_EQUAL |
155 | | - script |
156 | | - } |
157 | | - } |
158 | | - } |
159 | 168 | } |
160 | 169 |
|
161 | 170 | impl fmt::Display for Address { |
|
0 commit comments