This repository has been archived by the owner on Sep 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
trial_decryptions.rs
205 lines (168 loc) · 7.86 KB
/
trial_decryptions.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
use crate::{compact_formats::CompactBlock, lightwallet::{MemoDownloadOption, data::WalletTx, keys::Keys, wallet_txns::WalletTxns}};
use futures::{stream::FuturesUnordered, StreamExt};
use log::info;
use std::sync::Arc;
use tokio::{sync::{RwLock, mpsc::{unbounded_channel, UnboundedSender}, oneshot}, task::JoinHandle};
use zcash_primitives::{consensus::BlockHeight, note_encryption::try_sapling_compact_note_decryption, primitives::{Nullifier, SaplingIvk}, transaction::{Transaction, TxId}};
use super::syncdata::BlazeSyncData;
pub struct TrialDecryptions {
keys: Arc<RwLock<Keys>>,
wallet_txns: Arc<RwLock<WalletTxns>>,
}
impl TrialDecryptions {
pub fn new(keys: Arc<RwLock<Keys>>, wallet_txns: Arc<RwLock<WalletTxns>>) -> Self {
Self { keys, wallet_txns }
}
pub async fn start(
&self,
bsync_data: Arc<RwLock<BlazeSyncData>>,
detected_txid_sender: UnboundedSender<(TxId, Nullifier, BlockHeight, Option<u32>)>,
fulltx_fetcher: UnboundedSender<(TxId, oneshot::Sender<Result<Transaction, String>>)>,
) -> (JoinHandle<()>, UnboundedSender<CompactBlock>) {
//info!("Starting trial decrptions processor");
// Create a new channel where we'll receive the blocks
let (tx, mut rx) = unbounded_channel::<CompactBlock>();
let keys = self.keys.clone();
let wallet_txns = self.wallet_txns.clone();
let h = tokio::spawn(async move {
let mut workers = FuturesUnordered::new();
let mut cbs = vec![];
let ivks = Arc::new(
keys.read()
.await
.zkeys
.iter()
.map(|zk| zk.extfvk().fvk.vk.ivk())
.collect::<Vec<_>>(),
);
while let Some(cb) = rx.recv().await {
cbs.push(cb);
if cbs.len() >= 1_000 {
let keys = keys.clone();
let ivks = ivks.clone();
let wallet_txns = wallet_txns.clone();
let bsync_data = bsync_data.clone();
let detected_txid_sender = detected_txid_sender.clone();
workers.push(tokio::spawn(Self::trial_decrypt_batch(
cbs.split_off(0),
keys,
bsync_data,
ivks,
wallet_txns,
detected_txid_sender,
fulltx_fetcher.clone(),
)));
}
}
workers.push(tokio::spawn(Self::trial_decrypt_batch(
cbs,
keys,
bsync_data,
ivks,
wallet_txns,
detected_txid_sender,
fulltx_fetcher,
)));
while let Some(r) = workers.next().await {
r.unwrap().unwrap();
}
//info!("Finished final trial decryptions");
});
return (h, tx);
}
async fn trial_decrypt_batch(
cbs: Vec<CompactBlock>,
keys: Arc<RwLock<Keys>>,
bsync_data: Arc<RwLock<BlazeSyncData>>,
ivks: Arc<Vec<SaplingIvk>>,
wallet_txns: Arc<RwLock<WalletTxns>>,
detected_txid_sender: UnboundedSender<(TxId, Nullifier, BlockHeight, Option<u32>)>,
fulltx_fetcher: UnboundedSender<(TxId, oneshot::Sender<Result<Transaction, String>>)>,
) -> Result<(), String> {
let config = keys.read().await.config().clone();
let blk_count = cbs.len();
let mut workers = FuturesUnordered::new();
let download_memos = bsync_data.read().await.wallet_options.download_memos;
for cb in cbs {
let height = BlockHeight::from_u32(cb.height as u32);
for (tx_num, ctx) in cb.vtx.iter().enumerate() {
let mut wallet_tx = false;
for (output_num, co) in ctx.outputs.iter().enumerate() {
let cmu = co.cmu().map_err(|_| "No CMU".to_string())?;
let epk = match co.epk() {
Err(_) => continue,
Ok(epk) => epk,
};
for (i, ivk) in ivks.iter().enumerate() {
if let Some((note, to)) = try_sapling_compact_note_decryption(
&config.get_params(),
height,
&ivk,
&epk,
&cmu,
&co.ciphertext,
) {
wallet_tx = true;
let keys = keys.clone();
let bsync_data = bsync_data.clone();
let wallet_txns = wallet_txns.clone();
let detected_txid_sender = detected_txid_sender.clone();
let timestamp = cb.time as u64;
let ctx = ctx.clone();
workers.push(tokio::spawn(async move {
let keys = keys.read().await;
let extfvk = keys.zkeys[i].extfvk();
let have_spending_key = keys.have_spending_key(extfvk);
let uri = bsync_data.read().await.uri().clone();
// Get the witness for the note
let witness = bsync_data
.read()
.await
.block_data
.get_note_witness(uri, height, tx_num, output_num)
.await?;
let txid = WalletTx::new_txid(&ctx.hash);
let nullifier = note.nf(&extfvk.fvk.vk, witness.position() as u64);
wallet_txns.write().await.add_new_note(
txid.clone(),
height,
false,
timestamp,
note,
to,
&extfvk,
have_spending_key,
witness,
);
info!("Trial decrypt Detected txid {}", &txid);
detected_txid_sender
.send((txid, nullifier, height, Some(output_num as u32)))
.unwrap();
Ok::<_, String>(())
}));
// No need to try the other ivks if we found one
break;
}
}
}
// Check option to see if we are fetching all txns.
if !wallet_tx && download_memos == MemoDownloadOption::AllMemos {
let txid = WalletTx::new_txid(&ctx.hash);
let (tx, rx) = oneshot::channel();
fulltx_fetcher.send((txid, tx)).unwrap();
workers.push(tokio::spawn(async move {
// Discard the result, because this was not a wallet tx.
rx.await.unwrap().map(|_r| ())
}));
}
}
}
while let Some(r) = workers.next().await {
r.map_err(|e| e.to_string())??;
}
// Update sync status
bsync_data.read().await.sync_status.write().await.trial_dec_done += blk_count as u64;
// Return a nothing-value
Ok::<(), String>(())
}
}