Skip to content

Commit f23ffb8

Browse files
committed
wip: Add minimal support for loading signet UTXO snapshots
Adds minimal wiring to connect QML GUI to loading a signet UTXO snapshot via the connection settings. Uses SnapshotSettings.qml to allow user interaction. Modifies src/interfaces/node.h, src/node/interfaces.cpp and chainparams.cpp (temporarily for signet snapshot testing) to expose snapshot loading functionality through the node model. Current limitations: - Not integrated with onboarding process - Requires manual navigation to connection settings after initial startup - Snapshot verification progress is not implemented yet Testing: 1. Start the node 2. Complete onboarding 3. Navigate to connection settings 4. Load snapshot from provided interface
1 parent c97d2a1 commit f23ffb8

File tree

11 files changed

+243
-60
lines changed

11 files changed

+243
-60
lines changed

Diff for: src/interfaces/node.h

+6
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,12 @@ class Node
199199
//! List rpc commands.
200200
virtual std::vector<std::string> listRpcCommands() = 0;
201201

202+
//! Load UTXO Snapshot.
203+
virtual bool snapshotLoad(const std::string& path_string) = 0;
204+
205+
//! Get snapshot progress.
206+
virtual double getSnapshotProgress() = 0;
207+
202208
//! Set RPC timer interface if unset.
203209
virtual void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) = 0;
204210

Diff for: src/kernel/chainparams.cpp

+7
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,13 @@ class SigNetParams : public CChainParams {
371371

372372
vFixedSeeds.clear();
373373

374+
m_assumeutxo_data = MapAssumeutxo{
375+
{
376+
160000,
377+
{AssumeutxoHash{uint256S("0x5225141cb62dee63ab3be95f9b03d60801f264010b1816d4bd00618b2736e7be")}, 1278002},
378+
},
379+
};
380+
374381
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111);
375382
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
376383
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);

Diff for: src/node/interfaces.cpp

+63-1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
#include <node/context.h>
3030
#include <node/interface_ui.h>
3131
#include <node/transaction.h>
32+
#include <node/utxo_snapshot.h>
3233
#include <policy/feerate.h>
3334
#include <policy/fees.h>
3435
#include <policy/policy.h>
@@ -395,9 +396,70 @@ class NodeImpl : public Node
395396
{
396397
m_context = context;
397398
}
399+
double getSnapshotProgress() override { return m_snapshot_progress.load(); }
400+
bool snapshotLoad(const std::string& path_string) override
401+
{
402+
const fs::path path = fs::u8path(path_string);
403+
if (!fs::exists(path)) {
404+
LogPrintf("[loadsnapshot] Snapshot file %s does not exist\n", path.u8string());
405+
return false;
406+
}
407+
408+
AutoFile afile{fsbridge::fopen(path, "rb")};
409+
if (afile.IsNull()) {
410+
LogPrintf("[loadsnapshot] Failed to open snapshot file %s\n", path.u8string());
411+
return false;
412+
}
413+
414+
SnapshotMetadata metadata;
415+
try {
416+
afile >> metadata;
417+
} catch (const std::exception& e) {
418+
LogPrintf("[loadsnapshot] Failed to read snapshot metadata: %s\n", e.what());
419+
return false;
420+
}
421+
422+
const uint256& base_blockhash = metadata.m_base_blockhash;
423+
LogPrintf("[loadsnapshot] Waiting for blockheader %s in headers chain before snapshot activation\n",
424+
base_blockhash.ToString());
425+
426+
if (!m_context->chainman) {
427+
LogPrintf("[loadsnapshot] Chainman is null\n");
428+
return false;
429+
}
430+
431+
ChainstateManager& chainman = *m_context->chainman;
432+
CBlockIndex* snapshot_start_block = nullptr;
433+
434+
// Wait for the block to appear in the block index
435+
constexpr int max_wait_seconds = 600; // 10 minutes
436+
for (int i = 0; i < max_wait_seconds; ++i) {
437+
snapshot_start_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(base_blockhash));
438+
if (snapshot_start_block) break;
439+
std::this_thread::sleep_for(std::chrono::seconds(1));
440+
}
441+
442+
if (!snapshot_start_block) {
443+
LogPrintf("[loadsnapshot] Timed out waiting for snapshot start blockheader %s\n", base_blockhash.ToString());
444+
return false;
445+
}
446+
447+
// Activate the snapshot
448+
if (!chainman.ActivateSnapshot(afile, metadata, false)) {
449+
LogPrintf("[loadsnapshot] Unable to load UTXO snapshot %s\n", path.u8string());
450+
return false;
451+
}
452+
453+
CBlockIndex* new_tip = WITH_LOCK(::cs_main, return chainman.ActiveTip());
454+
LogPrintf("[loadsnapshot] Loaded %d coins from snapshot %s at height %d\n",
455+
metadata.m_coins_count, new_tip->GetBlockHash().ToString(), new_tip->nHeight);
456+
457+
return true;
458+
}
398459
ArgsManager& args() { return *Assert(Assert(m_context)->args); }
399460
ChainstateManager& chainman() { return *Assert(m_context->chainman); }
400461
NodeContext* m_context{nullptr};
462+
std::atomic<double> m_snapshot_progress{0.0};
401463
};
402464

403465
bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman)
@@ -510,7 +572,7 @@ class RpcHandlerImpl : public Handler
510572
class ChainImpl : public Chain
511573
{
512574
public:
513-
explicit ChainImpl(NodeContext& node) : m_node(node) {}
575+
explicit ChainImpl(node::NodeContext& node) : m_node(node) {}
514576
std::optional<int> getHeight() override
515577
{
516578
const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};

Diff for: src/qml/components/ConnectionSettings.qml

+16-2
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,24 @@ import "../controls"
1010
ColumnLayout {
1111
id: root
1212
signal next
13-
property bool snapshotImported: false
13+
property bool snapshotImported: onboarding ? false : chainModel.isSnapshotActive
14+
property bool onboarding: false
15+
16+
Component.onCompleted: {
17+
if (!onboarding) {
18+
snapshotImported = chainModel.isSnapshotActive
19+
} else {
20+
snapshotImported = false
21+
}
22+
}
23+
1424
function setSnapshotImported(imported) {
1525
snapshotImported = imported
1626
}
1727
spacing: 4
1828
Setting {
1929
id: gotoSnapshot
30+
visible: !root.onboarding
2031
Layout.fillWidth: true
2132
header: qsTr("Load snapshot")
2233
description: qsTr("Instant use with background sync")
@@ -40,7 +51,10 @@ ColumnLayout {
4051
connectionSwipe.incrementCurrentIndex()
4152
}
4253
}
43-
Separator { Layout.fillWidth: true }
54+
Separator {
55+
visible: !root.onboarding
56+
Layout.fillWidth: true
57+
}
4458
Setting {
4559
Layout.fillWidth: true
4660
header: qsTr("Enable listening")

Diff for: src/qml/components/SnapshotSettings.qml

+55-42
Original file line numberDiff line numberDiff line change
@@ -5,44 +5,26 @@
55
import QtQuick 2.15
66
import QtQuick.Controls 2.15
77
import QtQuick.Layouts 1.15
8+
import QtQuick.Dialogs 1.3
89

910
import "../controls"
1011

1112
ColumnLayout {
13+
id: columnLayout
14+
property bool snapshotLoading: nodeModel.snapshotLoading
1215
signal snapshotImportCompleted()
13-
property int snapshotVerificationCycles: 0
14-
property real snapshotVerificationProgress: 0
15-
property bool snapshotVerified: false
16+
property bool onboarding: false
17+
property bool snapshotVerified: onboarding ? false : chainModel.isSnapshotActive
18+
property string snapshotFileName: ""
19+
property var snapshotInfo: ({})
20+
property string selectedFile: ""
1621

17-
id: columnLayout
1822
width: Math.min(parent.width, 450)
1923
anchors.horizontalCenter: parent.horizontalCenter
2024

21-
22-
Timer {
23-
id: snapshotSimulationTimer
24-
interval: 50 // Update every 50ms
25-
running: false
26-
repeat: true
27-
onTriggered: {
28-
if (snapshotVerificationProgress < 1) {
29-
snapshotVerificationProgress += 0.01
30-
} else {
31-
snapshotVerificationCycles++
32-
if (snapshotVerificationCycles < 1) {
33-
snapshotVerificationProgress = 0
34-
} else {
35-
running = false
36-
snapshotVerified = true
37-
settingsStack.currentIndex = 2
38-
}
39-
}
40-
}
41-
}
42-
4325
StackLayout {
4426
id: settingsStack
45-
currentIndex: 0
27+
currentIndex: onboarding ? 0 : snapshotVerified ? 2 : snapshotLoading ? 1 : 0
4628

4729
ColumnLayout {
4830
Layout.alignment: Qt.AlignHCenter
@@ -77,11 +59,24 @@ ColumnLayout {
7759
Layout.bottomMargin: 20
7860
Layout.alignment: Qt.AlignCenter
7961
text: qsTr("Choose snapshot file")
80-
onClicked: {
81-
settingsStack.currentIndex = 1
82-
snapshotSimulationTimer.start()
62+
onClicked: fileDialog.open()
63+
}
64+
65+
FileDialog {
66+
id: fileDialog
67+
folder: shortcuts.home
68+
selectMultiple: false
69+
selectExisting: true
70+
nameFilters: ["Snapshot files (*.dat)", "All files (*)"]
71+
onAccepted: {
72+
selectedFile = String(fileUrl)
73+
snapshotFileName = selectedFile
74+
if (selectedFile.indexOf(".dat") === selectedFile.length - 4) {
75+
nodeModel.initializeSnapshot(true, snapshotFileName)
76+
}
8377
}
8478
}
79+
// TODO: Handle file error signal
8580
}
8681

8782
ColumnLayout {
@@ -102,16 +97,22 @@ ColumnLayout {
10297
Layout.leftMargin: 20
10398
Layout.rightMargin: 20
10499
header: qsTr("Loading Snapshot")
100+
description: qsTr("This might take a while...")
105101
}
106102

107-
ProgressIndicator {
108-
id: progressIndicator
109-
Layout.topMargin: 20
110-
width: 200
111-
height: 20
112-
progress: snapshotVerificationProgress
113-
Layout.alignment: Qt.AlignCenter
114-
progressColor: Theme.color.blue
103+
// TODO: add progress indicator once the snapshot progress is implemented
104+
105+
Connections {
106+
target: nodeModel
107+
function onSnapshotLoaded(success) {
108+
if (success) {
109+
chainModel.isSnapshotActiveChanged()
110+
snapshotVerified = chainModel.isSnapshotActive
111+
snapshotInfo = chainModel.getSnapshotInfo()
112+
settingsStack.currentIndex = 2
113+
}
114+
}
115+
// TODO: connect to snapshotProgressChanged once implemented
115116
}
116117
}
117118

@@ -137,8 +138,11 @@ ColumnLayout {
137138
descriptionColor: Theme.color.neutral6
138139
descriptionSize: 17
139140
descriptionLineHeight: 1.1
140-
description: qsTr("It contains transactions up to January 12, 2024. Newer transactions still need to be downloaded." +
141-
" The data will be verified in the background.")
141+
description: snapshotInfo && snapshotInfo["date"] ?
142+
qsTr("It contains transactions up to %1. Newer transactions still need to be downloaded." +
143+
" The data will be verified in the background.").arg(snapshotInfo["date"]) :
144+
qsTr("It contains transactions up to DEBUG. Newer transactions still need to be downloaded." +
145+
" The data will be verified in the background.")
142146
}
143147

144148
ContinueButton {
@@ -188,16 +192,25 @@ ColumnLayout {
188192
font.pixelSize: 14
189193
}
190194
CoreText {
191-
text: qsTr("200,000")
195+
text: snapshotInfo && snapshotInfo["height"] ?
196+
snapshotInfo["height"] : qsTr("DEBUG")
192197
Layout.alignment: Qt.AlignRight
193198
font.pixelSize: 14
194199
}
195200
}
196201
Separator { Layout.fillWidth: true }
197202
CoreText {
198-
text: qsTr("Hash: 0x1234567890abcdef...")
203+
text: snapshotInfo && snapshotInfo["hashSerialized"] ?
204+
qsTr("Hash: %1").arg(snapshotInfo["hashSerialized"].substring(0, 13) + "...") :
205+
qsTr("Hash: DEBUG")
199206
font.pixelSize: 14
200207
}
208+
209+
Component.onCompleted: {
210+
if (snapshotVerified) {
211+
snapshotInfo = chainModel.getSnapshotInfo()
212+
}
213+
}
201214
}
202215
}
203216
}

Diff for: src/qml/models/chainmodel.cpp

+22
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,13 @@
99
#include <QThread>
1010
#include <QTime>
1111
#include <interfaces/chain.h>
12+
#include <node/utxo_snapshot.h>
13+
#include <kernel/chainparams.h>
14+
#include <validation.h>
1215

1316
ChainModel::ChainModel(interfaces::Chain& chain)
1417
: m_chain{chain}
18+
// m_params{Params()}
1519
{
1620
QTimer* timer = new QTimer();
1721
connect(timer, &QTimer::timeout, this, &ChainModel::setCurrentTimeRatio);
@@ -101,3 +105,21 @@ void ChainModel::setCurrentTimeRatio()
101105

102106
Q_EMIT timeRatioListChanged();
103107
}
108+
109+
// Using hardcoded snapshot info to display in SnapshotSettings.qml
110+
QVariantMap ChainModel::getSnapshotInfo() {
111+
QVariantMap snapshot_info;
112+
113+
const MapAssumeutxo& valid_assumeutxos_map = Params().Assumeutxo();
114+
if (!valid_assumeutxos_map.empty()) {
115+
const int height = valid_assumeutxos_map.rbegin()->first;
116+
const auto& hash_serialized = valid_assumeutxos_map.rbegin()->second.hash_serialized;
117+
int64_t date = m_chain.getBlockTime(height);
118+
119+
snapshot_info["height"] = height;
120+
snapshot_info["hashSerialized"] = QString::fromStdString(hash_serialized.ToString());
121+
snapshot_info["date"] = QDateTime::fromSecsSinceEpoch(date).toString("MMMM d yyyy");
122+
}
123+
124+
return snapshot_info;
125+
}

Diff for: src/qml/models/chainmodel.h

+5-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class ChainModel : public QObject
2727
Q_PROPERTY(quint64 assumedBlockchainSize READ assumedBlockchainSize CONSTANT)
2828
Q_PROPERTY(quint64 assumedChainstateSize READ assumedChainstateSize CONSTANT)
2929
Q_PROPERTY(QVariantList timeRatioList READ timeRatioList NOTIFY timeRatioListChanged)
30+
Q_PROPERTY(bool isSnapshotActive READ isSnapshotActive NOTIFY isSnapshotActiveChanged)
3031

3132
public:
3233
explicit ChainModel(interfaces::Chain& chain);
@@ -36,18 +37,21 @@ class ChainModel : public QObject
3637
quint64 assumedBlockchainSize() const { return m_assumed_blockchain_size; };
3738
quint64 assumedChainstateSize() const { return m_assumed_chainstate_size; };
3839
QVariantList timeRatioList() const { return m_time_ratio_list; };
39-
40+
bool isSnapshotActive() const { return m_chain.hasAssumedValidChain(); };
4041
int timestampAtMeridian();
4142

4243
void setCurrentTimeRatio();
4344

45+
Q_INVOKABLE QVariantMap getSnapshotInfo();
46+
4447
public Q_SLOTS:
4548
void setTimeRatioList(int new_time);
4649
void setTimeRatioListInitial();
4750

4851
Q_SIGNALS:
4952
void timeRatioListChanged();
5053
void currentNetworkNameChanged();
54+
void isSnapshotActiveChanged();
5155

5256
private:
5357
QString m_current_network_name;

0 commit comments

Comments
 (0)