Skip to content

Conversation

@theStack
Copy link
Contributor

@theStack theStack commented Apr 6, 2023

Problem description

There is demand from users to get the UTXO set in form of a SQLite database (#24628). Bitcoin Core currently only supports dumping the UTXO set in a binary compact-serialized format, which was crafted specifically for AssumeUTXO snapshots (see PR #16899), with the primary goal of being as compact as possible. Previous PRs tried to extend the dumptxoutset RPC with new formats, either in human-readable form (e.g. #18689, #24202), or most recently, directly as SQLite database (#24952). Both are not optimal: due to the huge size of the ever-growing UTXO set with already more than 80 million entries on mainnet, human-readable formats are practically useless, and very likely one of the first steps would be to put them in some form of database anyway. Directly adding SQLite3 dumping support on the other hand introduces an additional dependency to the non-wallet part of bitcoind and the risk of increased maintenance burden (see e.g. #24952 (comment), #24628 (comment)).

Proposed solution

This PR follows the "external tooling" route by adding a simple Python script for achieving the same goal in a two-step process (first create compact-serialized UTXO set via dumptxoutset, then convert it to SQLite via the new script). Executive summary:

  • single file, no extra dependencies (sqlite3 is included in Python's standard library [1])
  • ~150 LOC, mostly deserialization/decompression routines ported from the Core codebase and (probably the most difficult part) a little elliptic curve / finite field math to decompress pubkeys (essentialy solving the secp256k1 curve equation y^2 = x^3 + 7 for y given x, respecting the proper polarity as indicated by the compression tag)
  • creates a database with only one table utxos with the following schema:
    (txid TEXT, vout INT, value INT, coinbase INT, height INT, scriptpubkey TEXT)
  • the resulting file has roughly 2x the size of the compact-serialized UTXO set (this is mostly due to encoding txids and scriptpubkeys as hex-strings rather than bytes)

[1] note that there are some rare cases of operating systems like FreeBSD though, where the sqlite3 module has to installed explicitly (see #26819)

A functional test is also added that creates UTXO set entries with various output script types (standard and also non-standard, for e.g. large scripts) and verifies that the UTXO sets of both formats match by comparing corresponding MuHashes. One MuHash is supplied by the bitcoind instance via gettxoutsetinfo muhash, the other is calculated in the test by reading back the created SQLite database entries and hashing them with the test framework's MuHash3072 module.

Manual test instructions

I'd suggest to do manual tests also by comparing MuHashes. For that, I've written a go tool some time ago which would calculate the MuHash of a sqlite database in the created format (I've tried to do a similar tool in Python, but it's painfully slow).

$ [run bitcoind instance with -coinstatsindex]
$ ./src/bitcoin-cli dumptxoutset ~/utxos.dat
$ ./src/bitcoin-cli gettxoutsetinfo muhash <block height returned in previous call>
(outputs MuHash calculated from node)

$ ./contrib/utxo-tools/utxo_to_sqlite.py ~/utxos.dat ~/utxos.sqlite
$ git clone https://github.com/theStack/utxo_dump_tools
$ cd utxo_dump_tools/calc_utxo_hash
$ go run calc_utxo_hash.go ~/utxos.sqlite
(outputs MuHash calculated from the SQLite UTXO set)

=> verify that both MuHashes are equal

For a demonstration what can be done with the resulting database, see #24952 (review) for some example queries. Thanks go to LarryRuane who gave me to the idea of rewriting this script in Python and adding it to contrib.

@DrahtBot
Copy link
Contributor

DrahtBot commented Apr 6, 2023

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/27432.

Reviews

See the guideline for information on the review process.

Type Reviewers
ACK romanz, tdb3, ajtowns, achow101
Concept ACK jamesob, dunxen, pablomartin4btc, Sjors, sipa
Stale ACK willcl-ark

If your review is incorrectly listed, please react with 👎 to this comment and the bot will ignore it on the next update.

Conflicts

No conflicts as of last run.

@pinheadmz
Copy link
Member

This also closes #21670 ;-)

@theStack
Copy link
Contributor Author

theStack commented Apr 6, 2023

Pinging users who worked on or reviewed / expressed interest in the previous attempt to solve this issue (PR #24952):
@dunxen @0xB10C @jamesob @prusnak @willcl-ark @w0xlt @jonatack @brunoerg @laanwj @fanquake

@theStack theStack force-pushed the add-utxo_to_sqlite-conversion-tool branch 2 times, most recently from 494be8c to 3ce180a Compare April 6, 2023 20:05
@bitcoin bitcoin deleted a comment from edgarpaula Apr 12, 2023
@achow101
Copy link
Member

the resulting file has roughly 2x the size of the compact-serialized UTXO set (this is mostly due to encoding txids and scriptpubkeys as hex-strings rather than bytes)

What is the rationale for encoding as text rather than bytes? SQLite can store byte values as BLOBs.

@theStack
Copy link
Contributor Author

the resulting file has roughly 2x the size of the compact-serialized UTXO set (this is mostly due to encoding txids and scriptpubkeys as hex-strings rather than bytes)

What is the rationale for encoding as text rather than bytes? SQLite can store byte values as BLOBs.

Fair question. There was already some discussion in #24952 about whether to store txids/scriptPubKeys as TEXT or BLOB, see #24952 (review), #24952 (comment) and #24952 (comment). The two main points were:

  • conversion from this database to json/csv etc should be as simple as possible, and ideally "select * from utxos" should already lead to human-readable output. Converting would then be as trivial as a short one-liner sqlite3 -json utxo.db "SELECT * FROM utxos" > utxo.json, without even having to specify the columns
  • more annoying: if using BLOB for the txid, we would have to decide if we store the txid in little or big endian byte order. Big endian would be more natural, as that's how we internally store the txid and also serialize it on the wire, but we show everything in little endian byte order in Bitcoin Core, so a simple "select hex(txid) from utxos" would just show the txid in the wrong order, and something like "reverse(...)" doesn't exist in SQLite (though some hacky workarounds have been proposed: rpc: Add sqlite format option for dumptxoutset #24952 (comment) and rpc: Add sqlite format option for dumptxoutset #24952 (comment)). There remains the possibility to just store the txid in little endian order, but that's the opposite of what we do in leveldb or in the serialization of outpoints, so it could lead to huge confusion for users if not clearly documented. For TEXT the order is clear, it's just stored what is shown everywhere in Bitcoin Core and all wallets, block explorers etc.

Considering the scriptPubKey column individually, there is no good reason to use TEXT rather than BLOB, but I went for TEXT mostly for consistency reasons, to not mix TEXT and BLOB in different columns when it's both binary data.

That said, I'm also very open also for using BLOB instead, it's just a matter of trade-offs.

@ajtowns
Copy link
Contributor

ajtowns commented Jul 27, 2023

Approach ACK. Seems like a fine idea to me.

What is the rationale for encoding as text rather than bytes? SQLite can store byte values as BLOBs.

It's a python conversion script: can't you just add a command-line option for the resulting db to have hex txids or big/little endian blobs if there's user demand for it? Hex encoding seems a fine default to me, for what it's worth.

If people end up wanting lots of different options (convert scriptPubKeys to addresses? some way to update the db to a new state, rather than just create a new one?) maybe it would make sense for this script to have its own repo even; but while it stays simple/small, seems fine for contrib.

@jamesob
Copy link
Contributor

jamesob commented Jul 27, 2023

Concept ACK, will test soon

@dunxen
Copy link
Contributor

dunxen commented Jul 27, 2023

Concept ACK

Copy link
Member

@willcl-ark willcl-ark left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tACK 3ce180a

Left two nits which don't need addressing unless being re-touched, but overall this works well in testing and seems like a useful contrib script. Converting the output to json also worked as described in the comments above.

@achow101 achow101 requested a review from josibake September 20, 2023 17:21
Copy link
Member

@pablomartin4btc pablomartin4btc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

@DrahtBot DrahtBot requested review from ajtowns and jamesob October 13, 2023 02:42
This was referenced Dec 2, 2023
@theStack theStack force-pushed the add-utxo_to_sqlite-conversion-tool branch 2 times, most recently from 73b9cab to a1c1cf3 Compare January 6, 2024 21:36
@DrahtBot DrahtBot removed the CI failed label Jan 6, 2024
@theStack
Copy link
Contributor Author

theStack commented Jan 6, 2024

Could mark as draft while CI is red?

Sorry for the extra-late reply, missed this message and the CI fail. Rebased on master and resolved the silent merge conflict (caused by the module move test_framework.muhash -> test_framework.crypto.muhash in #28374). Also fixed the Windows CI issue by closing the sqlite connections properly with explicit con.close() calls (see e.g. #28204). CI is green now.

What is the rationale for encoding as text rather than bytes? SQLite can store byte values as BLOBs.

It's a python conversion script: can't you just add a command-line option for the resulting db to have hex txids or big/little endian blobs if there's user demand for it? Hex encoding seems a fine default to me, for what it's worth.

Good idea, planning to tackle this as a follow-up.

@theStack theStack force-pushed the add-utxo_to_sqlite-conversion-tool branch from a1c1cf3 to 9668255 Compare January 22, 2024 12:37
@achow101 achow101 merged commit 43e71f7 into bitcoin:master Feb 14, 2025
18 checks passed
@theStack theStack deleted the add-utxo_to_sqlite-conversion-tool branch February 15, 2025 09:01
@fjahr
Copy link
Contributor

fjahr commented Feb 15, 2025

post-merge tACK 4080b66

@romanz
Copy link
Contributor

romanz commented Feb 15, 2025

FTR, it's possible to import the data from SQLite into DuckDB, to use its optimized query execution engine (for faster queries):

ATTACH 'utxo.sqlite' AS utxo_sqlite (TYPE SQLITE, READONLY);
ATTACH 'utxo.duckdb' AS utxo_duckdb;
COPY FROM DATABASE utxo_sqlite TO utxo_duckdb;
USE utxo_duckdb;
$ du -h utxo.*
24G	utxo.sqlite
13G	utxo.duckdb
In [1]: import duckdb

In [2]: c = duckdb.connect()

In [3]: c.sql("ATTACH 'utxo.duckdb' AS utxo_duckdb")

In [4]: c.sql("USE utxo_duckdb")

In [5]: %time c.sql("SELECT count(*) FROM utxos").show()
┌──────────────┐
│ count_star() │
│    int64     │
├──────────────┤
│    177884546 │
└──────────────┘

CPU times: user 2.16 ms, sys: 5.78 ms, total: 7.95 ms
Wall time: 7.1 ms

In [6]: %time c.sql("SELECT count(*) FROM utxos WHERE value < 1000").show()
┌──────────────┐
│ count_star() │
│    int64     │
├──────────────┤
│     85656982 │
└──────────────┘

CPU times: user 926 ms, sys: 765 ms, total: 1.69 s
Wall time: 161 ms

In [7]: %time c.sql("SELECT count(*), CAST(height/50000 AS INTEGER) as i FROM utxos WHERE value < 1000 GROUP BY i ORDER BY i").show()
┌──────────────┬───────┐
│ count_star() │   i   │
│    int64int32 │
├──────────────┼───────┤
│          5012 │
│       3641353 │
│       3713584 │
│       8831515 │
│       1050336 │
│       2645427 │
│        771638 │
│       2562629 │
│       54159010 │
│      157888211 │
│      375632812 │
│      144184713 │
│       71256514 │
│       51056315 │
│     3404410716 │
│     3475514917 │
│      599380618 │
├──────────────┴───────┤
│ 17 rows    2 columns │
└──────────────────────┘

CPU times: user 3.08 s, sys: 676 ms, total: 3.75 s
Wall time: 320 ms

@laanwj
Copy link
Member

laanwj commented Feb 15, 2025

Great to see that this was merged!

theStack added a commit to theStack/bitcoin that referenced this pull request Feb 16, 2025
fanquake added a commit that referenced this pull request Feb 16, 2025
95722d0 doc: add release note for #27432 (utxo-to-sqlite tool) (Sebastian Falbesoner)

Pull request description:

  This PR adds a missing release note for #27432.

ACKs for top commit:
  kevkevinpal:
    ACK [95722d0](95722d0)

Tree-SHA512: 47714182e814fb825dbaeede46a1b496c4b87f3c5bfa61ada00138926a6bf9eb9a3f99636eb698a7bcda6642f73d0a8c5bf531a726750d594decca8ba6a56e3a
0xB10C pushed a commit to 0xB10C/bitcoin that referenced this pull request Feb 17, 2025
sedited added a commit to sedited/rust-bitcoinkernel that referenced this pull request Feb 22, 2025
…513955891

29513955891 kernel: Add pure kernel bitcoin-chainstate
9c40433bd4a kernel: Add functions to get the block hash from a block
942df8f287f kernel: Add block index utility functions to C header
87102db87ac kernel: Add function to read block undo data from disk to C header
12b8c9442ad kernel: Add functions to read block from disk to C header
d977db3feb2 kernel: Add function for copying  block data to C header
8ae33627743 kernel: Add functions for the block validation state to C header
0565a0bbc01 kernel: Add validation interface to C header
837e5a0f536 kernel: Add interrupt function to C header
a80b7bfe3de kernel: Add import blocks function to C header
54d1a1231ec kernel: Add chainstate load options for in-memory dbs in C header
659efa9969c kernel: Add options for reindexing in C header
2179127c079 kernel: Add block validation to C header
26143992693 kernel: Add chainstate loading when instantiating a ChainstateManager
82d2bebbe54 kernel: Add chainstate manager option for setting worker threads
e875f520851 kernel: Add chainstate manager object to C header
4e486059178 kernel: Add notifications context option to C header
a5eb699b978 kernel: Add chain params context option to C header
0818b8d2c07 kernel: Add kernel library context object
71c24c95b31 kernel: Add logging to kernel library C header
0cc810386f7 kernel: Introduce initial kernel C header API
82ba9257157 Merge bitcoin/bitcoin#31366: cmake: Check `-Wno-*` compiler options for `leveldb` target
f236854a5bd Merge bitcoin/bitcoin#31731: doc: update translation generation cmake example
eb51963d870 Merge bitcoin/bitcoin#31884: cmake: Make implicit `libbitcoinkernel` dependencies explicit
58f15d4b215 Merge bitcoin/bitcoin#31379: cmake: Fix passing `APPEND_*FLAGS` to `secp256k1` subtree
e606c577cb2 Merge bitcoin/bitcoin#31899: cmake: Exclude generated sources from translation
758a93d6215 doc: update translation generation cmake example
fd14995b6a8 Merge bitcoin/bitcoin#31908: Revert merge of PR #31826
3e9b12b3e0f Revert "Merge bitcoin/bitcoin#31826: random: Check `GetRNDRRS` is supported in `InitHardwareRand` to avoid infinite loop"
785649f3977 Merge bitcoin/bitcoin#29881: guix: use GCC 13 to build releases
139640079ff Merge bitcoin/bitcoin#31826: random: Check `GetRNDRRS` is supported in `InitHardwareRand` to avoid infinite loop
dc3a7146337 Merge bitcoin/bitcoin#31794: wallet: abandon orphan coinbase txs, and their descendants, during startup
06757af2da5 Merge bitcoin/bitcoin#29156: tests: add functional test for miniscript decaying multisig
ff4ddd3d2e3 Revert "cmake: Ensure generated sources are up to date for `translate` target"
03b3166aac5 cmake: Exclude generated sources from translation
43e287b3ff5 Merge bitcoin/bitcoin#31892: build: remove ENABLE_HARDENING condition from check-security
63d625f7610 Merge bitcoin/bitcoin#31893: test: remove scanning check on `wallet_importdescriptors`
3b42e05aa9e cmake: Make implicit `libbitcoinkernel` dependencies explicit
3fd64efb437 cmake: Avoid using `OBJECT` libraries
28dec6c5f8b Merge bitcoin/bitcoin#31268: cmake: add optional source files to bitcoin_crypto and crc32c directly
50afaf3a389 Merge bitcoin/bitcoin#31836: contrib: Add deterministic-fuzz-coverage
405dd0e647e test: remove scanning check on `wallet_importdescriptors`
113a7a363fa build: remove ENABLE_HARDENING cond from check-security
9da0820ec55 Merge bitcoin/bitcoin#31869: cmake: Add `libbitcoinkernel` target
db36a92c02b Merge bitcoin/bitcoin#31879: doc: add release note for #27432 (utxo-to-sqlite tool)
95722d048a8 doc: add release note for #27432 (utxo-to-sqlite tool)
e4dd5a351bd test: wallet, abandon coinbase txs and their descendants during startup
09b150bb8a