rostrum 14.0.1

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
use std::collections::{HashMap, VecDeque};

use crate::chaindef::Transaction;
#[cfg(nexa)]
use crate::encode::{compute_outpoint_hash_from_tx, outpoint_hash};
use crate::mempool::MempoolEntry;
use bitcoincash::hash_types::Txid;

#[cfg(all(test, not(nexa)))]
use std::collections::HashSet;

// TTOR sort a list of transactions (old algo; used in tests for comparison)
#[cfg(all(test, not(nexa)))]
pub fn ttor_sorted(txs: Vec<Transaction>) -> Vec<Transaction> {
    let txs = {
        let mut queue: VecDeque<Transaction> = txs.into_iter().collect();

        let mut queue_txids: HashSet<Txid> = queue.iter().map(|tx| tx.txid()).collect();

        let mut txs: Vec<Transaction> = Vec::with_capacity(queue.len());

        while let Some(tx) = queue.pop_front() {
            let mut has_parent = false;

            for i in &tx.input {
                if queue_txids.contains(&i.previous_output.txid) {
                    // depends on parent
                    has_parent = true;
                    break;
                };
            }

            if has_parent {
                queue.push_back(tx);
            } else {
                queue_txids.remove(&tx.txid());
                txs.push(tx);
            }
        }
        txs
    };
    txs
}

/// Alternative implementation using Kahn's algorithm for topological sorting
/// This is more efficient with O(V + E) complexity and handles cycles gracefully
///
/// Note: This implementation may produce different but equally valid topological orderings
/// compared to the original `ttor_sorted` function. Both implementations respect
/// transaction dependencies, but may order independent transactions differently.
pub fn ttor_sorted_kahn(txs: Vec<Transaction>) -> Vec<Transaction> {
    if txs.is_empty() {
        return Vec::new();
    }

    // Build adjacency list and in-degree count
    let mut graph: HashMap<Txid, Vec<Txid>> = HashMap::new();
    let mut in_degree: HashMap<Txid, usize> = HashMap::new();
    let mut tx_map: HashMap<Txid, Transaction> = HashMap::new();

    // Initialize data structures
    for tx in txs {
        let txid = tx.txid();
        tx_map.insert(txid, tx);
        in_degree.insert(txid, 0);
        graph.insert(txid, Vec::new());
    }

    // Build the dependency graph
    // First, create a map of outpointhash -> txid for all outputs in our transaction set
    #[cfg(nexa)]
    let mut outpoint_to_txid: HashMap<crate::chaindef::OutPointHash, Txid> = HashMap::new();
    #[cfg(nexa)]
    for (txid, tx) in &tx_map {
        for (out_idx, _) in tx.output.iter().enumerate() {
            let oph = compute_outpoint_hash_from_tx(tx, out_idx as u32);
            outpoint_to_txid.insert(oph, *txid);
        }
    }

    for (txid, tx) in &tx_map {
        for input in &tx.input {
            #[cfg(bch)]
            let parent_txid = input.previous_output.txid;

            #[cfg(nexa)]
            let parent_txid = {
                let input_oph = outpoint_hash(&input.previous_output);
                match outpoint_to_txid.get(&input_oph) {
                    Some(&parent) => parent,
                    None => continue, // Parent not in our transaction set
                }
            };

            // Only consider dependencies within our transaction set
            if tx_map.contains_key(&parent_txid) {
                // Add edge from parent to current transaction
                graph.entry(parent_txid).or_default().push(*txid);

                // Increment in-degree of current transaction
                *in_degree.entry(*txid).or_default() += 1;
            }
        }
    }

    // Kahn's algorithm: find nodes with no incoming edges
    let mut queue: VecDeque<Txid> = VecDeque::new();
    for (txid, &degree) in &in_degree {
        if degree == 0 {
            queue.push_back(*txid);
        }
    }

    let mut result: Vec<Transaction> = Vec::with_capacity(tx_map.len());

    // Process nodes in topological order
    while let Some(txid) = queue.pop_front() {
        result.push(tx_map.remove(&txid).unwrap());

        // Remove edges from this node and update in-degrees
        if let Some(children) = graph.get(&txid) {
            for &child_txid in children {
                if let Some(degree) = in_degree.get_mut(&child_txid) {
                    *degree -= 1;
                    if *degree == 0 {
                        queue.push_back(child_txid);
                    }
                }
            }
        }
    }

    // Add any remaining transactions (handles cycles and orphaned transactions)
    // This matches the original implementation's behavior
    for (_, tx) in tx_map {
        result.push(tx);
    }

    result
}

/// Sort MempoolEntry by TTOR (Transaction Time Ordering Rule)
/// This ensures that parent transactions are added before their children
pub fn ttor_sorted_mempool_entries(entries: Vec<MempoolEntry>) -> Vec<MempoolEntry> {
    if entries.is_empty() {
        return Vec::new();
    }

    // Create a map from txid to MempoolEntry for efficient lookup
    let mut entry_map: HashMap<Txid, MempoolEntry> =
        entries.into_iter().map(|e| (e.tx().txid(), e)).collect();

    // Extract transactions for sorting (borrow from entries in map)
    let txs: Vec<Transaction> = entry_map.values().map(|e| e.tx().clone()).collect();
    let sorted_txs = ttor_sorted_kahn(txs);

    // Reorder entries according to sorted transaction order
    sorted_txs
        .into_iter()
        .filter_map(|tx| entry_map.remove(&tx.txid()))
        .collect()
}

#[cfg(all(test, not(nexa)))]
mod tests {
    use super::*;
    use bitcoin_hashes::{sha256d, Hash};
    use bitcoincash::{OutPoint, PackedLockTime, Script, Sequence, TxIn, TxOut, Witness};

    fn create_mock_transaction(txid: [u8; 32], inputs: Vec<[u8; 32]>) -> Transaction {
        let tx_inputs: Vec<TxIn> = inputs
            .into_iter()
            .map(|input_txid| TxIn {
                previous_output: OutPoint {
                    txid: Txid::from_hash(sha256d::Hash::from_inner(input_txid)),
                    vout: 0,
                },
                script_sig: Script::new(),
                sequence: Sequence(0),
                witness: Witness::new(),
            })
            .collect();

        // Create a transaction with a unique txid by using the provided txid parameter
        // We need to create a transaction that has the desired txid when txid() is called
        let mut tx = Transaction {
            version: 1,
            lock_time: PackedLockTime(0),
            input: tx_inputs,
            output: vec![TxOut {
                value: 1000,
                script_pubkey: Script::new(),
                token: None,
            }],
        };

        // For testing purposes, we'll create transactions with different outputs to ensure different txids
        // The txid is calculated from the transaction content, so we need to make them different
        tx.output[0].value = txid[0] as u64 * 1000; // Use first byte of txid to make value unique

        tx
    }

    /// Create a mock transaction with proper dependency relationships
    /// This function creates transactions where input txids actually match the txids of referenced transactions
    fn create_mock_transaction_with_deps(
        base_txid: [u8; 32],
        parent_txs: &[Transaction],
    ) -> Transaction {
        let tx_inputs: Vec<TxIn> = parent_txs
            .iter()
            .map(|parent_tx| TxIn {
                previous_output: OutPoint {
                    txid: parent_tx.txid(),
                    vout: 0,
                },
                script_sig: Script::new(),
                sequence: Sequence(0),
                witness: Witness::new(),
            })
            .collect();

        let mut tx = Transaction {
            version: 1,
            lock_time: PackedLockTime(0),
            input: tx_inputs,
            output: vec![TxOut {
                value: 1000,
                script_pubkey: Script::new(),
                token: None,
            }],
        };

        // Make the transaction unique by using the base_txid
        tx.output[0].value = base_txid[0] as u64 * 1000;

        tx
    }

    #[test]
    fn test_simple_chain() {
        // Create a simple chain: A -> B -> C
        let tx_a = create_mock_transaction([1; 32], vec![]);
        let tx_b = create_mock_transaction_with_deps([2; 32], &[tx_a.clone()]);
        let tx_c = create_mock_transaction_with_deps([3; 32], &[tx_b.clone()]);

        let txs = vec![tx_c.clone(), tx_a.clone(), tx_b.clone()];

        let result_original = ttor_sorted(txs.clone());
        let result_kahn = ttor_sorted_kahn(txs);

        // Both should produce the same number of transactions
        assert_eq!(result_original.len(), 3);
        assert_eq!(result_kahn.len(), 3);

        // Both should contain all transactions
        let original_txids: HashSet<Txid> = result_original.iter().map(|tx| tx.txid()).collect();
        let kahn_txids: HashSet<Txid> = result_kahn.iter().map(|tx| tx.txid()).collect();
        assert_eq!(original_txids, kahn_txids);

        // Verify dependencies are respected in both results
        verify_dependencies_respected(&result_original);
        verify_dependencies_respected(&result_kahn);
    }

    #[test]
    fn test_diamond_dependency() {
        // Create a diamond dependency: A -> B, A -> C, B -> D, C -> D
        let tx_a = create_mock_transaction([1; 32], vec![]);
        let tx_b = create_mock_transaction_with_deps([2; 32], &[tx_a.clone()]);
        let tx_c = create_mock_transaction_with_deps([3; 32], &[tx_a.clone()]);
        let tx_d = create_mock_transaction_with_deps([4; 32], &[tx_b.clone(), tx_c.clone()]);

        let txs = vec![tx_d.clone(), tx_c.clone(), tx_b.clone(), tx_a.clone()];

        let result_original = ttor_sorted(txs.clone());
        let result_kahn = ttor_sorted_kahn(txs);

        // Both should produce the same number of transactions
        assert_eq!(result_original.len(), 4);
        assert_eq!(result_kahn.len(), 4);

        // Both should contain all transactions
        let original_txids: HashSet<Txid> = result_original.iter().map(|tx| tx.txid()).collect();
        let kahn_txids: HashSet<Txid> = result_kahn.iter().map(|tx| tx.txid()).collect();
        assert_eq!(original_txids, kahn_txids);

        // Verify dependencies are respected in both results
        verify_dependencies_respected(&result_original);
        verify_dependencies_respected(&result_kahn);
    }

    #[test]
    fn test_independent_transactions() {
        // Create independent transactions (no dependencies)
        let tx_a = create_mock_transaction([1; 32], vec![]);
        let tx_b = create_mock_transaction([2; 32], vec![]);
        let tx_c = create_mock_transaction([3; 32], vec![]);

        let txs = vec![tx_c.clone(), tx_a.clone(), tx_b.clone()];

        let result_original = ttor_sorted(txs.clone());
        let result_kahn = ttor_sorted_kahn(txs);

        // Both should produce the same number of transactions
        assert_eq!(result_original.len(), 3);
        assert_eq!(result_kahn.len(), 3);

        // Both should contain all transactions
        let original_txids: HashSet<Txid> = result_original.iter().map(|tx| tx.txid()).collect();
        let kahn_txids: HashSet<Txid> = result_kahn.iter().map(|tx| tx.txid()).collect();
        assert_eq!(original_txids, kahn_txids);

        // For independent transactions, both should produce valid orderings
        verify_dependencies_respected(&result_original);
        verify_dependencies_respected(&result_kahn);
    }

    #[test]
    fn test_empty_input() {
        let txs: Vec<Transaction> = vec![];

        let result_original = ttor_sorted(txs.clone());
        let result_kahn = ttor_sorted_kahn(txs);

        assert_eq!(result_original.len(), 0);
        assert_eq!(result_kahn.len(), 0);
    }

    #[test]
    fn test_single_transaction() {
        let tx = create_mock_transaction([1; 32], vec![]);
        let txs = vec![tx.clone()];

        let result_original = ttor_sorted(txs.clone());
        let result_kahn = ttor_sorted_kahn(txs);

        assert_eq!(result_original.len(), 1);
        assert_eq!(result_kahn.len(), 1);
        assert_eq!(result_original[0].txid(), tx.txid());
        assert_eq!(result_kahn[0].txid(), tx.txid());
    }

    #[test]
    fn test_complex_dependency() {
        // Create a more complex dependency graph
        // A -> B -> D
        // A -> C -> D
        // E -> F -> G
        // H (independent)
        let tx_a = create_mock_transaction([1; 32], vec![]);
        let tx_b = create_mock_transaction_with_deps([2; 32], &[tx_a.clone()]);
        let tx_c = create_mock_transaction_with_deps([3; 32], &[tx_a.clone()]);
        let tx_d = create_mock_transaction_with_deps([4; 32], &[tx_b.clone(), tx_c.clone()]);
        let tx_e = create_mock_transaction([5; 32], vec![]);
        let tx_f = create_mock_transaction_with_deps([6; 32], &[tx_e.clone()]);
        let tx_g = create_mock_transaction_with_deps([7; 32], &[tx_f.clone()]);
        let tx_h = create_mock_transaction([8; 32], vec![]);

        let txs = vec![
            tx_g.clone(),
            tx_f.clone(),
            tx_e.clone(),
            tx_d.clone(),
            tx_c.clone(),
            tx_b.clone(),
            tx_a.clone(),
            tx_h.clone(),
        ];

        let result_original = ttor_sorted(txs.clone());
        let result_kahn = ttor_sorted_kahn(txs);

        // Both should produce the same number of transactions
        assert_eq!(result_original.len(), 8);
        assert_eq!(result_kahn.len(), 8);

        // Both should contain all transactions
        let original_txids: HashSet<Txid> = result_original.iter().map(|tx| tx.txid()).collect();
        let kahn_txids: HashSet<Txid> = result_kahn.iter().map(|tx| tx.txid()).collect();
        assert_eq!(original_txids, kahn_txids);

        // Verify dependencies are respected in both results
        verify_dependencies_respected(&result_original);
        verify_dependencies_respected(&result_kahn);
    }

    /// Helper function to verify that dependencies are respected in a transaction ordering
    fn verify_dependencies_respected(txs: &[Transaction]) {
        let tx_positions: HashMap<Txid, usize> = txs
            .iter()
            .enumerate()
            .map(|(pos, tx)| (tx.txid(), pos))
            .collect();

        for (pos, tx) in txs.iter().enumerate() {
            for input in &tx.input {
                if let Some(&parent_pos) = tx_positions.get(&input.previous_output.txid) {
                    // Parent transaction should come before this transaction
                    assert!(
                        parent_pos < pos,
                        "Dependency violation: transaction {} (pos {}) depends on {} (pos {})",
                        tx.txid(),
                        pos,
                        input.previous_output.txid,
                        parent_pos
                    );
                }
            }
        }
    }
}