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
mod compressor;
mod script;
mod serialize;
#[cfg(test)]
mod tests;

use self::compressor::ScriptCompression;
use self::serialize::write_compact_size;
use bitcoin::consensus::encode::Encodable;
use bitcoin::hashes::Hash;
use bitcoin::BlockHash;
use compressor::compress_amount;
use std::collections::{BTreeMap, HashSet};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use subcoin_primitives::runtime::Coin;
use txoutset::var_int::VarInt;

const SNAPSHOT_MAGIC_BYTES: [u8; 5] = [b'u', b't', b'x', b'o', 0xff];

/// Groups UTXOs by `txid` into a lexicographically ordered `BTreeMap` (same as the order stored by
/// Bitcoin Core in leveldb).
///
/// NOTE: this requires substantial RAM.
pub fn group_utxos_by_txid(
    utxos: impl IntoIterator<Item = Utxo>,
) -> BTreeMap<bitcoin::Txid, Vec<OutputEntry>> {
    let mut map: BTreeMap<bitcoin::Txid, Vec<OutputEntry>> = BTreeMap::new();

    for utxo in utxos {
        map.entry(utxo.txid).or_default().push(OutputEntry {
            vout: utxo.vout,
            coin: utxo.coin,
        });
    }

    map
}

// Equivalent function in Rust for serializing an OutPoint and Coin
//
// https://github.com/bitcoin/bitcoin/blob/6f9db1ebcab4064065ccd787161bf2b87e03cc1f/src/kernel/coinstats.cpp#L51
pub fn tx_out_ser(outpoint: bitcoin::OutPoint, coin: &Coin) -> bitcoin::io::Result<Vec<u8>> {
    let mut data = Vec::new();

    // Serialize the OutPoint (txid and vout)
    outpoint.consensus_encode(&mut data)?;

    // Serialize the coin's height and coinbase flag
    let height_and_coinbase = (coin.height << 1) | (coin.is_coinbase as u32);
    height_and_coinbase.consensus_encode(&mut data)?;

    let txout = bitcoin::TxOut {
        value: bitcoin::Amount::from_sat(coin.amount),
        script_pubkey: bitcoin::ScriptBuf::from_bytes(coin.script_pubkey.clone()),
    };

    // Serialize the actual UTXO (value and script)
    txout.consensus_encode(&mut data)?;

    Ok(data)
}

/// Represents a UTXO output in the snapshot format.
///
/// A combination of the output index (vout) and associated coin data.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct OutputEntry {
    /// The output index within the transaction.
    pub vout: u32,
    /// The coin data associated with this output.
    pub coin: Coin,
}

/// Represents a single UTXO (Unspent Transaction Output) in Bitcoin.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Utxo {
    /// The transaction ID that contains this UTXO.
    pub txid: bitcoin::Txid,
    /// The output index within the transaction.
    pub vout: u32,
    /// The coin data associated with this UTXO (e.g., amount and any relevant metadata).
    pub coin: Coin,
}

impl From<(bitcoin::Txid, u32, Coin)> for Utxo {
    fn from((txid, vout, coin): (bitcoin::Txid, u32, Coin)) -> Self {
        Self { txid, vout, coin }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SnapshotMetadata {
    version: u16,
    supported_versions: HashSet<u16>,
    network_magic: [u8; 4],
    base_blockhash: [u8; 32],
    coins_count: u64,
}

impl SnapshotMetadata {
    const VERSION: u16 = 2;

    pub fn new(network_magic: [u8; 4], base_blockhash: [u8; 32], coins_count: u64) -> Self {
        let supported_versions = HashSet::from([Self::VERSION]);
        Self {
            version: Self::VERSION,
            supported_versions,
            network_magic,
            base_blockhash,
            coins_count,
        }
    }

    pub fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
        writer.write_all(&SNAPSHOT_MAGIC_BYTES)?;
        writer.write_all(&self.version.to_le_bytes())?;
        writer.write_all(&self.network_magic)?;
        writer.write_all(&self.base_blockhash)?;
        writer.write_all(&self.coins_count.to_le_bytes())?;
        Ok(())
    }

    #[allow(unused)]
    pub fn deserialize<R: std::io::Read>(
        reader: &mut R,
        expected_network_magic: &[u8],
    ) -> std::io::Result<Self> {
        use std::io::{Error, ErrorKind};

        let mut magic_bytes = [0; SNAPSHOT_MAGIC_BYTES.len()];
        reader.read_exact(&mut magic_bytes)?;
        if magic_bytes != SNAPSHOT_MAGIC_BYTES {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("Invalid UTXO snapshot magic bytes (expected: {SNAPSHOT_MAGIC_BYTES:?}, got: {magic_bytes:?})"),
            ));
        }

        let mut version_bytes = [0; 2];
        reader.read_exact(&mut version_bytes)?;
        let version = u16::from_le_bytes(version_bytes);

        let supported_versions = HashSet::from([Self::VERSION]);
        if !supported_versions.contains(&version) {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("Unsupported snapshot version: {version}"),
            ));
        }

        let mut network_magic = [0u8; 4];
        reader.read_exact(&mut network_magic)?;
        if network_magic != expected_network_magic {
            return Err(Error::new(ErrorKind::InvalidData, "Network magic mismatch"));
        }

        let mut base_blockhash = [0; 32];
        reader.read_exact(&mut base_blockhash)?;

        let mut coins_count_bytes = [0; 8];
        reader.read_exact(&mut coins_count_bytes)?;
        let coins_count = u64::from_le_bytes(coins_count_bytes);

        Ok(Self {
            version,
            supported_versions,
            network_magic,
            base_blockhash,
            coins_count,
        })
    }
}

/// Responsible for dumping the UTXO set snapshot compatible with Bitcoin Core.
///
/// The format of generated snapshot is compatible with Bitcoin Core 28.0.
pub struct UtxoSnapshotGenerator {
    output_filepath: PathBuf,
    output_file: File,
    network: bitcoin::Network,
}

impl UtxoSnapshotGenerator {
    /// Constructs a new instance of [`UtxoSnapshotGenerator`].
    pub fn new(output_filepath: PathBuf, output_file: File, network: bitcoin::Network) -> Self {
        Self {
            output_filepath,
            output_file,
            network,
        }
    }

    /// Returns the path of generated snapshot file.
    pub fn path(&self) -> &Path {
        &self.output_filepath
    }

    /// Writes a single entry of UTXO.
    pub fn write_utxo_entry(
        &mut self,
        txid: bitcoin::Txid,
        vout: u32,
        coin: Coin,
    ) -> std::io::Result<()> {
        let Coin {
            is_coinbase,
            amount,
            height,
            script_pubkey,
        } = coin;

        let outpoint = bitcoin::OutPoint { txid, vout };

        let mut data = Vec::new();

        let amount = txoutset::Amount::new(amount);

        let code = txoutset::Code {
            height,
            is_coinbase,
        };
        let script = txoutset::Script::from_bytes(script_pubkey);

        outpoint.consensus_encode(&mut data)?;
        code.consensus_encode(&mut data)?;
        amount.consensus_encode(&mut data)?;
        script.consensus_encode(&mut data)?;

        let _ = self.output_file.write(data.as_slice())?;

        Ok(())
    }

    /// Writes the metadata of snapshot.
    pub fn write_metadata(
        &mut self,
        bitcoin_block_hash: BlockHash,
        coins_count: u64,
    ) -> std::io::Result<()> {
        write_snapshot_metadata(
            &mut self.output_file,
            self.network,
            bitcoin_block_hash,
            coins_count,
        )
    }

    /// Write the UTXO snapshot at the specified block to a file.
    ///
    /// NOTE: Do not use it in production.
    pub fn generate_snapshot_in_mem(
        &mut self,
        bitcoin_block_hash: BlockHash,
        utxos_count: u64,
        utxos: impl IntoIterator<Item = Utxo>,
    ) -> std::io::Result<()> {
        generate_snapshot_in_mem_inner(
            &mut self.output_file,
            self.network,
            bitcoin_block_hash,
            utxos_count,
            utxos,
        )
    }

    /// Writes UTXO entries for a given transaction.
    pub fn write_coins(
        &mut self,
        txid: bitcoin::Txid,
        coins: Vec<OutputEntry>,
    ) -> std::io::Result<()> {
        write_coins(&mut self.output_file, txid, coins)
    }
}

fn write_snapshot_metadata<W: std::io::Write>(
    writer: &mut W,
    network: bitcoin::Network,
    bitcoin_block_hash: BlockHash,
    coins_count: u64,
) -> std::io::Result<()> {
    let snapshot_metadata = SnapshotMetadata::new(
        network.magic().to_bytes(),
        bitcoin_block_hash.to_byte_array(),
        coins_count,
    );

    snapshot_metadata.serialize(writer)?;

    Ok(())
}

/// Write the UTXO snapshot at the specified block using the given writer.
///
/// NOTE: Do not use it in production.
fn generate_snapshot_in_mem_inner<W: std::io::Write>(
    writer: &mut W,
    network: bitcoin::Network,
    bitcoin_block_hash: BlockHash,
    utxos_count: u64,
    utxos: impl IntoIterator<Item = Utxo>,
) -> std::io::Result<()> {
    write_snapshot_metadata(writer, network, bitcoin_block_hash, utxos_count)?;

    for (txid, coins) in group_utxos_by_txid(utxos) {
        write_coins(writer, txid, coins)?;
    }

    Ok(())
}

pub fn write_coins<W: std::io::Write>(
    writer: &mut W,
    txid: bitcoin::Txid,
    mut coins: Vec<OutputEntry>,
) -> std::io::Result<()> {
    coins.sort_by_key(|output_entry| output_entry.vout);

    let mut data = Vec::new();
    txid.consensus_encode(&mut data)?;
    writer.write_all(&data)?;

    write_compact_size(writer, coins.len() as u64)?;

    for OutputEntry { vout, coin } in coins {
        write_compact_size(writer, vout as u64)?;
        serialize_coin(writer, coin)?;
    }

    Ok(())
}

fn serialize_coin<W: std::io::Write>(writer: &mut W, coin: Coin) -> std::io::Result<()> {
    let Coin {
        is_coinbase,
        amount,
        height,
        script_pubkey,
    } = coin;

    // https://github.com/bitcoin/bitcoin/blob/0903ce8dbc25d3823b03d52f6e6bff74d19e801e/src/coins.h#L62
    let code = (height << 1) | is_coinbase as u32;

    let mut data = Vec::new();
    VarInt::new(code as u64).consensus_encode(&mut data)?;
    VarInt::new(compress_amount(amount)).consensus_encode(&mut data)?;
    writer.write_all(&data)?;

    ScriptCompression(script_pubkey).serialize(writer)?;

    Ok(())
}