btc.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. use crate::{serial::deserialize, serial::serialize, Error, Result};
  2. use rand::{thread_rng, Rng};
  3. use rand::distributions::Alphanumeric;
  4. use secp256k1::key::SecretKey;
  5. use bitcoin::util::ecdsa::{PrivateKey, PublicKey};
  6. use bitcoin::util::address::Address;
  7. use bitcoin::network::constants::Network;
  8. // Swap out these types for any future non bitcoin-rs types
  9. pub type PubAddress = Address;
  10. pub type PubKey = PublicKey;
  11. pub type PrivKey = PrivateKey;
  12. pub struct BitcoinKeys {
  13. secret_key: SecretKey,
  14. bitcoin_private_key: PrivateKey,
  15. pub bitcoin_public_key: PublicKey,
  16. pub pub_address: Address,
  17. }
  18. impl BitcoinKeys {
  19. pub fn new(
  20. ) -> Result<BitcoinKeys> {
  21. let context = secp256k1::Secp256k1::new();
  22. // Probably not good enough for release
  23. let rand: String = thread_rng()
  24. .sample_iter(&Alphanumeric)
  25. .take(32)
  26. .map(char::from)
  27. .collect();
  28. let rand_hex = hex::encode(rand);
  29. // Generate simple byte array from rand
  30. let data_slice: &[u8] = rand_hex.as_bytes();
  31. let secret_key = SecretKey::from_slice(&hex::decode(data_slice).unwrap()).unwrap();
  32. // Use Testnet
  33. let bitcoin_private_key = PrivateKey::new(secret_key, Network::Testnet);
  34. let bitcoin_public_key = PublicKey::from_private_key(&context, &bitcoin_private_key);
  35. //let pubkey_serialized = bitcoin_public_key.to_bytes();
  36. let pub_address = Address::p2pkh(&bitcoin_public_key, Network::Testnet);
  37. Ok(Self {
  38. secret_key,
  39. bitcoin_private_key,
  40. bitcoin_public_key,
  41. pub_address,
  42. })
  43. }
  44. // This should do a db lookup to return the same obj
  45. pub fn address_from_slice(key: &[u8]) -> Result<Address> {
  46. let pub_key = PublicKey::from_slice(key).unwrap();
  47. let address = Address::p2pkh(&pub_key, Network::Testnet);
  48. Ok(address)
  49. }
  50. pub fn get_deposit_address(&self) -> Result<&Address> {
  51. Ok(&self.pub_address)
  52. }
  53. pub fn get_pubkey(&self) -> &PublicKey {
  54. &self.bitcoin_public_key
  55. }
  56. pub fn get_privkey(&self) -> &PrivateKey {
  57. &self.bitcoin_private_key
  58. }
  59. }