Skip to content

Commit c59e557

Browse files
committed
wip: Add initial support for loading signet UTXO snapshots
Adds wiring to connect QML GUI to loading a signet UTXO snapshot via the connection settings. Modifies src/interfaces/node.h, src/node/interfaces.cpp and src/validation.h and src/validation.cpp to implement snapshot loading functionality. Current limitations: - Not integrated with onboarding process - Requires manual navigation to connection settings after initial startup Testing: 1. Start the node 2. Complete onboarding 3. Navigate to connection settings 4. Load snapshot from provided interface Note: This is a work in progress. Do not merge until fully implemented and tested.
1 parent 1d08d2c commit c59e557

15 files changed

+272
-36
lines changed

src/interfaces/node.h

+3
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,9 @@ 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, std::function<void(double)> progress_callback) = 0;
204+
202205
//! Set RPC timer interface if unset.
203206
virtual void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) = 0;
204207

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);

src/node/interfaces.cpp

+61-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,6 +396,65 @@ class NodeImpl : public Node
395396
{
396397
m_context = context;
397398
}
399+
bool snapshotLoad(const std::string& path_string, std::function<void(double)> progress_callback) override
400+
{
401+
const fs::path path = fs::u8path(path_string);
402+
if (!fs::exists(path)) {
403+
LogPrintf("[loadsnapshot] Snapshot file %s does not exist\n", path.u8string());
404+
return false;
405+
}
406+
407+
AutoFile afile{fsbridge::fopen(path, "rb")};
408+
if (afile.IsNull()) {
409+
LogPrintf("[loadsnapshot] Failed to open snapshot file %s\n", path.u8string());
410+
return false;
411+
}
412+
413+
SnapshotMetadata metadata;
414+
try {
415+
afile >> metadata;
416+
} catch (const std::exception& e) {
417+
LogPrintf("[loadsnapshot] Failed to read snapshot metadata: %s\n", e.what());
418+
return false;
419+
}
420+
421+
const uint256& base_blockhash = metadata.m_base_blockhash;
422+
LogPrintf("[loadsnapshot] Waiting for blockheader %s in headers chain before snapshot activation\n",
423+
base_blockhash.ToString());
424+
425+
if (!m_context->chainman) {
426+
LogPrintf("[loadsnapshot] Chainman is null\n");
427+
return false;
428+
}
429+
430+
ChainstateManager& chainman = *m_context->chainman;
431+
CBlockIndex* snapshot_start_block = nullptr;
432+
433+
// Wait for the block to appear in the block index
434+
constexpr int max_wait_seconds = 600; // 10 minutes
435+
for (int i = 0; i < max_wait_seconds; ++i) {
436+
snapshot_start_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(base_blockhash));
437+
if (snapshot_start_block) break;
438+
std::this_thread::sleep_for(std::chrono::seconds(1));
439+
}
440+
441+
if (!snapshot_start_block) {
442+
LogPrintf("[loadsnapshot] Timed out waiting for snapshot start blockheader %s\n", base_blockhash.ToString());
443+
return false;
444+
}
445+
446+
// Activate the snapshot
447+
if (!chainman.ActivateSnapshot(afile, metadata, false, progress_callback)) {
448+
LogPrintf("[loadsnapshot] Unable to load UTXO snapshot %s\n", path.u8string());
449+
return false;
450+
}
451+
452+
CBlockIndex* new_tip = WITH_LOCK(::cs_main, return chainman.ActiveTip());
453+
LogPrintf("[loadsnapshot] Loaded %d coins from snapshot %s at height %d\n",
454+
metadata.m_coins_count, new_tip->GetBlockHash().ToString(), new_tip->nHeight);
455+
456+
return true;
457+
}
398458
ArgsManager& args() { return *Assert(Assert(m_context)->args); }
399459
ChainstateManager& chainman() { return *Assert(m_context->chainman); }
400460
NodeContext* m_context{nullptr};
@@ -808,4 +868,4 @@ class ChainImpl : public Chain
808868
namespace interfaces {
809869
std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
810870
std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
811-
} // namespace interfaces
871+
} // namespace interfaces

src/qml/bitcoin.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,8 @@ int QmlGuiMain(int argc, char* argv[])
311311
engine.rootContext()->setContextProperty("optionsModel", &options_model);
312312
engine.rootContext()->setContextProperty("needOnboarding", need_onboarding);
313313

314+
QObject::connect(&node_model, &NodeModel::snapshotLoaded, &options_model, &OptionsQmlModel::setSnapshotLoadCompleted);
315+
314316
AppMode app_mode = SetupAppMode();
315317

316318
qmlRegisterSingletonInstance<AppMode>("org.bitcoincore.qt", 1, 0, "AppMode", &app_mode);

src/qml/components/ConnectionSettings.qml

+44-21
Original file line numberDiff line numberDiff line change
@@ -8,36 +8,59 @@ import QtQuick.Layouts 1.15
88
import "../controls"
99

1010
ColumnLayout {
11-
property bool snapshotImported: false
11+
// TODO: Remove this once storing the snapshot path is implemented
12+
property bool isOnboarding: false
13+
property bool snapshotImported: optionsModel.snapshotLoadCompleted
14+
15+
Component.onCompleted: {
16+
snapshotImported = optionsModel.snapshotLoadCompleted
17+
}
18+
1219
function setSnapshotImported(imported) {
1320
snapshotImported = imported
21+
optionsModel.setSnapshotLoadCompleted(imported)
1422
}
1523
spacing: 4
16-
Setting {
17-
id: gotoSnapshot
24+
Item {
25+
// TODO: Remove this once storing the snapshot path is implemented
26+
visible: !isOnboarding
27+
height: visible ? implicitHeight : 0
1828
Layout.fillWidth: true
19-
header: qsTr("Load snapshot")
20-
description: qsTr("Instant use with background sync")
21-
actionItem: Item {
22-
width: 26
23-
height: 26
24-
CaretRightIcon {
25-
anchors.centerIn: parent
26-
visible: !snapshotImported
27-
color: gotoSnapshot.stateColor
29+
Layout.preferredHeight: gotoSnapshot.height
30+
31+
Setting {
32+
id: gotoSnapshot
33+
visible: parent.visible
34+
Layout.fillWidth: true
35+
header: qsTr("Load snapshot")
36+
description: qsTr("Instant use with background sync")
37+
actionItem: Item {
38+
width: 26
39+
height: 26
40+
CaretRightIcon {
41+
// TODO: aligment will be fixed once Onboarding snapshot works
42+
anchors.right: parent.right
43+
anchors.verticalCenter: parent.verticalCenter
44+
visible: !snapshotImported
45+
color: gotoSnapshot.stateColor
46+
}
47+
GreenCheckIcon {
48+
anchors.centerIn: parent
49+
visible: snapshotImported
50+
color: Theme.color.transparent
51+
}
2852
}
29-
GreenCheckIcon {
30-
anchors.centerIn: parent
31-
visible: snapshotImported
32-
color: Theme.color.transparent
53+
onClicked: {
54+
connectionSwipe.incrementCurrentIndex()
55+
connectionSwipe.incrementCurrentIndex()
3356
}
3457
}
35-
onClicked: {
36-
connectionSwipe.incrementCurrentIndex()
37-
connectionSwipe.incrementCurrentIndex()
38-
}
3958
}
40-
Separator { Layout.fillWidth: true }
59+
Separator {
60+
Layout.fillWidth: true
61+
// TODO: Remove this once storing the snapshot path is implemented
62+
visible: !isOnboarding
63+
}
4164
Setting {
4265
Layout.fillWidth: true
4366
header: qsTr("Enable listening")

src/qml/components/SnapshotSettings.qml

+43-6
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,22 @@
55
import QtQuick 2.15
66
import QtQuick.Controls 2.15
77
import QtQuick.Layouts 1.15
8+
import QtQuick.Dialogs 1.3
9+
810

911
import "../controls"
1012

1113
ColumnLayout {
1214
signal snapshotImportCompleted()
1315
property int snapshotVerificationCycles: 0
1416
property real snapshotVerificationProgress: 0
15-
property bool snapshotVerified: false
17+
property bool snapshotVerified: optionsModel.snapshotLoadCompleted
1618

1719
id: columnLayout
1820
width: Math.min(parent.width, 450)
1921
anchors.horizontalCenter: parent.horizontalCenter
2022

21-
23+
// TODO: Remove simulation timer before release
2224
Timer {
2325
id: snapshotSimulationTimer
2426
interval: 50 // Update every 50ms
@@ -42,7 +44,7 @@ ColumnLayout {
4244

4345
StackLayout {
4446
id: settingsStack
45-
currentIndex: 0
47+
currentIndex: optionsModel.snapshotLoadCompleted ? 2 : 0
4648

4749
ColumnLayout {
4850
Layout.alignment: Qt.AlignHCenter
@@ -78,8 +80,26 @@ ColumnLayout {
7880
Layout.alignment: Qt.AlignCenter
7981
text: qsTr("Choose snapshot file")
8082
onClicked: {
81-
settingsStack.currentIndex = 1
82-
snapshotSimulationTimer.start()
83+
// TODO: Connect this to snapshot loading
84+
// settingsStack.currentIndex = 1
85+
fileDialog.open()
86+
}
87+
}
88+
89+
FileDialog {
90+
id: fileDialog
91+
folder: shortcuts.home
92+
selectMultiple: false
93+
onAccepted: {
94+
console.log("File chosen:", fileDialog.fileUrls)
95+
var snapshotFileName = fileDialog.fileUrl.toString()
96+
console.log("Snapshot file name:", snapshotFileName)
97+
if (snapshotFileName.endsWith(".dat")) {
98+
// optionsModel.setSnapshotDirectory(snapshotFileName)
99+
// console.log("Snapshot directory set:", optionsModel.getSnapshotDirectory())
100+
nodeModel.initializeSnapshot(true, snapshotFileName)
101+
settingsStack.currentIndex = 1
102+
}
83103
}
84104
}
85105
}
@@ -109,10 +129,27 @@ ColumnLayout {
109129
Layout.topMargin: 20
110130
width: 200
111131
height: 20
112-
progress: snapshotVerificationProgress
132+
progress: nodeModel.snapshotProgress
113133
Layout.alignment: Qt.AlignCenter
114134
progressColor: Theme.color.blue
115135
}
136+
137+
Connections {
138+
target: nodeModel
139+
function onSnapshotProgressChanged() {
140+
progressIndicator.progress = nodeModel.snapshotProgress
141+
}
142+
function onSnapshotLoaded(success) {
143+
if (success) {
144+
progressIndicator.progress = 1
145+
settingsStack.currentIndex = 2 // Move to the "Snapshot Loaded" page
146+
} else {
147+
// Handle snapshot loading failure
148+
console.error("Snapshot loading failed")
149+
// You might want to show an error message or take other actions here
150+
}
151+
}
152+
}
116153
}
117154

118155
ColumnLayout {

src/qml/models/nodemodel.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
#include <QMetaObject>
1717
#include <QTimerEvent>
1818
#include <QString>
19+
#include <QThread>
20+
#include <QUrl>
21+
#include <QDebug>
1922

2023
NodeModel::NodeModel(interfaces::Node& node)
2124
: m_node{node}
@@ -121,6 +124,8 @@ void NodeModel::initializeResult(bool success, interfaces::BlockAndHeaderTipInfo
121124
setVerificationProgress(tip_info.verification_progress);
122125

123126
Q_EMIT setTimeRatioListInitial();
127+
// TODO: fix this so that it works once storing the snapshot path is implemented
128+
Q_EMIT initializationFinished();
124129
}
125130

126131
void NodeModel::startShutdownPolling()
@@ -166,3 +171,35 @@ void NodeModel::ConnectToNumConnectionsChangedSignal()
166171
setNumOutboundPeers(new_num_peers.outbound_full_relay + new_num_peers.block_relay);
167172
});
168173
}
174+
175+
// Loads a snapshot from a given path using FileDialog
176+
void NodeModel::initializeSnapshot(bool initLoadSnapshot, QString path_file) {
177+
if (initLoadSnapshot) {
178+
// TODO: this is to deal with FileDialog returning a QUrl
179+
path_file = QUrl(path_file).toLocalFile();
180+
// TODO: Remove this before release
181+
// qDebug() << "path_file: " << path_file;
182+
QThread* snapshot_thread = new QThread();
183+
184+
// Capture path_file by value
185+
auto lambda = [this, path_file]() {
186+
bool result = this->snapshotLoad(path_file, [this](double progress) {
187+
setSnapshotProgress(progress);
188+
});
189+
Q_EMIT snapshotLoaded(result);
190+
};
191+
192+
connect(snapshot_thread, &QThread::started, lambda);
193+
connect(snapshot_thread, &QThread::finished, snapshot_thread, &QThread::deleteLater);
194+
195+
snapshot_thread->start();
196+
}
197+
}
198+
199+
void NodeModel::setSnapshotProgress(double new_snapshot_progress)
200+
{
201+
if (new_snapshot_progress != m_snapshot_progress) {
202+
m_snapshot_progress = new_snapshot_progress;
203+
Q_EMIT snapshotProgressChanged();
204+
}
205+
}

src/qml/models/nodemodel.h

+11-1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ class NodeModel : public QObject
3434
Q_PROPERTY(double verificationProgress READ verificationProgress NOTIFY verificationProgressChanged)
3535
Q_PROPERTY(bool pause READ pause WRITE setPause NOTIFY pauseChanged)
3636
Q_PROPERTY(bool faulted READ errorState WRITE setErrorState NOTIFY errorStateChanged)
37+
Q_PROPERTY(double snapshotProgress READ snapshotProgress NOTIFY snapshotProgressChanged)
3738

3839
public:
3940
explicit NodeModel(interfaces::Node& node);
@@ -52,13 +53,19 @@ class NodeModel : public QObject
5253
void setPause(bool new_pause);
5354
bool errorState() const { return m_faulted; }
5455
void setErrorState(bool new_error);
56+
double snapshotProgress() const { return m_snapshot_progress; }
57+
void setSnapshotProgress(double new_snapshot_progress);
58+
bool isSnapshotLoaded() const;
5559

5660
Q_INVOKABLE float getTotalBytesReceived() const { return (float)m_node.getTotalBytesRecv(); }
5761
Q_INVOKABLE float getTotalBytesSent() const { return (float)m_node.getTotalBytesSent(); }
5862

5963
Q_INVOKABLE void startNodeInitializionThread();
6064
Q_INVOKABLE void requestShutdown();
6165

66+
Q_INVOKABLE void initializeSnapshot(bool initLoadSnapshot, QString path_file);
67+
Q_INVOKABLE bool snapshotLoad(QString path_file, std::function<void(double)> progress_callback) const { return m_node.snapshotLoad(path_file.toStdString(), progress_callback); }
68+
6269
void startShutdownPolling();
6370
void stopShutdownPolling();
6471

@@ -77,6 +84,9 @@ public Q_SLOTS:
7784

7885
void setTimeRatioList(int new_time);
7986
void setTimeRatioListInitial();
87+
void initializationFinished();
88+
void snapshotLoaded(bool result);
89+
void snapshotProgressChanged();
8090

8191
protected:
8292
void timerEvent(QTimerEvent* event) override;
@@ -90,7 +100,7 @@ public Q_SLOTS:
90100
double m_verification_progress{0.0};
91101
bool m_pause{false};
92102
bool m_faulted{false};
93-
103+
double m_snapshot_progress{0.0};
94104
int m_shutdown_polling_timer_id{0};
95105

96106
QVector<QPair<int, double>> m_block_process_time;

0 commit comments

Comments
 (0)