bsv-wallet-toolbox 0.2.19

Pure Rust BSV wallet-toolbox implementation
Documentation
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! BEEF construction from storage via recursive input chain walking.
//!
//! Builds a valid BEEF (BRC-62) for a given txid by recursively collecting
//! proven transactions and their merkle proofs from storage. This is needed
//! by the signer pipeline to build valid BEEF for transactions.

use std::collections::HashSet;
use std::io::Cursor;

use crate::error::{WalletError, WalletResult};
use crate::storage::find_args::*;
use crate::storage::traits::reader::StorageReader;
use crate::storage::traits::wallet_provider::WalletStorageProvider;

use bsv::transaction::beef::{Beef, BEEF_V2};
use bsv::transaction::beef_tx::BeefTx;
use bsv::transaction::merkle_path::MerklePath;
use bsv::transaction::transaction::Transaction as BsvTransaction;

/// How to handle self-signed (wallet-created) transactions in BEEF construction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrustSelf {
    /// Trust transactions known to have been created by this wallet.
    /// Include them as txid-only entries without proof.
    Known,
    /// Trust both known and newly-created wallet transactions.
    KnownAndNew,
    /// Do not trust any self-signed transactions -- require full proofs.
    No,
}

/// Collected transaction data during recursive BEEF building.
struct CollectedTx {
    /// The raw transaction bytes.
    raw_tx: Vec<u8>,
    /// The txid of this transaction.
    txid: String,
    /// If proven, the merkle path bytes.
    merkle_path: Option<Vec<u8>>,
    /// Whether this is a txid-only entry (trusted, no raw_tx needed in BEEF).
    txid_only: bool,
}

/// Build a valid BEEF for the given txid by recursively walking input chains.
///
/// Looks up the txid in ProvenTx table first. If found with merkle_path, it's
/// a proven leaf. Otherwise looks up in Transaction table for raw_tx and
/// recurses into input txids.
///
/// Returns serialized BEEF bytes, or None if the transaction cannot be found.
pub async fn get_valid_beef_for_txid(
    storage: &(dyn WalletStorageProvider + Send + Sync),
    txid: &str,
    trust_self: TrustSelf,
    known_txids: &HashSet<String>,
) -> WalletResult<Option<Vec<u8>>> {
    get_valid_beef_for_txid_inner(storage, txid, trust_self, known_txids).await
}

/// Variant accepting a `StorageReader` for use from within storage methods.
///
/// Uses the low-level `StorageReader` trait (with explicit `None` trx args)
/// instead of `WalletStorageProvider`. This allows it to be called from within
/// `storage_create_action` where the storage is `&S: StorageReaderWriter`.
pub async fn get_valid_beef_for_storage_reader<S: StorageReader + ?Sized>(
    storage: &S,
    txid: &str,
    trust_self: TrustSelf,
    known_txids: &HashSet<String>,
) -> WalletResult<Option<Vec<u8>>> {
    let mut collected: Vec<CollectedTx> = Vec::new();
    let mut visited: HashSet<String> = HashSet::new();
    collect_tx_recursive_reader(
        storage,
        txid,
        trust_self,
        known_txids,
        &mut collected,
        &mut visited,
    )
    .await?;
    build_beef_from_collected(collected)
}

async fn get_valid_beef_for_txid_inner(
    storage: &dyn WalletStorageProvider,
    txid: &str,
    trust_self: TrustSelf,
    known_txids: &HashSet<String>,
) -> WalletResult<Option<Vec<u8>>> {
    let mut collected: Vec<CollectedTx> = Vec::new();
    let mut visited: HashSet<String> = HashSet::new();

    collect_tx_recursive(
        storage,
        txid,
        trust_self,
        known_txids,
        &mut collected,
        &mut visited,
    )
    .await?;

    build_beef_from_collected(collected)
}

/// Recursively collect transaction data for BEEF construction.
///
/// Walks the input chain: for each unvisited input txid, checks if it's proven
/// (has merkle_path), otherwise recurses into its inputs.
async fn collect_tx_recursive(
    storage: &dyn WalletStorageProvider,
    txid: &str,
    trust_self: TrustSelf,
    known_txids: &HashSet<String>,
    collected: &mut Vec<CollectedTx>,
    visited: &mut HashSet<String>,
) -> WalletResult<()> {
    if visited.contains(txid) {
        return Ok(());
    }
    visited.insert(txid.to_string());

    // 1. Check if txid is in ProvenTx table (has merkle proof)
    let proven = storage
        .find_proven_txs(&FindProvenTxsArgs {
            partial: ProvenTxPartial {
                txid: Some(txid.to_string()),
                ..Default::default()
            },
            ..Default::default()
        })
        .await?;

    if let Some(ptx) = proven.into_iter().next() {
        // Proven transaction -- it's a leaf with merkle proof
        if trust_self == TrustSelf::Known {
            // In Known mode, proven txs are trusted as txid-only
            collected.push(CollectedTx {
                raw_tx: Vec::new(),
                txid: txid.to_string(),
                merkle_path: None,
                txid_only: true,
            });
        } else {
            collected.push(CollectedTx {
                raw_tx: ptx.raw_tx,
                txid: txid.to_string(),
                merkle_path: Some(ptx.merkle_path),
                txid_only: false,
            });
        }
        return Ok(());
    }

    // 2. Not proven -- check Transaction table
    let txs = storage
        .find_transactions(&FindTransactionsArgs {
            partial: TransactionPartial {
                txid: Some(txid.to_string()),
                ..Default::default()
            },
            ..Default::default()
        })
        .await?;

    let tx_record = match txs.into_iter().next() {
        Some(t) => t,
        None => {
            // Transaction not found in storage -- check if it's a known txid
            if known_txids.contains(txid) {
                collected.push(CollectedTx {
                    raw_tx: Vec::new(),
                    txid: txid.to_string(),
                    merkle_path: None,
                    txid_only: true,
                });
            }
            return Ok(());
        }
    };

    // If trust_self is Known, treat wallet-created transactions as txid-only
    if trust_self == TrustSelf::Known {
        collected.push(CollectedTx {
            raw_tx: Vec::new(),
            txid: txid.to_string(),
            merkle_path: None,
            txid_only: true,
        });
        return Ok(());
    }

    let raw_tx = match tx_record.raw_tx {
        Some(ref raw) => raw.clone(),
        None => {
            // No raw_tx available -- can't build BEEF for this path.
            // If it's in known_txids, include as txid-only.
            if known_txids.contains(txid) {
                collected.push(CollectedTx {
                    raw_tx: Vec::new(),
                    txid: txid.to_string(),
                    merkle_path: None,
                    txid_only: true,
                });
            }
            return Ok(());
        }
    };

    // Parse raw_tx to extract input txids for recursion
    let bsv_tx = {
        let mut cursor = Cursor::new(&raw_tx);
        BsvTransaction::from_binary(&mut cursor).map_err(|e| {
            WalletError::Internal(format!("Failed to parse raw_tx for {}: {}", txid, e))
        })?
    };

    // Recurse into each input's source txid
    for input in &bsv_tx.inputs {
        if let Some(ref source_txid) = input.source_txid {
            if !visited.contains(source_txid.as_str()) {
                // If in known_txids, skip recursion and just add txid-only
                if known_txids.contains(source_txid.as_str()) {
                    visited.insert(source_txid.clone());
                    collected.push(CollectedTx {
                        raw_tx: Vec::new(),
                        txid: source_txid.clone(),
                        merkle_path: None,
                        txid_only: true,
                    });
                } else {
                    Box::pin(collect_tx_recursive(
                        storage,
                        source_txid,
                        trust_self,
                        known_txids,
                        collected,
                        visited,
                    ))
                    .await?;
                }
            }
        }
    }

    // Add this transaction (not proven, with raw_tx, no merkle proof)
    // Also merge inputBEEF if available
    collected.push(CollectedTx {
        raw_tx,
        txid: txid.to_string(),
        merkle_path: None,
        txid_only: false,
    });

    Ok(())
}

/// Build a BEEF from collected transactions and return serialized bytes.
fn build_beef_from_collected(collected: Vec<CollectedTx>) -> WalletResult<Option<Vec<u8>>> {
    if collected.is_empty() {
        return Ok(None);
    }

    let mut beef = Beef::new(BEEF_V2);

    for ctx in &collected {
        if ctx.txid_only {
            beef.txs.push(BeefTx {
                tx: None,
                txid: ctx.txid.clone(),
                bump_index: None,
                input_txids: Vec::new(),
            });
            continue;
        }

        let bsv_tx = {
            let mut cursor = Cursor::new(&ctx.raw_tx);
            BsvTransaction::from_binary(&mut cursor).map_err(|e| {
                WalletError::Internal(format!("Failed to parse raw_tx for {}: {}", ctx.txid, e))
            })?
        };

        let bump_index = if let Some(ref mp_bytes) = ctx.merkle_path {
            let mp = {
                let mut cursor = Cursor::new(mp_bytes);
                MerklePath::from_binary(&mut cursor).map_err(|e| {
                    WalletError::Internal(format!(
                        "Failed to parse merkle_path for {}: {}",
                        ctx.txid, e
                    ))
                })?
            };
            let idx = beef.bumps.len();
            beef.bumps.push(mp);
            Some(idx)
        } else {
            None
        };

        let beef_tx = BeefTx::from_tx(bsv_tx, bump_index).map_err(|e| {
            WalletError::Internal(format!("Failed to create BeefTx for {}: {}", ctx.txid, e))
        })?;
        beef.txs.push(beef_tx);
    }

    let mut buf = Vec::new();
    beef.to_binary(&mut buf)
        .map_err(|e| WalletError::Internal(format!("Failed to serialize BEEF: {}", e)))?;

    Ok(Some(buf))
}

/// Recursively collect transaction data using the low-level `StorageReader` trait.
///
/// Used by `get_valid_beef_for_storage_reader` which is called from within
/// storage method implementations where `WalletStorageProvider` isn't available.
async fn collect_tx_recursive_reader<S: StorageReader + ?Sized>(
    storage: &S,
    txid: &str,
    trust_self: TrustSelf,
    known_txids: &HashSet<String>,
    collected: &mut Vec<CollectedTx>,
    visited: &mut HashSet<String>,
) -> WalletResult<()> {
    if visited.contains(txid) {
        return Ok(());
    }
    visited.insert(txid.to_string());

    // 1. Check ProvenTx table
    let proven = storage
        .find_proven_txs(
            &FindProvenTxsArgs {
                partial: ProvenTxPartial {
                    txid: Some(txid.to_string()),
                    ..Default::default()
                },
                ..Default::default()
            },
            None,
        )
        .await?;

    if let Some(ptx) = proven.into_iter().next() {
        if trust_self == TrustSelf::Known {
            collected.push(CollectedTx {
                raw_tx: Vec::new(),
                txid: txid.to_string(),
                merkle_path: None,
                txid_only: true,
            });
        } else {
            collected.push(CollectedTx {
                raw_tx: ptx.raw_tx,
                txid: txid.to_string(),
                merkle_path: Some(ptx.merkle_path),
                txid_only: false,
            });
        }
        return Ok(());
    }

    // 2. Check Transaction table
    let txs = storage
        .find_transactions(
            &FindTransactionsArgs {
                partial: TransactionPartial {
                    txid: Some(txid.to_string()),
                    ..Default::default()
                },
                ..Default::default()
            },
            None,
        )
        .await?;

    let tx_record = match txs.into_iter().next() {
        Some(t) => t,
        None => {
            if known_txids.contains(txid) {
                collected.push(CollectedTx {
                    raw_tx: Vec::new(),
                    txid: txid.to_string(),
                    merkle_path: None,
                    txid_only: true,
                });
            }
            return Ok(());
        }
    };

    if trust_self == TrustSelf::Known {
        collected.push(CollectedTx {
            raw_tx: Vec::new(),
            txid: txid.to_string(),
            merkle_path: None,
            txid_only: true,
        });
        return Ok(());
    }

    let raw_tx = match tx_record.raw_tx {
        Some(ref raw) => raw.clone(),
        None => {
            if known_txids.contains(txid) {
                collected.push(CollectedTx {
                    raw_tx: Vec::new(),
                    txid: txid.to_string(),
                    merkle_path: None,
                    txid_only: true,
                });
            }
            return Ok(());
        }
    };

    let bsv_tx = {
        let mut cursor = Cursor::new(&raw_tx);
        BsvTransaction::from_binary(&mut cursor).map_err(|e| {
            WalletError::Internal(format!("Failed to parse raw_tx for {}: {}", txid, e))
        })?
    };

    for input in &bsv_tx.inputs {
        if let Some(ref source_txid) = input.source_txid {
            if !visited.contains(source_txid.as_str()) {
                if known_txids.contains(source_txid.as_str()) {
                    visited.insert(source_txid.clone());
                    collected.push(CollectedTx {
                        raw_tx: Vec::new(),
                        txid: source_txid.clone(),
                        merkle_path: None,
                        txid_only: true,
                    });
                } else {
                    Box::pin(collect_tx_recursive_reader(
                        storage,
                        source_txid,
                        trust_self,
                        known_txids,
                        collected,
                        visited,
                    ))
                    .await?;
                }
            }
        }
    }

    collected.push(CollectedTx {
        raw_tx,
        txid: txid.to_string(),
        merkle_path: None,
        txid_only: false,
    });

    Ok(())
}