Trait crypto_addr::Address

source ·
pub trait Address {
    // Required method
    fn addr(&self, opts: &AddressFormat) -> Result<String, Error>;
}
Expand description

Generate an Address string from existing Public Key

This trait provides the main functionality of the crate. The provided addr method implements encoding a public key as a P2PKH address. This trait is implemented for all types which expose a sequence of bytes via AsRef<[u8]>.

Usage

Addresses are generated from public keys using Address::addr

use crypto_addr::{Address, AddressFormat, Error};
use hex_literal::hex;

// This is a compressed public key in SEC 1 standard format
const PUBLIC_KEY_BYTES: [u8; 33] =
    hex!("029d08f65e6aac041328edaeddba9c682356f81b37b052728fd8637c14eddb7ff1");

// Generate a Bitcoin P2PKH address
assert_eq!(
    PUBLIC_KEY_BYTES.addr(&AddressFormat::Bitcoin).as_deref(),
    Ok("14cWWeAYZmA9oGgLpjekay9xLwHew3Ni34")
);

// Generate a Litcoin P2PKH address
assert_eq!(
    PUBLIC_KEY_BYTES.addr(&AddressFormat::Litecoin).as_deref(),
    Ok("LNqTmrUNeRQD45NVzse3rzDiZ9ew7HMYDY")
);

// Generate a Dogecoin P2PKH address
assert_eq!(
    PUBLIC_KEY_BYTES.addr(&AddressFormat::Dogecoin).as_deref(),
    Ok("D8kc3u7BsB4SLGrwZKeK8jKZE51xKNc3FF")
);

// Generate a Bitcoin Cash P2PKH address with elided "bitcoincash" prefix
assert_eq!(
    PUBLIC_KEY_BYTES.addr(&AddressFormat::BitcoinCash(None)).as_deref(),
    Ok("qqnelysjjjyrn4eywr04vf4v9nydrqdk6vep2tp2g9")
);

// Generate a Bitcoin Cash P2PKH address with a custom prefix
assert_eq!(
    PUBLIC_KEY_BYTES.addr(&AddressFormat::BitcoinCash(Some("foo".to_owned()))).as_deref(),
    Ok("foo:qqnelysjjjyrn4eywr04vf4v9nydrqdk6v730zmhs6")
);

// Errors are detected
let partial_pubkey = &PUBLIC_KEY_BYTES[..30];
assert_eq!(
    partial_pubkey.addr(&AddressFormat::Bitcoin).unwrap_err(),
    Error::InvalidLength{expected: 33, received: 30}
);

Required Methods§

source

fn addr(&self, opts: &AddressFormat) -> Result<String, Error>

Derive a P2PKH address string from a public key (self). Parameters for the address format are given by opts. Returns Err if public key is not able to derive an address, i.e. if it is not the correct length.

Implementors§

source§

impl<T: AsRef<[u8]>> Address for T

Address is implemented for all types that expose a sequence of bytes via AsRef<[u8]>. In this case, the input bytes are interpreted as a compressed public key encoded with encoding described in SEC 1: Elliptic Curve Cryptography (Version 2.0) section 2.3.3 (page 10).