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
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// Descriptor wallet library extending bitcoin & miniscript functionality
// by LNP/BP Association (https://lnp-bp.org)
// Written in 2020-2021 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the Apache-2.0 License
// along with this software.
// If not, see <https://opensource.org/licenses/Apache-2.0>.

use std::convert::{TryFrom, TryInto};
use std::fmt::{self, Display, Formatter};
use std::str::FromStr;

use bitcoin::bech32::u5;
use bitcoin::hashes::{hex, Hash};
use bitcoin::secp256k1;
use bitcoin::secp256k1::schnorrsig as bip340;
use bitcoin::util::address::{self, Payload};
use bitcoin::{
    Address, Network, PubkeyHash, Script, ScriptHash, WPubkeyHash, WScriptHash,
};

use crate::{PubkeyScript, WitnessVersion, WitnessVersionError};

/// See also [`bitcoin::Address`] as a non-copy alternative supporting
/// future witness program versions
#[derive(
    Copy,
    Clone,
    Ord,
    PartialOrd,
    Eq,
    PartialEq,
    Hash,
    Debug,
    From,
    StrictEncode,
    StrictDecode,
)]
pub struct AddressCompat {
    pub inner: AddressPayload,
    pub testnet: bool,
}

impl AddressCompat {
    pub fn from_script(
        script: &Script,
        network: bitcoin::Network,
    ) -> Option<Self> {
        Address::from_script(&script, network)
            .ok_or(address::Error::UncompressedPubkey)
            .and_then(Self::try_from)
            .ok()
    }
}

impl From<AddressCompat> for Address {
    fn from(payload: AddressCompat) -> Self {
        payload.inner.into_address(if payload.testnet {
            Network::Testnet
        } else {
            Network::Bitcoin
        })
    }
}

impl TryFrom<Address> for AddressCompat {
    type Error = address::Error;

    fn try_from(address: Address) -> Result<Self, Self::Error> {
        Ok(AddressCompat {
            inner: address.payload.try_into()?,
            testnet: address.network != bitcoin::Network::Bitcoin,
        })
    }
}

impl From<AddressCompat> for PubkeyScript {
    fn from(payload: AddressCompat) -> Self {
        Address::from(payload).script_pubkey().into()
    }
}

impl Display for AddressCompat {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(&Address::from(*self), f)
    }
}

impl FromStr for AddressCompat {
    type Err = address::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Address::from_str(s).and_then(AddressCompat::try_from)
    }
}

/// See also [`descriptor::Compact`] as a non-copy alternative supporting
/// bare/custom scripts
#[derive(
    Copy,
    Clone,
    Ord,
    PartialOrd,
    Eq,
    PartialEq,
    Hash,
    Debug,
    Display,
    From,
    StrictEncode,
    StrictDecode,
)]
pub enum AddressPayload {
    #[from]
    #[display("pkh:{0}")]
    PubkeyHash(PubkeyHash),

    #[from]
    #[display("sh:{0}")]
    ScriptHash(ScriptHash),

    #[from]
    #[display("wpkh:{0}")]
    WPubkeyHash(WPubkeyHash),

    #[from]
    #[display("wsh:{0}")]
    WScriptHash(WScriptHash),

    #[from]
    #[display("pkxo:{0}")]
    Taproot(bip340::PublicKey),
}

impl AddressPayload {
    pub fn into_address(self, network: Network) -> Address {
        Address {
            payload: self.into(),
            network,
        }
    }

    pub fn from_address(address: Address) -> Option<Self> {
        Self::from_payload(address.payload)
    }

    pub fn from_payload(payload: Payload) -> Option<Self> {
        Some(match payload {
            Payload::PubkeyHash(pkh) => AddressPayload::PubkeyHash(pkh),
            Payload::ScriptHash(sh) => AddressPayload::ScriptHash(sh),
            Payload::WitnessProgram { version, program }
                if version.to_u8() == 0 && program.len() == 20 =>
            {
                AddressPayload::WPubkeyHash(
                    WPubkeyHash::from_slice(&program)
                        .expect("WPubkeyHash vec length estimation is broken"),
                )
            }
            Payload::WitnessProgram { version, program }
                if version.to_u8() == 0 && program.len() == 32 =>
            {
                AddressPayload::WScriptHash(
                    WScriptHash::from_slice(&program)
                        .expect("WScriptHash vec length estimation is broken"),
                )
            }
            Payload::WitnessProgram { version, program }
                if version.to_u8() == 1 && program.len() == 32 =>
            {
                AddressPayload::Taproot(
                    bip340::PublicKey::from_slice(&program).expect(
                        "Taproot public key vec length estimation is broken",
                    ),
                )
            }
            _ => return None,
        })
    }

    pub fn from_script(script: &Script) -> Option<Self> {
        Address::from_script(&script, Network::Bitcoin)
            .and_then(Self::from_address)
    }
}

impl From<AddressPayload> for Payload {
    fn from(ap: AddressPayload) -> Self {
        match ap {
            AddressPayload::PubkeyHash(pkh) => Payload::PubkeyHash(pkh),
            AddressPayload::ScriptHash(sh) => Payload::ScriptHash(sh),
            AddressPayload::WPubkeyHash(wpkh) => Payload::WitnessProgram {
                version: u5::try_from_u8(0).unwrap(),
                program: wpkh.to_vec(),
            },
            AddressPayload::WScriptHash(wsh) => Payload::WitnessProgram {
                version: u5::try_from_u8(0).unwrap(),
                program: wsh.to_vec(),
            },
            AddressPayload::Taproot(tr) => Payload::WitnessProgram {
                version: u5::try_from_u8(1).unwrap(),
                program: tr.serialize().to_vec(),
            },
        }
    }
}

impl TryFrom<Payload> for AddressPayload {
    type Error = address::Error;

    fn try_from(payload: Payload) -> Result<Self, Self::Error> {
        Ok(match payload {
            Payload::PubkeyHash(hash) => AddressPayload::PubkeyHash(hash),
            Payload::ScriptHash(hash) => AddressPayload::ScriptHash(hash),
            Payload::WitnessProgram { version, program }
                if version.to_u8() == 0u8 =>
            {
                if program.len() == 32 {
                    AddressPayload::WScriptHash(
                        WScriptHash::from_slice(&program).expect(
                            "WScriptHash is broken: it must be 32 byte len",
                        ),
                    )
                } else if program.len() == 20 {
                    AddressPayload::WPubkeyHash(
                        WPubkeyHash::from_slice(&program).expect(
                            "WScriptHash is broken: it must be 20 byte len",
                        ),
                    )
                } else {
                    panic!(
                        "bitcoin::Address is broken: v0 witness program must be \
                        either 32 or 20 bytes len"
                    )
                }
            }
            Payload::WitnessProgram { version, program }
                if version.to_u8() == 1u8 =>
            {
                if program.len() == 32 {
                    AddressPayload::Taproot(bip340::PublicKey::from_slice(&program).expect(
                        "bip340::PublicKey is broken: it must be 32 byte len",
                    ))
                } else {
                    panic!(
                        "bitcoin::Address is broken: v1 witness program must be \
                        either 32 bytes len"
                    )
                }
            }
            Payload::WitnessProgram { version, .. } => {
                return Err(address::Error::InvalidWitnessVersion(
                    version.to_u8(),
                ))
            }
        })
    }
}

impl From<AddressPayload> for PubkeyScript {
    fn from(ap: AddressPayload) -> Self {
        ap.into_address(Network::Bitcoin).script_pubkey().into()
    }
}

#[derive(
    Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display, Error, From,
)]
#[display(doc_comments)]
pub enum AddressParseError {
    /// unknown address payload prefix `{0}`; expected `pkh`, `sh`, `wpkh`,
    /// `wsh` and `pkxo` only
    UnknownPrefix(String),

    /// unrecognized address payload string format
    UnrecognizedStringFormat,

    /// address payload must be prefixed by pyaload format prefix, indicating
    /// specific form of hash or a public key used inside the address
    PrefixAbsent,

    /// wrong address payload data
    #[from(hex::Error)]
    WrongPayloadHashData,

    /// wrong BIP340 public key (xcoord-only)
    #[from(secp256k1::Error)]
    WrongPublicKeyData,

    /// unrecognized address network string; only `mainnet`, `testnet` and
    /// `regtest` are possible at address level
    UnrecognizedAddressNetwork,

    /// unrecognized address format string; must be one of `P2PKH`, `P2SH`,
    /// `P2WPKH`, `P2WSH`, `P2TR`
    UnrecognizedAddressFormat,

    /// wrong witness version
    #[from(WitnessVersionError)]
    WrongWitnessVersion,
}

impl FromStr for AddressPayload {
    type Err = AddressParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.to_lowercase();
        let mut split = s.split(":");
        Ok(match (split.next(), split.next(), split.next()) {
            (_, _, Some(_)) => {
                return Err(AddressParseError::UnrecognizedStringFormat)
            }
            (Some("pkh"), Some(hash), None) => {
                AddressPayload::PubkeyHash(PubkeyHash::from_str(hash)?)
            }
            (Some("sh"), Some(hash), None) => {
                AddressPayload::ScriptHash(ScriptHash::from_str(hash)?)
            }
            (Some("wpkh"), Some(hash), None) => {
                AddressPayload::WPubkeyHash(WPubkeyHash::from_str(hash)?)
            }
            (Some("wsh"), Some(hash), None) => {
                AddressPayload::WScriptHash(WScriptHash::from_str(hash)?)
            }
            (Some("pkxo"), Some(hash), None) => {
                AddressPayload::Taproot(bip340::PublicKey::from_str(hash)?)
            }
            (Some(prefix), ..) => {
                return Err(AddressParseError::UnknownPrefix(prefix.to_owned()))
            }
            (None, ..) => return Err(AddressParseError::PrefixAbsent),
        })
    }
}

#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display)]
pub enum AddressFormat {
    #[display("P2PKH")]
    P2pkh,

    #[display("P2SH")]
    P2sh,

    #[display("P2WPKH")]
    P2wpkh,

    #[display("P2WSH")]
    P2wsh,

    #[display("P2TR")]
    P2tr,

    #[display("P2W{0}")]
    Future(WitnessVersion),
}

impl AddressFormat {
    pub fn witness_version(self) -> Option<WitnessVersion> {
        match self {
            AddressFormat::P2pkh => None,
            AddressFormat::P2sh => None,
            AddressFormat::P2wpkh | AddressFormat::P2wsh => {
                Some(WitnessVersion::V0)
            }
            AddressFormat::P2tr => Some(WitnessVersion::V1),
            AddressFormat::Future(ver) => Some(ver),
        }
    }
}

impl From<Address> for AddressFormat {
    fn from(address: Address) -> Self {
        address.payload.into()
    }
}

impl From<Payload> for AddressFormat {
    fn from(payload: Payload) -> Self {
        match payload {
            Payload::PubkeyHash(_) => AddressFormat::P2pkh,
            Payload::ScriptHash(_) => AddressFormat::P2sh,
            Payload::WitnessProgram { version, program }
                if version.to_u8() == 0 && program.len() == 32 =>
            {
                AddressFormat::P2wsh
            }
            Payload::WitnessProgram { version, program }
                if version.to_u8() == 0 && program.len() == 20 =>
            {
                AddressFormat::P2wpkh
            }
            Payload::WitnessProgram { version, .. } if version.to_u8() == 1 => {
                AddressFormat::P2tr
            }
            Payload::WitnessProgram { version, .. } => AddressFormat::Future(
                version
                    .to_u8()
                    .try_into()
                    .expect("bitcoin::Address witness version is broken"),
            ),
        }
    }
}

impl FromStr for AddressFormat {
    type Err = AddressParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.to_uppercase().as_str() {
            "P2PKH" => AddressFormat::P2pkh,
            "P2SH" => AddressFormat::P2sh,
            "P2WPKH" => AddressFormat::P2wpkh,
            "P2WSH" => AddressFormat::P2wsh,
            "P2TR" => AddressFormat::P2tr,
            s if s.starts_with("P2W") => {
                AddressFormat::Future(WitnessVersion::from_str(&s[3..])?)
            }
            _ => return Err(AddressParseError::UnrecognizedAddressFormat),
        })
    }
}

#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display)]
pub enum AddressNetwork {
    #[display("mainnet")]
    Mainnet,

    #[display("testnet")]
    Testnet,

    #[display("regtest")]
    Regtest,
}

impl FromStr for AddressNetwork {
    type Err = AddressParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.to_lowercase().as_str() {
            "mainnet" => AddressNetwork::Mainnet,
            "testnet" => AddressNetwork::Testnet,
            "regtest" => AddressNetwork::Regtest,
            _ => return Err(AddressParseError::UnrecognizedAddressNetwork),
        })
    }
}

impl From<Address> for AddressNetwork {
    fn from(address: Address) -> Self {
        address.network.into()
    }
}

impl From<bitcoin::Network> for AddressNetwork {
    fn from(network: Network) -> Self {
        match network {
            Network::Bitcoin => AddressNetwork::Mainnet,
            Network::Testnet => AddressNetwork::Testnet,
            Network::Signet => AddressNetwork::Testnet,
            Network::Regtest => AddressNetwork::Regtest,
        }
    }
}