forked from RGB-WG/rgb-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelectrum.rs
77 lines (65 loc) · 2.17 KB
/
electrum.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// RGB standard library
// Written in 2020 by
// Dr. Maxim Orlovsky <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
use std::cell::RefCell;
use electrum_client::{Client, ElectrumApi, Error};
use lnpbp::bitcoin::{Transaction, Txid};
use lnpbp::rgb::validation::{TxResolver, TxResolverError};
fn map_electrum_err(other: Error) -> TxResolverError {
log::error!("Electrum error: {:?}", other);
TxResolverError
}
pub struct ElectrumTxResolver {
client: RefCell<Client>,
}
impl ElectrumTxResolver {
pub fn new(server: &str) -> Result<Self, Error> {
Ok(ElectrumTxResolver {
client: RefCell::new(Client::new(server, None)?),
})
}
}
impl TxResolver for &ElectrumTxResolver {
fn resolve(
&self,
txid: &Txid,
) -> Result<Option<(Transaction, u64)>, TxResolverError> {
log::debug!("Resolving txid {}", txid);
let tx = self
.client
.borrow_mut()
.transaction_get(txid)
.map_err(map_electrum_err)?;
let input_amount = tx
.input
.iter()
.map(|i| -> Result<_, Error> {
Ok((
self.client
.borrow_mut()
.transaction_get(&i.previous_output.txid)?,
i.previous_output.vout,
))
})
.collect::<Result<Vec<_>, Error>>()
.map_err(map_electrum_err)?
.into_iter()
.map(|(tx, vout)| tx.output[vout as usize].value)
.fold(0, |sum, i| i + sum);
let output_amount = tx.output.iter().fold(0, |sum, o| sum + o.value);
let fee = input_amount
.checked_sub(output_amount)
.ok_or(TxResolverError)?;
log::debug!("Calculated fee: {}", fee);
Ok(Some((tx, fee)))
}
}