This repository has been archived by the owner on Feb 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
chain_sync.rs
225 lines (206 loc) · 8.09 KB
/
chain_sync.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// Citadel: Bitcoin, LN & RGB wallet runtime
// Written in 2021 by
// Dr. Maxim Orlovsky <orlovsky@mycitadel.io>
//
// 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 AGPL License
// along with this software.
// If not, see <https://www.gnu.org/licenses/agpl-3.0-standalone.html>.
use std::collections::{BTreeMap, BTreeSet};
use std::convert::TryInto;
use bitcoin::{OutPoint, Script, Txid};
use electrum_client::{Client as ElectrumClient, ElectrumApi};
use wallet::address::AddressCompat;
use wallet::hd::{ChildIndex, UnhardenedIndex};
use crate::cache::Driver as CacheDriver;
use crate::model::{ContractId, TweakedOutput, Utxo};
use crate::runtime::Runtime;
use crate::storage::Driver as StorageDriver;
use crate::Error;
impl Runtime {
pub(in crate::runtime) fn chain_sync(
&mut self,
contract_id: ContractId,
lookup_depth: u8,
) -> Result<BTreeMap<rgb::ContractId, Vec<Utxo>>, Error> {
debug!("Synchronizing contract data with electrum server");
debug!(
"Connecting electrum server at {} ...",
self.config.electrum_server
);
debug!("Electrum server successfully connected");
let electrum =
ElectrumClient::new(&self.config.electrum_server.to_string())?;
let lookup_depth = UnhardenedIndex::from(lookup_depth);
let contract = self.storage.contract_ref(contract_id)?;
let policy = self.storage.policy(contract_id)?;
let mut unspent: Vec<Utxo> = vec![];
let mut outpoints: BTreeSet<OutPoint> = bset![];
let mut mine_info: BTreeMap<(u32, u16), Txid> = bmap! {};
let mut index_offset = UnhardenedIndex::zero();
let last_used_index = self
.cache
.last_used_derivation(contract_id)
.unwrap_or_default();
let mut scripts: Vec<(UnhardenedIndex, Script, Option<TweakedOutput>)> =
contract
.data()
.p2c_tweaks()
.into_iter()
.map(|tweak| {
(
tweak.derivation_index,
tweak.script.clone(),
Some(tweak.clone()),
)
})
.collect();
debug!(
"Requesting unspent information for {} known tweaked scripts",
scripts.len()
);
loop {
let mut count = 0usize;
trace!("{:#?}", scripts);
let txid_map = electrum
.batch_script_list_unspent(
&scripts
.iter()
.map(|(_, script, _)| script.clone())
.collect::<Vec<_>>(),
)
.map_err(|_| Error::Electrum)?
.into_iter()
.zip(scripts)
.fold(
BTreeMap::<
(u32, Txid),
Vec<(
u16,
u64,
UnhardenedIndex,
Script,
Option<TweakedOutput>,
)>,
>::new(),
|mut map, (found, (derivation_index, script, tweak))| {
for item in found {
map.entry((item.height as u32, item.tx_hash))
.or_insert(Vec::new())
.push((
item.tx_pos as u16,
item.value,
derivation_index,
script.clone(),
tweak.clone(),
));
count += 1;
}
map
},
);
debug!("Found {} unspent outputs in the batch", count);
trace!("{:#?}", txid_map);
trace!(
"Resolving block transaction position for {} transactions",
txid_map.len()
);
for ((height, txid), outs) in txid_map {
match electrum.transaction_get_merkle(&txid, height as usize) {
Ok(res) => {
mine_info.insert((height, res.pos as u16), txid);
for (vout, value, derivation_index, script, tweak) in
outs
{
if !outpoints
.insert(OutPoint::new(txid, vout as u32))
{
continue;
}
let address = contract
.chain()
.try_into()
.ok()
.and_then(|network| {
AddressCompat::from_script(&script, network)
});
unspent.push(Utxo {
value,
height,
offset: res.pos as u16,
txid,
vout,
derivation_index,
tweak: tweak
.map(|tweak| (tweak.tweak, tweak.pubkey)),
address,
});
}
}
Err(err) => warn!(
"Unable to get tx block position for {} at height {}: \
electrum server error {:?}",
txid, height, err
),
}
}
if count == 0 && index_offset > last_used_index {
debug!(
"No unspent outputs are found in the batch and we \
are behind the last used derivation; stopping search"
);
break;
}
if index_offset == UnhardenedIndex::largest() {
debug!("Reached last possible index number, breaking");
break;
}
let from = index_offset;
index_offset = index_offset
.checked_add(lookup_depth)
.unwrap_or(UnhardenedIndex::largest());
scripts = policy
.derive_scripts(from..index_offset)
.into_iter()
.map(|(derivation_index, script)| {
(derivation_index, script, None)
})
.collect();
debug!("Generating next spending script batch");
}
while let Ok(Some(info)) = electrum.block_headers_pop() {
debug!("Updating known blockchain height: {}", info.height);
self.known_height = info.height as u32;
}
let mut assets =
bmap! { rgb::ContractId::default() => unspent.clone() };
for (utxo, outpoint) in unspent.iter_mut().zip(outpoints.iter()) {
for (asset_id, amounts) in
self.rgb20_client.outpoint_assets(*outpoint)?
{
if amounts.is_empty() {
continue;
}
let amount = amounts.iter().sum();
if amount > 0 {
let mut u = utxo.clone();
u.value = amount;
assets.entry(asset_id).or_insert(vec![]).push(u);
}
}
}
trace!("Transaction mining info: {:#?}", mine_info);
self.cache.update(
contract_id,
mine_info,
Some(self.known_height),
outpoints,
assets.clone(),
)?;
Ok(assets)
}
}