uckb_key/
pkhash.rs

1// Copyright (C) 2019-2020 Boyu Yang
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use crate::{
10    address::{Address, AddressBuilder, CodeHashIndex, Network},
11    utilities,
12};
13
14pub enum PubKeyHash {
15    Secp256k1Blake160([u8; 20]),
16}
17
18impl ::std::fmt::Debug for PubKeyHash {
19    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
20        match *self {
21            Self::Secp256k1Blake160(_) => write!(f, "PubKeyHash::Secp256k1Blake160({})", self),
22        }
23    }
24}
25
26impl ::std::fmt::Display for PubKeyHash {
27    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
28        match *self {
29            Self::Secp256k1Blake160(ref data) => write!(f, "{}", utilities::hex_string(data)),
30        }
31    }
32}
33
34impl PubKeyHash {
35    pub fn from_secp256k1_blake160(data: [u8; 20]) -> Self {
36        Self::Secp256k1Blake160(data)
37    }
38
39    pub fn address(&self, is_mainnet: bool) -> Address {
40        let network = if is_mainnet {
41            Network::Main
42        } else {
43            Network::Test
44        };
45        match *self {
46            Self::Secp256k1Blake160(ref data) => AddressBuilder::default()
47                .network(network)
48                .code_hash_by_index(CodeHashIndex::Secp256k1Blake160)
49                .args_simple(data.to_vec())
50                .build()
51                .unwrap(),
52        }
53    }
54
55    pub fn as_slice(&self) -> &[u8] {
56        match *self {
57            Self::Secp256k1Blake160(ref data) => &data[..],
58        }
59    }
60}