btc.rs 2.6 KB

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