bsv-wallet-toolbox 0.2.23

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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! Signer-level createAction orchestration.
//!
//! Ported from wallet-toolbox/src/signer/methods/createAction.ts.
//! Coordinates storage.create_action, build_signable_transaction,
//! complete_signed_transaction, storage.process_action, and BEEF construction.

use std::collections::HashMap;

use bsv::primitives::public_key::PublicKey;
use bsv::transaction::Beef;
use bsv::wallet::cached_key_deriver::CachedKeyDeriver;

use crate::error::{WalletError, WalletResult};
use crate::services::traits::WalletServices;
use crate::signer::build_signable::build_signable_transaction;
use crate::signer::complete_signed::complete_signed_transaction;
use crate::signer::types::{
    PendingSignAction, SignableTransactionRef, SignerCreateActionResult, ValidCreateActionArgs,
};
use crate::storage::action_types::{
    StorageCreateActionArgs, StorageCreateActionInput, StorageCreateActionOptions,
    StorageCreateActionOutput, StorageOutPoint, StorageProcessActionArgs,
};
use crate::storage::manager::WalletStorageManager;
use crate::wallet::types::AuthId;

/// Simple bytes-to-hex encoding.
fn bytes_to_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

/// Parse an OutpointString ("txid.vout") into a StorageOutPoint.
fn parse_outpoint_string(s: &str) -> StorageOutPoint {
    let parts: Vec<&str> = s.rsplitn(2, '.').collect();
    if parts.len() == 2 {
        StorageOutPoint {
            txid: parts[1].to_string(),
            vout: parts[0].parse().unwrap_or(0),
        }
    } else {
        StorageOutPoint {
            txid: s.to_string(),
            vout: 0,
        }
    }
}

/// Convert ValidCreateActionArgs to StorageCreateActionArgs.
///
/// Strips unlocking scripts (storage only needs the length).
/// Maps SDK CreateActionOptions to StorageCreateActionOptions.
pub(crate) fn to_storage_args(args: &ValidCreateActionArgs) -> StorageCreateActionArgs {
    use bsv::wallet::types::{BooleanDefaultFalse, BooleanDefaultTrue};

    let opts = &args.options;
    let storage_options = StorageCreateActionOptions {
        sign_and_process: BooleanDefaultTrue(opts.sign_and_process.0),
        accept_delayed_broadcast: BooleanDefaultTrue(opts.accept_delayed_broadcast.0),
        trust_self: opts.trust_self.as_ref().map(|ts| ts.as_str().to_string()),
        known_txids: opts.known_txids.clone(),
        return_txid_only: BooleanDefaultFalse(opts.return_txid_only.0),
        no_send: BooleanDefaultFalse(opts.no_send.0),
        no_send_change: opts
            .no_send_change
            .iter()
            .map(|s| parse_outpoint_string(s))
            .collect(),
        send_with: opts.send_with.clone(),
        randomize_outputs: BooleanDefaultTrue(opts.randomize_outputs.0),
    };

    StorageCreateActionArgs {
        description: args.description.clone(),
        inputs: args
            .inputs
            .iter()
            .map(|i| StorageCreateActionInput {
                outpoint: StorageOutPoint {
                    txid: i.outpoint.txid.clone(),
                    vout: i.outpoint.vout,
                },
                input_description: i.input_description.clone(),
                unlocking_script_length: i
                    .unlocking_script
                    .as_ref()
                    .map(|s| s.len())
                    .unwrap_or(i.unlocking_script_length),
                sequence_number: i.sequence_number,
            })
            .collect(),
        outputs: args
            .outputs
            .iter()
            .map(|o| {
                let script_hex = o
                    .locking_script
                    .as_ref()
                    .map(|s| bytes_to_hex(s))
                    .unwrap_or_default();
                StorageCreateActionOutput {
                    locking_script: script_hex,
                    satoshis: o.satoshis,
                    output_description: o.output_description.clone(),
                    basket: o.basket.clone(),
                    custom_instructions: o.custom_instructions.clone(),
                    tags: o.tags.clone(),
                }
            })
            .collect(),
        lock_time: args.lock_time,
        version: args.version,
        labels: args.labels.iter().map(|l| l.to_string()).collect(),
        options: storage_options,
        input_beef: args.input_beef.clone(),
        is_new_tx: args.is_new_tx,
        is_sign_action: args.is_sign_action,
        is_no_send: args.is_no_send,
        is_delayed: args.is_delayed,
        is_send_with: args.is_send_with,
        is_remix_change: false,
        is_test_werr_review_actions: None,
        include_all_source_transactions: false,
        random_vals: None,
    }
}

/// Execute the signer-level createAction flow.
///
/// 1. Call storage.create_action to allocate UTXOs and create records
/// 2. Build the unsigned transaction via build_signable_transaction
/// 3. Branch based on whether this is a deferred sign action:
///    - If `is_sign_action`: store `PendingSignAction`, return `SignableTransaction`.
///    - Otherwise: sign via `complete_signed_transaction`, process, optionally broadcast.
pub async fn signer_create_action(
    storage: &WalletStorageManager,
    services: &(dyn WalletServices + Send + Sync),
    key_deriver: &CachedKeyDeriver,
    identity_pub_key: &PublicKey,
    auth: &str,
    args: &ValidCreateActionArgs,
) -> WalletResult<(SignerCreateActionResult, Option<PendingSignAction>)> {
    // --- Step 1: Storage create action ---
    let auth_id = AuthId {
        identity_key: auth.to_string(),
        user_id: None,
        is_active: None,
    };
    let storage_args = to_storage_args(args);
    let mut dcr = storage.create_action(&auth_id, &storage_args).await?;
    merge_input_beef_signer(storage, &mut dcr).await?;
    let reference = dcr.reference.clone();

    // --- Step 2: Build unsigned transaction ---
    let (mut tx, amount, pdi) =
        build_signable_transaction(&dcr, args, key_deriver, identity_pub_key)?;

    // --- Step 3a: Delayed signing (is_sign_action) ---
    if args.is_sign_action {
        // Serialize unsigned tx for later recovery
        let mut tx_bytes = Vec::new();
        tx.to_binary(&mut tx_bytes).map_err(|e| {
            WalletError::Internal(format!("Failed to serialize unsigned tx: {}", e))
        })?;

        let pending = PendingSignAction {
            reference: reference.clone(),
            dcr: dcr.clone(),
            args: args.clone(),
            tx: tx_bytes.clone(),
            amount,
            pdi: pdi.clone(),
        };

        // Build signable transaction BEEF for the caller
        let signable_beef = build_beef_bytes(&tx, &dcr.input_beef)?;

        let no_send_change = if args.is_no_send {
            let txid = tx
                .id()
                .map_err(|e| WalletError::Internal(format!("Failed to compute txid: {}", e)))?;
            dcr.no_send_change_output_vouts
                .as_ref()
                .map(|vouts| vouts.iter().map(|v| format!("{}.{}", txid, v)).collect())
                .unwrap_or_default()
        } else {
            vec![]
        };

        let result = SignerCreateActionResult {
            txid: None,
            tx: None,
            no_send_change,
            send_with_results: vec![],
            signable_transaction: Some(SignableTransactionRef {
                reference: reference.clone(),
                tx: signable_beef,
            }),
            not_delayed_results: None,
        };

        return Ok((result, Some(pending)));
    }

    // --- Step 3b: Immediate signing ---
    let signed_tx_bytes = complete_signed_transaction(
        &mut tx,
        &pdi,
        &HashMap::new(),
        key_deriver,
        identity_pub_key,
    )?;

    let txid = tx
        .id()
        .map_err(|e| WalletError::Internal(format!("Failed to compute txid: {}", e)))?;

    // Build BEEF, verify unlock scripts, then serialize
    let beef = build_beef(&tx, &dcr.input_beef)?;
    crate::signer::verify_unlock_scripts::verify_unlock_scripts(&txid, &beef)?;
    let beef_bytes = serialize_beef_atomic(&beef, &txid)?;

    let no_send_change = if args.is_no_send {
        dcr.no_send_change_output_vouts
            .as_ref()
            .map(|vouts| vouts.iter().map(|v| format!("{}.{}", txid, v)).collect())
            .unwrap_or_default()
    } else {
        vec![]
    };

    // --- Step 4: Process action in storage ---
    let process_args = StorageProcessActionArgs {
        is_new_tx: args.is_new_tx,
        is_send_with: args.is_send_with,
        is_no_send: args.is_no_send,
        is_delayed: args.is_delayed,
        reference: Some(reference),
        txid: Some(txid.clone()),
        raw_tx: Some(signed_tx_bytes),
        send_with: if args.is_send_with {
            args.options.send_with.clone()
        } else {
            vec![]
        },
    };
    let process_result = storage.process_action(&auth_id, &process_args).await?;
    // --- Step 5: Broadcast and update status ---
    // In the TS implementation, shareReqsWithWorld handles both broadcast
    // and the post-broadcast status update. The initial status from
    // processAction is unprocessed/unprocessed. After successful broadcast,
    // status should transition to unmined/unproven (or sending/unproven
    // for the non-delayed case). Without this update, outputs remain
    // invisible to the balance query and UTXO selection.
    if !args.is_no_send && !args.is_delayed {
        let post_results = services
            .post_beef(&beef_bytes, std::slice::from_ref(&txid))
            .await;

        let outcome = crate::signer::broadcast_outcome::classify_broadcast_results(&post_results);

        match &outcome {
            crate::signer::broadcast_outcome::BroadcastOutcome::Success
            | crate::signer::broadcast_outcome::BroadcastOutcome::OrphanMempool { .. } => {
                // Success or transient orphan — transition to unproven/unmined.
                // OrphanMempool stays in sending for monitor retry.
                let _ = crate::signer::broadcast_outcome::apply_success_or_orphan_outcome(
                    storage, &txid, &outcome,
                )
                .await;
            }
            crate::signer::broadcast_outcome::BroadcastOutcome::DoubleSpend { .. }
            | crate::signer::broadcast_outcome::BroadcastOutcome::InvalidTx { .. } => {
                // Permanent failure — mark tx failed, outputs unspendable, reconcile against chain.
                // Log any handler error for ops visibility; do not propagate — the broadcast
                // outcome we already have remains authoritative for the caller.
                if let Err(e) =
                    crate::signer::broadcast_outcome::handle_permanent_broadcast_failure(
                        storage, services, &txid, &outcome,
                    )
                    .await
                {
                    tracing::error!(
                        error = %e,
                        txid = %txid,
                        "createAction: permanent failure handler errored"
                    );
                }
            }
            crate::signer::broadcast_outcome::BroadcastOutcome::ServiceError { details } => {
                // Transition tx+req back to Sending and bump attempts so
                // TaskSendWaiting will actually retry. Log any handler error
                // but don't propagate — the broadcast already happened and the
                // caller's contract is to return the classified outcome.
                if let Err(e) = crate::signer::broadcast_outcome::apply_service_error_outcome(
                    storage,
                    &txid,
                    details.clone(),
                )
                .await
                {
                    tracing::error!(
                        error = %e,
                        txid = %txid,
                        "createAction: service error retry transition failed"
                    );
                }
            }
        }
    }

    let result = SignerCreateActionResult {
        txid: Some(txid),
        tx: if args.options.return_txid_only.0.unwrap_or(false) {
            None
        } else {
            Some(beef_bytes)
        },
        no_send_change,
        send_with_results: process_result.send_with_results.unwrap_or_default(),
        signable_transaction: None,
        not_delayed_results: process_result.not_delayed_results,
    };

    Ok((result, None))
}

/// Build a Beef object containing the transaction and its input proofs.
///
/// Constructs a Beef by:
/// 1. Merging input_beef if available (contains source txs with proofs)
/// 2. Merging the signed/unsigned transaction via merge_raw_tx
pub(crate) fn build_beef(
    tx: &bsv::transaction::transaction::Transaction,
    input_beef: &Option<Vec<u8>>,
) -> WalletResult<Beef> {
    let mut beef = Beef::new(bsv::transaction::beef::BEEF_V1);
    if let Some(ref input_beef_bytes) = input_beef {
        if !input_beef_bytes.is_empty() {
            beef.merge_beef_from_binary(input_beef_bytes)
                .map_err(|e| WalletError::Internal(format!("Failed to merge input BEEF: {}", e)))?;
        }
    }

    let mut raw_tx = Vec::new();
    tx.to_binary(&mut raw_tx)
        .map_err(|e| WalletError::Internal(format!("Failed to serialize tx: {}", e)))?;
    beef.merge_raw_tx(&raw_tx, None)
        .map_err(|e| WalletError::Internal(format!("Failed to merge raw tx: {}", e)))?;

    Ok(beef)
}

/// Serialize a Beef as Atomic BEEF bytes targeting a specific txid.
pub(crate) fn serialize_beef_atomic(beef: &Beef, txid: &str) -> WalletResult<Vec<u8>> {
    beef.to_binary_atomic(txid)
        .map_err(|e| WalletError::Internal(format!("Failed to serialize Atomic BEEF: {}", e)))
}

/// Build Atomic BEEF bytes containing the transaction and its input proofs.
///
/// Convenience wrapper around `build_beef` + `serialize_beef_atomic`.
/// Used for the signable BEEF path (delayed signing) where verification
/// is NOT done since the tx is unsigned.
pub(crate) fn build_beef_bytes(
    tx: &bsv::transaction::transaction::Transaction,
    input_beef: &Option<Vec<u8>>,
) -> WalletResult<Vec<u8>> {
    let txid = tx
        .id()
        .map_err(|e| WalletError::Internal(format!("Failed to compute txid: {}", e)))?;
    let beef = build_beef(tx, input_beef)?;
    serialize_beef_atomic(&beef, &txid)
}

/// Populate `dcr.input_beef` with BEEF proof data for all storage-provided inputs.
///
/// Without this, the outgoing BEEF won't include source tx proofs and
/// recipients/miners will reject it during SPV verification.
///
/// Also merges any stored `inputBEEF` from source transactions (which may
/// contain the original sender's BEEF chain, needed for full verification
/// when our UTXOs came from received payments).
pub(crate) async fn merge_input_beef_signer(
    storage: &WalletStorageManager,
    dcr: &mut crate::storage::action_types::StorageCreateActionResult,
) -> WalletResult<()> {
    use crate::storage::beef::{get_valid_beef_for_txid, TrustSelf};
    use crate::types::StorageProvidedBy;
    use bsv::transaction::beef::{Beef, BEEF_V2};
    use std::collections::HashSet;

    let active = match storage.active() {
        Some(a) => a.clone(),
        None => return Ok(()),
    };

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

    // Merge the base input_beef from storage — this is the foundation.
    if let Some(ref ib) = dcr.input_beef {
        if !ib.is_empty() {
            beef.merge_beef_from_binary(ib).map_err(|e| {
                WalletError::Internal(format!(
                    "Failed to merge base input BEEF ({} bytes): {e}",
                    ib.len()
                ))
            })?;
        }
    }

    // Merge BEEF for each storage-provided input
    let mut known_txids: HashSet<String> = HashSet::new();
    for input in &dcr.inputs {
        if input.provided_by == StorageProvidedBy::Storage {
            let txid = &input.source_txid;
            if !txid.is_empty() && beef.find_txid(txid).is_none() {
                let tx_beef_bytes =
                    get_valid_beef_for_txid(&*active, txid, TrustSelf::No, &known_txids)
                        .await
                        .map_err(|e| {
                            WalletError::Internal(format!(
                                "Failed to fetch BEEF for storage input {txid}: {e}"
                            ))
                        })?
                        .ok_or_else(|| {
                            WalletError::Internal(format!(
                                "No BEEF proof found for storage-provided input {txid}"
                            ))
                        })?;

                beef.merge_beef_from_binary(&tx_beef_bytes).map_err(|e| {
                    WalletError::Internal(format!("Failed to merge BEEF for input {txid}: {e}"))
                })?;

                known_txids.insert(txid.clone());
            }
        }
    }

    // Merge any stored inputBEEF from source transactions.
    // When UTXOs came from received payments, the sender's proof chain
    // is stored as inputBEEF on the source transaction record.
    for input in &dcr.inputs {
        if input.provided_by == StorageProvidedBy::Storage && !input.source_txid.is_empty() {
            let txs = active
                .find_transactions(&crate::storage::find_args::FindTransactionsArgs {
                    partial: crate::storage::find_args::TransactionPartial {
                        txid: Some(input.source_txid.clone()),
                        ..Default::default()
                    },
                    ..Default::default()
                })
                .await
                .map_err(|e| {
                    WalletError::Internal(format!(
                        "Failed to look up source tx {}: {e}",
                        input.source_txid
                    ))
                })?;

            for tx_rec in &txs {
                if let Some(ref ib) = tx_rec.input_beef {
                    if !ib.is_empty() {
                        beef.merge_beef_from_binary(ib).map_err(|e| {
                            WalletError::Internal(format!(
                                "Failed to merge stored inputBEEF for {}: {e}",
                                input.source_txid
                            ))
                        })?;
                    }
                }
            }
        }
    }

    // Serialize back
    if beef.txs.is_empty() {
        dcr.input_beef = None;
    } else {
        let mut buf = Vec::new();
        beef.to_binary(&mut buf).map_err(|e| {
            WalletError::Internal(format!(
                "Failed to serialize merged BEEF ({} txs): {e}",
                beef.txs.len()
            ))
        })?;
        dcr.input_beef = Some(buf);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use bsv::wallet::types::BooleanDefaultFalse;

    #[test]
    fn test_return_txid_only_controls_tx_field() {
        let return_txid_only = BooleanDefaultFalse(Some(true));
        let beef_bytes = vec![1, 2, 3];
        let tx: Option<Vec<u8>> = if return_txid_only.0.unwrap_or(false) {
            None
        } else {
            Some(beef_bytes.clone())
        };
        assert!(tx.is_none());

        let return_txid_only = BooleanDefaultFalse(Some(false));
        let tx: Option<Vec<u8>> = if return_txid_only.0.unwrap_or(false) {
            None
        } else {
            Some(beef_bytes.clone())
        };
        assert!(tx.is_some());

        // Default (None) should behave as false — tx is included
        let return_txid_only = BooleanDefaultFalse(None);
        let tx: Option<Vec<u8>> = if return_txid_only.0.unwrap_or(false) {
            None
        } else {
            Some(beef_bytes)
        };
        assert!(tx.is_some());
    }

    #[test]
    fn test_send_with_conditional() {
        let send_with_txids = vec!["aabb".to_string(), "ccdd".to_string()];

        let is_send_with = true;
        let result: Vec<String> = if is_send_with {
            send_with_txids.clone()
        } else {
            vec![]
        };
        assert_eq!(result.len(), 2);

        let is_send_with = false;
        let result: Vec<String> = if is_send_with {
            send_with_txids
        } else {
            vec![]
        };
        assert!(result.is_empty());
    }
}