lib.rs (5857B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2022-2025, 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 use std::str::FromStr; 17 18 use bitcoin::{Address, Amount, Network, Txid, hashes::hex::FromHex}; 19 use rpc::{Category, Transaction}; 20 use rpc_utils::segwit_min_amount; 21 use segwit::{decode_segwit_msg, encode_segwit_key}; 22 use taler_common::{api::EddsaPublicKey, config::parser::ConfigSource}; 23 24 use crate::{rpc::RpcApi, segwit::DecodeSegWitErr}; 25 26 pub mod api; 27 pub mod cli; 28 pub mod config; 29 pub mod db; 30 pub mod loops; 31 pub mod payto; 32 pub mod rpc; 33 pub mod rpc_utils; 34 pub mod segwit; 35 pub mod setup; 36 pub mod sql; 37 pub mod taler_utils; 38 39 pub const CONFIG_SOURCE: ConfigSource = ConfigSource::simple("depolymerizer-bitcoin"); 40 41 #[derive(Debug, thiserror::Error)] 42 pub enum GetOpReturnErr { 43 #[error("Missing opreturn")] 44 MissingOpReturn, 45 #[error(transparent)] 46 RPC(#[from] rpc::Error), 47 } 48 49 /// An extended bitcoincore JSON-RPC api client who can send and retrieve metadata with their transaction 50 pub trait RpcApiExtended: RpcApi { 51 /// Send a transaction with a 32B key as metadata encoded using fake segwit addresses 52 async fn send_segwit_key( 53 &mut self, 54 to: &Address, 55 amount: Amount, 56 metadata: &[u8; 32], 57 ) -> rpc::Result<Txid> { 58 let network = guess_network(to); 59 let hrp = match network { 60 Network::Bitcoin => bech32::hrp::BC, 61 Network::Testnet | Network::Signet => bech32::hrp::TB, 62 Network::Regtest => bech32::hrp::BCRT, 63 _ => unimplemented!(), 64 }; 65 let addresses = encode_segwit_key(hrp, metadata); 66 let addresses = [ 67 Address::from_str(&addresses[0]).unwrap().assume_checked(), 68 Address::from_str(&addresses[1]).unwrap().assume_checked(), 69 ]; 70 let mut recipients = vec![(to, amount)]; 71 let min = segwit_min_amount(); 72 recipients.extend(addresses.iter().map(|addr| (addr, min))); 73 self.send_many(recipients).await 74 } 75 76 /// Get detailed information about an in-wallet transaction and it's 32B metadata key encoded using fake segwit addresses 77 async fn get_tx_segwit_key( 78 &mut self, 79 id: &Txid, 80 ) -> Result<(Transaction, Result<EddsaPublicKey, DecodeSegWitErr>), rpc::Error> { 81 let full = self.get_tx(id).await?; 82 83 let addresses: Vec<String> = full 84 .decoded 85 .vout 86 .iter() 87 .filter_map(|it| { 88 it.script_pub_key 89 .address 90 .as_ref() 91 .map(|addr| addr.clone().assume_checked().to_string()) 92 }) 93 .collect(); 94 95 Ok((full, decode_segwit_msg(&addresses))) 96 } 97 98 /// Get detailed information about an in-wallet transaction and its op_return metadata 99 async fn get_tx_op_return( 100 &mut self, 101 id: &Txid, 102 ) -> Result<(Transaction, Vec<u8>), GetOpReturnErr> { 103 let full = self.get_tx(id).await?; 104 105 let op_return_out = full 106 .decoded 107 .vout 108 .iter() 109 .find(|it| it.script_pub_key.asm.starts_with("OP_RETURN")) 110 .ok_or(GetOpReturnErr::MissingOpReturn)?; 111 112 let hex = op_return_out.script_pub_key.asm.split_once(' ').unwrap().1; 113 // Op return payload is always encoded in hexadecimal 114 let metadata = Vec::from_hex(hex).unwrap(); 115 116 Ok((full, metadata)) 117 } 118 119 /// Get the first sender address from a raw transaction 120 async fn sender_address(&mut self, full: &Transaction) -> rpc::Result<Address> { 121 let first = &full.decoded.vin[0]; 122 let tx = self.get_input_output(&first.txid.unwrap()).await?; 123 Ok(tx 124 .vout 125 .into_iter() 126 .find(|it| it.n == first.vout.unwrap()) 127 .unwrap() 128 .script_pub_key 129 .address 130 .unwrap() 131 .assume_checked()) 132 } 133 134 /// Bounce a transaction bask to its sender 135 /// 136 /// There is no reliable way to bounce a transaction as you cannot know if the addresses 137 /// used are shared or come from a third-party service. We only send back to the first input 138 /// address as a best-effort gesture. 139 async fn bounce( 140 &mut self, 141 id: &Txid, 142 bounce_fee: &Amount, 143 metadata: Option<&[u8]>, 144 ) -> Result<Txid, rpc::Error> { 145 let full = self.get_tx(id).await?; 146 let detail = &full.details[0]; 147 assert!(detail.category == Category::Receive); 148 149 let amount = detail.amount.to_unsigned().unwrap(); 150 let sender = self.sender_address(&full).await?; 151 let bounce_amount = Amount::from_sat(amount.to_sat().saturating_sub(bounce_fee.to_sat())); 152 // Send refund making recipient pay the transaction fees 153 self.send(&sender, bounce_amount, metadata, true).await 154 } 155 } 156 157 impl<T: RpcApi> RpcApiExtended for T {} 158 159 pub fn guess_network(address: &Address) -> Network { 160 let addr = address.as_unchecked(); 161 for network in [ 162 Network::Bitcoin, 163 Network::Regtest, 164 Network::Signet, 165 Network::Regtest, 166 ] { 167 if addr.is_valid_for_network(network) { 168 return network; 169 } 170 } 171 unreachable!() 172 }