zinc-core 0.5.0

Core Rust library for Zinc Bitcoin + Ordinals wallet
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
use crate::ordinals::shield::{
    analyze_psbt, analyze_psbt_with_scope, audit_psbt, is_safe_to_spend, WarningLevel,
};
use std::collections::HashSet;
use bitcoin::psbt::{Input, Psbt};
use bitcoin::transaction::Transaction;
use bitcoin::{Amount, OutPoint, ScriptBuf, TxOut, Txid};
use std::collections::HashMap;
use std::str::FromStr;

// Helper to create a dummy PSBT
fn create_dummy_psbt(inputs: &[(u64, Option<u64>)], outputs: &[u64]) -> Psbt {
    let mut tx = Transaction {
        version: bitcoin::transaction::Version::TWO,
        lock_time: bitcoin::locktime::absolute::LockTime::ZERO,
        input: vec![],
        output: vec![],
    };

    let mut psbt_inputs = vec![];

    for (i, (value, _inscription_offset)) in inputs.iter().enumerate() {
        tx.input.push(bitcoin::TxIn {
            previous_output: OutPoint {
                txid: Txid::from_str(
                    "0000000000000000000000000000000000000000000000000000000000000000",
                )
                .unwrap(),
                vout: u32::try_from(i).unwrap(),
            },
            script_sig: ScriptBuf::new(),
            sequence: bitcoin::Sequence::MAX,
            witness: bitcoin::Witness::default(),
        });

        let input = Input {
            witness_utxo: Some(TxOut {
                value: Amount::from_sat(*value),
                script_pubkey: ScriptBuf::new(), // Dummy script
            }),
            ..Default::default()
        };
        psbt_inputs.push(input);
    }

    for value in outputs {
        tx.output.push(TxOut {
            value: Amount::from_sat(*value),
            script_pubkey: ScriptBuf::new(), // Dummy script
        });
    }

    let mut psbt = Psbt::from_unsigned_tx(tx).unwrap();
    psbt.inputs = psbt_inputs;
    psbt
}

#[test]
fn test_tight_squeeze_burn() {
    // Input: 10,000 sats. Inscription @ 9,999.
    // Output: 9,999 sats.
    // Fee: 1 sat.
    // Expectation: DANGER (Burned to fee).

    let inputs = vec![(10_000, Some(9_999))];
    let outputs = vec![9_999];
    let psbt = create_dummy_psbt(&inputs, &outputs);

    // Build known inscriptions map
    let mut known_inscriptions = HashMap::new();
    // (txid, vout) -> (id, offset)
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[0].previous_output.txid, 0),
        vec![("Inscription 0".to_string(), 9_999_u64)],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest).unwrap();

    assert_eq!(
        result.warning_level,
        WarningLevel::Danger,
        "Inscription at 9,999 should be burned if output is 9,999"
    );
    assert!(result
        .inscriptions_burned
        .contains(&"Inscription 0".to_string()));
}

// Salvage shape (input 10k → [546 postage, recovery], fee in the tail) with the inscription at offset 0:
// it lands in the padded output and is NOT burned. The shield returns Warn (postage was reduced), which
// the service gate ALLOWS — it only refuses Danger/burned. So an offset-0 salvage proceeds.
#[test]
fn test_salvage_offset_zero_is_allowed() {
    let inputs = vec![(10_000, Some(0))];
    let outputs = vec![546, 9_254]; // 200 sats fee in the tail
    let psbt = create_dummy_psbt(&inputs, &outputs);

    let mut known_inscriptions = HashMap::new();
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[0].previous_output.txid, 0),
        vec![("Inscription 0".to_string(), 0_u64)],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest).unwrap();
    // The gate refuses only on Danger or a burned inscription; postage-reduction Warn is allowed.
    assert_ne!(
        result.warning_level,
        WarningLevel::Danger,
        "offset-0 inscription is preserved (in the postage output) → not Danger"
    );
    assert!(
        result.inscriptions_burned.is_empty(),
        "offset-0 inscription is not burned"
    );
}

// Same salvage shape, but the inscription is near the END of the UTXO (offset 9,900), which falls in
// the fee tail → BURNED. The shield must flag Danger so the service gate (assertPsbtPreservesInscriptions)
// refuses to sign. This is the core safety guarantee for sat-surgery.
#[test]
fn test_salvage_high_offset_burn_is_blocked() {
    let inputs = vec![(10_000, Some(9_900))];
    let outputs = vec![546, 9_254]; // outputs cover sats 0..9_800; sats 9_800..10_000 are fee
    let psbt = create_dummy_psbt(&inputs, &outputs);

    let mut known_inscriptions = HashMap::new();
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[0].previous_output.txid, 0),
        vec![("Inscription 0".to_string(), 9_900_u64)],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest).unwrap();
    assert_eq!(
        result.warning_level,
        WarningLevel::Danger,
        "a mid/high-offset inscription that falls in the fee tail must be flagged Danger"
    );
    assert!(
        result.inscriptions_burned.contains(&"Inscription 0".to_string()),
        "the burned inscription must be reported so the gate can refuse it"
    );
}

#[test]
fn test_survivor_boundary() {
    // Input: 10,000 sats. Inscription @ 9,999.
    // Output: 10,000 sats.
    // Fee: 0 sats.
    // Expectation: SAFE.

    let inputs = vec![(10_000, Some(9_999))];
    let outputs = vec![10_000];
    let psbt = create_dummy_psbt(&inputs, &outputs);

    let mut known_inscriptions = HashMap::new();
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[0].previous_output.txid, 0),
        vec![("Inscription 0".to_string(), 9_999_u64)],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest).unwrap();

    assert_eq!(result.warning_level, WarningLevel::Safe);
    assert!(result.inscriptions_burned.is_empty());
}

#[test]
fn test_multi_inscription_utxo() {
    // Input: 20,000 sats.
    // Inscr A @ 5,000. Inscr B @ 15,000.
    // Output 0: 10,000 sats.
    // Output 1: 10,000 sats.
    // Expectation: A -> Out 0, B -> Out 1.

    let inputs = vec![(20_000, None)];
    let outputs = vec![10_000, 10_000];
    let psbt = create_dummy_psbt(&inputs, &outputs);

    let mut known_inscriptions = HashMap::new();
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[0].previous_output.txid, 0),
        vec![
            ("Inscription 0".to_string(), 5_000),
            ("Inscription 1".to_string(), 15_000),
        ],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest).unwrap();

    // Verify A moved to Output 0
    let a_dest = result
        .inscription_destinations
        .get("Inscription 0")
        .unwrap();
    assert_eq!(a_dest.vout, Some(0));

    // Verify B moved to Output 1
    let b_dest = result
        .inscription_destinations
        .get("Inscription 1")
        .unwrap();
    assert_eq!(b_dest.vout, Some(1));
}

#[test]
fn test_mixed_inputs_order() {
    // Input 0: 5,000 (Clean)
    // Input 1: 5,000 (Inscr @ 0)
    // Output 0: 6,000
    // Expectation: Output 0 takes all Input 0 (5k) + 1k of Input 1.
    // Inscr @ 0 of Input 1 is the 5,001st sat overall.
    // Output 0 capacity is 6,000. So Inscr lands @ offset 5,000 of Output 0. SAFE.

    let inputs = vec![(5_000, None), (5_000, Some(0))];
    let outputs = vec![6_000];
    let psbt = create_dummy_psbt(&inputs, &outputs);

    let mut known_inscriptions = HashMap::new();
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[1].previous_output.txid, 1),
        vec![("Inscription 0".to_string(), 0)],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest).unwrap();

    let dest = result
        .inscription_destinations
        .get("Inscription 0")
        .unwrap();
    assert_eq!(dest.vout, Some(0));
}

#[test]
fn test_blind_spot_missing_witness() {
    // Input 0: Value UNKNOWN (Missing witness_utxo)
    // Input 1: Inscription
    // Expectation: ERROR / CANNOT ANALYZE

    let mut psbt = create_dummy_psbt(&[(10_000, None), (10_000, Some(0))], &[20_000]);
    // Sabotage Input 0
    psbt.inputs[0].witness_utxo = None;

    let mut known_inscriptions = HashMap::new();
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[1].previous_output.txid, 1),
        vec![("Inscription 0".to_string(), 0)],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest);
    assert!(result.is_err(), "Should fail if input value is unknown");
}

#[test]
fn test_burial_warning() {
    // Input 0: Inscr (546 sats)
    // Input 1: Payment (1 BTC = 100,000,000 sats)
    // Output 0: 100,000,546 (Consolidated)
    // Expectation: WARN (Merging inscr into large output)

    let inputs = vec![(546, Some(0)), (100_000_000, None)];
    let outputs = vec![100_000_546];
    let psbt = create_dummy_psbt(&inputs, &outputs);

    let mut known_inscriptions = HashMap::new();
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[0].previous_output.txid, 0),
        vec![("Inscription 0".to_string(), 0)],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest).unwrap();
    assert_eq!(
        result.warning_level,
        WarningLevel::Warn,
        "Should warn when burying inscription"
    );
}

#[test]
fn test_random_offset_pointer() {
    // Input: 10,000. Inscription @ 3,500.
    // Output 0: 3,500.
    // Output 1: 6,500.
    // Expectation: Inscr is sat index 3,500 (3,501st sat).
    // Output 0 takes indices 0-3,499.
    // Output 1 takes indices 3,500-9,999.
    // Inscr lands at index 0 of Output 1.

    let inputs = vec![(10_000, Some(3_500))];
    let outputs = vec![3_500, 6_500];
    let psbt = create_dummy_psbt(&inputs, &outputs);

    let mut known_inscriptions = HashMap::new();
    known_inscriptions.insert(
        (psbt.unsigned_tx.input[0].previous_output.txid, 0),
        vec![("Inscription 0".to_string(), 3_500)],
    );

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest).unwrap();

    let dest = result
        .inscription_destinations
        .get("Inscription 0")
        .unwrap();
    assert_eq!(dest.vout, Some(1));
    assert_eq!(dest.offset, 0);
}

#[test]
fn test_split_transaction_safe() {
    // Current Split Flow:
    // Input 0: 100,000 sats (Clean BTC)
    // Output 0: 10,000 sats
    // Output 1: 10,000 sats
    // Output 2: 79,000 sats (Change)
    // Fee: 1,000 sats
    // Expectation: SAFE. No inscriptions.

    let inputs = vec![(100_000, None)];
    let outputs = vec![10_000, 10_000, 79_000];
    let psbt = create_dummy_psbt(&inputs, &outputs);

    let known_inscriptions = HashMap::new(); // Empty

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest)
        .expect("Should analyze successfully even if no inscriptions");

    assert_eq!(result.warning_level, WarningLevel::Safe);
    assert!(result.inscription_destinations.is_empty());
    assert!(result.inscriptions_burned.is_empty());
    assert_eq!(result.fee_sats, 1_000);
}

#[test]
fn test_missing_witness_utxo_error() {
    // Input 0: Value 100,000, but MISSING witness_utxo info in PSBT input
    // Expectation: Err(OrdError::RequestFailed("...missing witness_utxo..."))

    let mut psbt = create_dummy_psbt(&[(100_000, None)], &[99_000]);
    // Sabotage input
    psbt.inputs[0].witness_utxo = None;

    let known_inscriptions = HashMap::new();

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest);

    assert!(result.is_err());
    let err = result.unwrap_err();
    match err {
        crate::ordinals::error::OrdError::RequestFailed(msg) => {
            assert!(
                msg.contains("missing witness_utxo data"),
                "Error message should mention missing witness_utxo"
            );
        }
    }
}

#[test]
fn test_fallback_to_non_witness_utxo() {
    // Input 0: Missing witness_utxo, but HAS non_witness_utxo (Legacy/SegWit via PSBT fallback)
    // Expectation: SAFE (Should fallback and read value)

    let mut psbt = create_dummy_psbt(&[(10_000, None)], &[9_000]);

    // 1. Remove witness_utxo
    psbt.inputs[0].witness_utxo = None;

    // 2. Add non_witness_utxo (Legacy TxOut)
    let legacy_tx = Transaction {
        version: bitcoin::transaction::Version::TWO,
        lock_time: bitcoin::locktime::absolute::LockTime::ZERO,
        input: vec![], // Inputs don't matter for this check usually, just the output at vout
        output: vec![TxOut {
            value: Amount::from_sat(10_000),
            script_pubkey: ScriptBuf::new(),
        }],
    };
    psbt.inputs[0].non_witness_utxo = Some(legacy_tx);

    let known_inscriptions = HashMap::new();

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest)
        .expect("Should succeed by falling back to non_witness_utxo");

    assert_eq!(result.warning_level, WarningLevel::Safe);
    assert_eq!(result.fee_sats, 1_000);
}
#[test]
fn test_analyze_sighash_warning() {
    // Input 0: SIGHASH_NONE (Danger)
    // Expectation: DANGER + Warning in result

    let inputs = vec![(10_000, None)];
    let outputs = vec![9_000];
    let mut psbt = create_dummy_psbt(&inputs, &outputs);

    // Set dangerous SIGHASH (SIGHASH_NONE = 2)
    psbt.inputs[0].sighash_type = Some(bitcoin::psbt::PsbtSighashType::from_u32(2));

    let known_inscriptions: HashMap<(Txid, u32), Vec<(String, u64)>> = HashMap::new();

    let result = analyze_psbt(&psbt, &known_inscriptions, bitcoin::Network::Regtest)
        .expect("Analysis should succeed");

    assert_eq!(
        result.warning_level,
        WarningLevel::Danger,
        "SIGHASH_NONE should trigger Danger"
    );
    assert!(!result.warnings.is_empty(), "Should have warnings");
    assert!(
        result.warnings[0].contains("SIGHASH_NONE"),
        "Warning should mention SIGHASH_NONE"
    );
}

#[test]
fn is_safe_to_spend_reflects_membership() {
    let op = OutPoint {
        txid: Txid::from_str(
            "0000000000000000000000000000000000000000000000000000000000000000",
        )
        .unwrap(),
        vout: 7,
    };
    let mut protected = HashSet::new();
    assert!(is_safe_to_spend(&op, &protected), "unknown outpoint is spendable");
    protected.insert(op);
    assert!(!is_safe_to_spend(&op, &protected), "protected outpoint is not spendable");
}

#[test]
fn audit_psbt_accepts_a_clean_psbt() {
    // One funded input, one output, no known inscriptions → analysis succeeds.
    let psbt = create_dummy_psbt(&[(10_000, None)], &[9_000]);
    let known = HashMap::new();
    assert!(audit_psbt(&psbt, &known, None, bitcoin::Network::Regtest).is_ok());
}

#[test]
fn audit_and_analyze_respect_input_scope_subset() {
    let psbt = create_dummy_psbt(&[(10_000, None), (20_000, None)], &[25_000]);
    let known = HashMap::new();
    // Scope limited to input 0 only.
    assert!(audit_psbt(&psbt, &known, Some(&[0]), bitcoin::Network::Regtest).is_ok());
    let scoped =
        analyze_psbt_with_scope(&psbt, &known, Some(&[0]), bitcoin::Network::Regtest).unwrap();
    let full = analyze_psbt(&psbt, &known, bitcoin::Network::Regtest).unwrap();
    // Both analyses complete; full sees both inputs, scoped is constrained to one.
    let _ = (&scoped, &full);
}

#[test]
fn analyze_psbt_with_scope_rejects_out_of_range_index() {
    let psbt = create_dummy_psbt(&[(10_000, None)], &[9_000]);
    let known = HashMap::new();
    assert!(
        analyze_psbt_with_scope(&psbt, &known, Some(&[5]), bitcoin::Network::Regtest).is_err(),
        "an out-of-range scope index must be rejected"
    );
}