rostrum 8.0.0

An efficient implementation of Electrum Server with token support
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
use anyhow::Result;
use std::{
    cmp::Ordering,
    collections::{HashMap, HashSet},
};

use bitcoin_hashes::{hex::ToHex, Hash};
use bitcoincash::Txid;
use rayon::prelude::*;
use sha1::Digest;
use sha2::Sha256;

use crate::{
    chaindef::{OutPointHash, ScriptHash, TokenID},
    indexes::{
        outputindex::OutputIndexRow,
        scripthashindex::{OutputFlags, ScriptHashIndexRow},
        DBRow,
    },
    mempool::{ConfirmationState, Tracker},
    query::queryutil::token_from_outpoint,
    store::{DBContents, DBStore},
    timeout::{
        par_timeout_collect, par_timeout_collect_boxed, par_timeout_collect_vec, TimeoutTrigger,
    },
};

use super::queryutil::{get_output_rows, height_by_txid, output_is_spent, tx_spending_outpoint};

#[derive(Serialize)]
pub struct HistoryItem {
    pub tx_hash: Txid,
    pub height: i32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fee: Option<u64>, // need to be set only for unconfirmed transactions (i.e. height <= 0)
}

#[derive(Serialize)]
pub struct UnspentItem {
    #[serde(rename = "tx_hash")]
    pub txid: Txid,
    #[serde(rename = "tx_pos")]
    pub vout: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub outpoint_hash: Option<OutPointHash>,
    pub height: u32,
    pub value: u64,

    #[cfg(feature = "nexa")]
    #[serde(skip_serializing_if = "Option::is_none", rename = "token_id_hex")]
    pub token_id: Option<TokenID>,

    #[cfg(not(feature = "nexa"))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_id: Option<TokenID>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_amount: Option<i64>,
}

/**
 * For sorting history items by confirmation height (and then ID)
 */
pub(crate) fn by_block_height(a: &HistoryItem, b: &HistoryItem) -> Ordering {
    if a.height == b.height {
        // Order by little endian tx hash if height is the same,
        // in most cases, this order is the same as on the blockchain.
        return b.tx_hash.cmp(&a.tx_hash);
    }
    if a.height > 0 && b.height > 0 {
        return a.height.cmp(&b.height);
    }

    // mempool txs should be sorted last, so add to it a large number
    // per spec, mempool entries do not need to be sorted, but we do it
    // anyway so that statushash is deterministic
    let mut a_height = a.height;
    let mut b_height = b.height;
    if a_height <= 0 {
        a_height = 0xEE_EEEE + a_height.abs();
    }
    if b_height <= 0 {
        b_height = 0xEE_EEEE + b_height.abs();
    }
    a_height.cmp(&b_height)
}

/**
 * Find output rows given filter parameters.
 *
 * This is an expensive call used by  most blockchain.scripthash.* queries.
 */
fn scan_for_outputs(
    store: &DBStore,
    scripthash: ScriptHash,
    output_flags: OutputFlags,
    filter_token: Option<TokenID>,
) -> Box<impl '_ + ParallelIterator<Item = OutputIndexRow>> {
    let scripthash_filter = match output_flags {
        OutputFlags::None => ScriptHashIndexRow::filter_by_scripthash(scripthash.into_inner()),
        OutputFlags::HasTokens => {
            ScriptHashIndexRow::filter_by_scripthash_with_token(scripthash.into_inner())
        }
    };
    let scripthashes = store
        .scan(ScriptHashIndexRow::CF, scripthash_filter)
        .map(|r| ScriptHashIndexRow::from_row(&r))
        .map(|r| r.outpointhash())
        .collect::<Vec<OutPointHash>>();

    // get_output_rows is an expensive call, so we collect outpoint hashes above
    // so that we can call it in parallel.
    Box::new(
        scripthashes
            .into_par_iter()
            .flat_map(move |outpointhash| {
                get_output_rows(store, &outpointhash)
                    .collect::<Vec<OutputIndexRow>>()
                    .into_par_iter()
            })
            .filter(move |o| {
                if let Some(filter) = &filter_token {
                    debug_assert!(output_flags == OutputFlags::HasTokens);
                    match token_from_outpoint(store, &o.hash()) {
                        Some((t, _)) => &t == filter,
                        None => false,
                    }
                } else {
                    true
                }
            }),
    )
}

/**
 * Calculate coin balance in scripthash that has been confirmed in blocks.
 */
pub fn confirmed_scripthash_balance(
    index: &DBStore,
    scripthash: ScriptHash,
    timeout: &TimeoutTrigger,
) -> Result<(i64, Vec<(i64, OutPointHash)>)> {
    assert!(index.contents == DBContents::ConfirmedIndex);
    let outputs = par_timeout_collect_vec::<(i64, OutPointHash)>(
        timeout,
        scan_for_outputs(index, scripthash, OutputFlags::None, None)
            .map(|o| (o.value(), o.take_hash()))
            .map(|(value, outpoint)| {
                if output_is_spent(index, outpoint) {
                    // Output was created AND spent in the same index. Zero it out.
                    (0, outpoint)
                } else {
                    (value as i64, outpoint)
                }
            }),
    )?;

    let amount = outputs.par_iter().map(|(value, _)| value).sum();

    // Only return unspent confirmed outputs
    let outputs = outputs
        .into_iter()
        .filter(|(amount, _)| amount > &0)
        .collect();

    Ok((amount, outputs))
}

/**
 * Calculate coin balance in scripthash that has been confirmed in blocks.
 *
 * Takes confirmed_outputs in to be able to see if mempool spends confirmed utxos.
 */
pub fn unconfirmed_scripthash_balance(
    mempool: &DBStore,
    confirmed_outputs: Vec<(i64, OutPointHash)>,
    scripthash: ScriptHash,
    timeout: &TimeoutTrigger,
) -> Result<i64> {
    assert!(DBContents::MempoolIndex == mempool.contents);

    let unconfirmed_outputs = par_timeout_collect_vec::<i64>(
        timeout,
        scan_for_outputs(mempool, scripthash, OutputFlags::None, None)
            .map(|o| (o.value(), o.take_hash()))
            .map(|(value, outpoint)| {
                if output_is_spent(mempool, outpoint) {
                    // Output was created AND spent in the same index. Zero it out.
                    0
                } else {
                    value as i64
                }
            }),
    )?;

    let amount: i64 = unconfirmed_outputs.par_iter().sum();

    // Subtract spends from confirmed utxos
    let spent_confirmed: i64 = confirmed_outputs
        .into_par_iter()
        .map(|(value, out)| {
            assert!(value >= 0);
            if output_is_spent(mempool, out) {
                value
            } else {
                0
            }
        })
        .sum::<i64>();

    Ok(amount - spent_confirmed)
}

// Used in .reduce for merging maps
fn merge_token_balance_maps(
    mut a: HashMap<TokenID, i64>,
    b: HashMap<TokenID, i64>,
) -> HashMap<TokenID, i64> {
    for (token_id, amount) in b {
        a.entry(token_id)
            .and_modify(|a| {
                *a += amount;
            })
            .or_insert(amount);
    }
    a
}

/**
 * Calculate token balance in a given store.
 */
fn calc_token_balance(
    store: &DBStore,
    scripthash: ScriptHash,
    timeout: &TimeoutTrigger,
) -> Result<(HashMap<TokenID, i64>, Vec<OutPointHash>)> {
    let outputs = par_timeout_collect_vec::<OutPointHash>(
        timeout,
        scan_for_outputs(store, scripthash, OutputFlags::HasTokens, None).map(|o| o.take_hash()),
    )?;

    #[allow(clippy::redundant_closure)]
    let balance: HashMap<TokenID, i64> = outputs
        .par_iter()
        .map(|outpoint| {
            let (token_id, amount) = token_from_outpoint(store, outpoint)
                .expect("token info found for outpoint {outpoint}");
            if output_is_spent(store, *outpoint) {
                // Output was created AND spent in the same index. Zero it out.
                (token_id, 0)
            } else {
                (token_id, amount)
            }
        })
        .fold(
            || HashMap::<TokenID, i64>::default(),
            |mut map, (token_id, amount)| {
                map.entry(token_id)
                    .and_modify(|a| {
                        *a += amount;
                    })
                    .or_insert(amount);
                map
            },
        )
        .reduce(|| HashMap::default(), merge_token_balance_maps);

    Ok((balance, outputs))
}

/**
 * Get the unconfirmed token balance
 */
pub(crate) fn unconfirmed_scripthash_token_balance(
    mempool: &DBStore,
    index: &DBStore,
    confirmed_outputs: Vec<OutPointHash>,
    scripthash: ScriptHash,
    timeout: &TimeoutTrigger,
) -> Result<HashMap<TokenID, i64>> {
    assert!(mempool.contents == DBContents::MempoolIndex);
    assert!(index.contents == DBContents::ConfirmedIndex);

    // This finds the balance of entries that have been both created and spent
    // in the mempool. It cannot see spends of outputs thave have been confirmed.
    let (balance, _) = calc_token_balance(mempool, scripthash, timeout)?;

    // Find inputs that spends from confirmed outputs as well
    #[allow(clippy::redundant_closure)]
    let spends_of_confirmed = confirmed_outputs
        .into_par_iter()
        .map(|outpoint| {
            if output_is_spent(mempool, outpoint) {
                let (token_id, amount) = token_from_outpoint(index, &outpoint)
                    .expect("token info found for outpoint {outpoint}");
                (token_id, -amount)
            } else {
                // This output was funded in the confirmed index, not mempool.
                // If it's not spent here, then ignore it.
                (TokenID::all_zeros(), 0)
            }
        })
        .fold(
            || HashMap::<TokenID, i64>::default(),
            |mut map, (token_id, amount)| {
                map.entry(token_id)
                    .and_modify(|a| {
                        *a += amount;
                    })
                    .or_insert(amount);
                map
            },
        )
        .reduce(|| HashMap::default(), merge_token_balance_maps);

    // Merge in spends of confirmed outputs
    let mut balance = merge_token_balance_maps(balance, spends_of_confirmed);
    balance.remove(&TokenID::all_zeros());

    Ok(balance)
}

/**
 * Get the confirmed token balance
 */
pub(crate) fn confirmed_scripthash_token_balance(
    store: &DBStore,
    scripthash: ScriptHash,
    timeout: &TimeoutTrigger,
) -> Result<(HashMap<TokenID, i64>, Vec<OutPointHash>)> {
    calc_token_balance(store, scripthash, timeout)
}

/**
 * Find all transactions that spend of fund scripthash.
 *
 * Parameter 'additional_outpoints' is for funding utxos from other indexes.
 * For mempool, this parameter is needed to be able to locate spends of confirmed outputs
 * (as those outputs are not funded in the mempool)
 */
pub(crate) fn scripthash_transactions(
    store: &DBStore,
    scripthash: ScriptHash,
    output_flags: OutputFlags,
    filter_token: Option<TokenID>,
    additional_outputs: Vec<OutPointHash>,
    timeout: &TimeoutTrigger,
) -> Result<(HashSet<Txid>, Vec<OutPointHash>)> {
    let outputs = par_timeout_collect_boxed::<OutputIndexRow>(
        timeout,
        scan_for_outputs(store, scripthash, output_flags, filter_token),
    )?;

    let (mut funder_txid, outpoints): (HashSet<Txid>, Vec<OutPointHash>) =
        outputs.into_iter().map(|o| (o.txid(), o.hash())).unzip();

    let spender_txids: HashSet<Txid> = par_timeout_collect::<Txid, HashSet<Txid>>(
        timeout,
        outpoints
            .par_iter()
            .chain(additional_outputs.par_iter())
            .filter_map(|o| tx_spending_outpoint(store, o).map(|input| input.txid())),
    )?;
    funder_txid.extend(spender_txids.into_iter());
    Ok((funder_txid, outpoints))
}

/**
 * Get outputs that have been confirmed on the blockchain given filter parameters.
 */
pub(crate) fn get_confirmed_outputs(
    index: &DBStore,
    scripthash: ScriptHash,
    output_flags: OutputFlags,
    filter_token: Option<TokenID>,
    timeout: &TimeoutTrigger,
) -> Result<Vec<OutPointHash>> {
    assert!(index.contents == DBContents::ConfirmedIndex);
    par_timeout_collect::<OutPointHash, _>(
        timeout,
        scan_for_outputs(index, scripthash, output_flags, filter_token).map(|o| o.hash()),
    )
}

/**
 * Generate list of HistoryItem for a scripthashes confirmed history.
 *
 * Also returns confirmed outputs that can be used to get unconfirmed spends
 * of confirmed utxos.
 */
fn confirmed_history(
    store: &DBStore,
    scripthash: ScriptHash,
    output_flags: OutputFlags,
    filter_token: Option<TokenID>,
    timeout: &TimeoutTrigger,
) -> Result<(Vec<HistoryItem>, Vec<OutPointHash>)> {
    let (txids, outputs) = scripthash_transactions(
        store,
        scripthash,
        output_flags,
        filter_token,
        vec![],
        timeout,
    )?;

    let history = txids
        .into_par_iter()
        .map(|txid| {
            let height = match height_by_txid(store, txid) {
                Some(h) => h,
                None => {
                    debug_assert!(false, "Confirmed tx cannot be missing height");
                    0
                }
            };
            HistoryItem {
                tx_hash: txid,
                height: height as i32,
                fee: None,
            }
        })
        .collect();
    Ok((history, outputs))
}

/**
 * Generate list of HistoryItem for a scripthashes unconfirmed history
 */
pub fn unconfirmed_history(
    mempool: &Tracker,
    confirmed_outputs: Vec<OutPointHash>,
    scripthash: ScriptHash,
    output_flags: OutputFlags,
    filter_token: Option<TokenID>,
    timeout: &TimeoutTrigger,
) -> Result<Vec<HistoryItem>> {
    let (txids, _) = scripthash_transactions(
        mempool.index(),
        scripthash,
        output_flags,
        filter_token,
        confirmed_outputs,
        timeout,
    )?;

    Ok(txids
        .into_par_iter()
        .map(|txid| {
            let height = match mempool.tx_confirmation_state(&txid, None) {
                ConfirmationState::InMempool => 0,
                ConfirmationState::UnconfirmedParent => -1,
                ConfirmationState::Indeterminate | ConfirmationState::Confirmed => {
                    debug_assert!(
                        false,
                        "Mempool tx's state cannot be indeterminate or confirmed"
                    );
                    0
                }
            };
            HistoryItem {
                tx_hash: txid,
                height,
                fee: mempool.get_fee(&txid),
            }
        })
        .collect())
}

pub fn scripthash_history(
    store: &DBStore,
    mempool: &Tracker,
    scripthash: ScriptHash,
    output_flags: OutputFlags,
    filter_token: Option<TokenID>,
    timeout: &TimeoutTrigger,
) -> Result<Vec<HistoryItem>> {
    let (mut history, confirmed_outputs) = confirmed_history(
        store,
        scripthash,
        output_flags,
        filter_token.clone(),
        timeout,
    )?;

    history.extend(
        unconfirmed_history(
            mempool,
            confirmed_outputs,
            scripthash,
            output_flags,
            filter_token,
            timeout,
        )?
        .into_iter(),
    );

    history.par_sort_unstable_by(by_block_height);

    Ok(history)
}

/**
 * Generate a hash of scripthash history as defined in electrum spec
 */
pub fn hash_scripthash_history(history: &Vec<HistoryItem>) -> Option<[u8; 32]> {
    if history.is_empty() {
        None
    } else {
        let mut sha2 = Sha256::new();
        let parts: Vec<String> = history
            .into_par_iter()
            .map(|t| format!("{}:{}:", t.tx_hash.to_hex(), t.height))
            .collect();

        for p in parts {
            sha2.update(p.as_bytes());
        }
        Some(sha2.finalize().into())
    }
}

pub(crate) fn scripthash_listunspent(
    store: &DBStore,
    mempool: &DBStore,
    scripthash: ScriptHash,
    output_flags: OutputFlags,
    filter_token: Option<TokenID>,
    timeout: &TimeoutTrigger,
) -> Result<Vec<UnspentItem>> {
    assert!(store.contents == DBContents::ConfirmedIndex);
    assert!(mempool.contents == DBContents::MempoolIndex);

    let confirmed = scan_for_outputs(store, scripthash, output_flags, filter_token.clone())
        .filter(|out| !output_is_spent(store, out.hash()))
        .map(|out| {
            let txid = out.txid();

            (out, height_by_txid(store, txid).expect("height missing"))
        });
    let unconfirmed = scan_for_outputs(mempool, scripthash, output_flags, filter_token.clone())
        .filter(|out| !output_is_spent(mempool, out.hash()))
        .map(|out| {
            (out, 0 /* mempool height */)
        });

    let unspent_outputs = confirmed.chain(unconfirmed);

    // Fetch token info
    let unspent_outputs = unspent_outputs.filter_map(|(output, height)| {
        if output_flags == OutputFlags::HasTokens {
            let (token_id, amount) =
                token_from_outpoint(store, &output.hash()).unwrap_or_else(|| {
                    token_from_outpoint(mempool, &output.hash()).expect("missing token info")
                });

            if let Some(filter) = &filter_token {
                if filter == &token_id {
                    Some((output, height, Some(token_id), Some(amount)))
                } else {
                    None
                }
            } else {
                Some((output, height, Some(token_id), Some(amount)))
            }
        } else {
            Some((output, height, None, None))
        }
    });

    // Collect into json-serializable objects
    let unspent_outputs = unspent_outputs.map(|(out, height, token_id, token_amount)| {
        #[cfg(feature = "nexa")]
        {
            // With nexa, we also want outpoint hash
            UnspentItem {
                txid: out.txid(),
                vout: out.index(),
                outpoint_hash: Some(out.hash()),
                height,
                value: out.value(),
                token_id,
                token_amount,
            }
        }
        #[cfg(not(feature = "nexa"))]
        {
            UnspentItem {
                txid: out.txid(),
                vout: out.index(),
                outpoint_hash: None,
                height,
                value: out.value(),
                token_id,
                token_amount,
            }
        }
    });

    let mut unspent = par_timeout_collect_vec::<UnspentItem>(timeout, unspent_outputs)?;

    unspent.par_sort_by_key(|u| u.height);

    Ok(unspent)
}