Skip to content

Commit 799b4cd

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 implement 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 working, could be improved Testing: 1. Start the node 2. Complete onboarding 3. Navigate to connection settings 4. Load snapshot from provided interface
1 parent c97d2a1 commit 799b4cd

File tree

11 files changed

+279
-29
lines changed

11 files changed

+279
-29
lines changed

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

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

+88-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,95 @@ 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+
// Snapshot Progress GUI display
443+
COutPoint outpoint;
444+
Coin coin;
445+
const uint64_t coins_count = metadata.m_coins_count;
446+
uint64_t coins_left = metadata.m_coins_count;
447+
448+
LogPrintf("[loadsnapshot] Loading %d coins from snapshot %s\n", coins_count, base_blockhash.ToString());
449+
int64_t coins_processed{0};
450+
m_snapshot_progress.store(0.0);
451+
452+
while (coins_left > 0) {
453+
--coins_left;
454+
++coins_processed;
455+
456+
if (coins_processed > 0) {
457+
double progress = static_cast<float>(coins_processed) / static_cast<float>(coins_count);
458+
m_snapshot_progress.store(progress);
459+
if (coins_processed % 1000000 == 0) {
460+
LogPrintf("[loadsnapshot] Progress: %.2f%% (%d/%d coins)\n",
461+
progress * 100, coins_processed, coins_count);
462+
}
463+
}
464+
}
465+
m_snapshot_progress.store(1.0);
466+
467+
if (!snapshot_start_block) {
468+
LogPrintf("[loadsnapshot] Timed out waiting for snapshot start blockheader %s\n", base_blockhash.ToString());
469+
return false;
470+
}
471+
472+
// Activate the snapshot
473+
if (!chainman.ActivateSnapshot(afile, metadata, false)) {
474+
LogPrintf("[loadsnapshot] Unable to load UTXO snapshot %s\n", path.u8string());
475+
return false;
476+
}
477+
478+
CBlockIndex* new_tip = WITH_LOCK(::cs_main, return chainman.ActiveTip());
479+
LogPrintf("[loadsnapshot] Loaded %d coins from snapshot %s at height %d\n",
480+
metadata.m_coins_count, new_tip->GetBlockHash().ToString(), new_tip->nHeight);
481+
482+
return true;
483+
}
398484
ArgsManager& args() { return *Assert(Assert(m_context)->args); }
399485
ChainstateManager& chainman() { return *Assert(m_context->chainman); }
400486
NodeContext* m_context{nullptr};
487+
std::atomic<double> m_snapshot_progress{0.0};
401488
};
402489

403490
bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman)
@@ -510,7 +597,7 @@ class RpcHandlerImpl : public Handler
510597
class ChainImpl : public Chain
511598
{
512599
public:
513-
explicit ChainImpl(NodeContext& node) : m_node(node) {}
600+
explicit ChainImpl(node::NodeContext& node) : m_node(node) {}
514601
std::optional<int> getHeight() override
515602
{
516603
const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};

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

src/qml/components/SnapshotSettings.qml

+66-11
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,25 @@
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+
property bool snapshotLoading: nodeModel.snapshotLoading
1214
signal snapshotImportCompleted()
1315
property int snapshotVerificationCycles: 0
1416
property real snapshotVerificationProgress: 0
15-
property bool snapshotVerified: false
17+
property bool onboarding: false
18+
property bool snapshotVerified: onboarding ? false : chainModel.isSnapshotActive
19+
property string snapshotFileName: ""
20+
property var snapshotInfo: ({})
1621

1722
id: columnLayout
1823
width: Math.min(parent.width, 450)
1924
anchors.horizontalCenter: parent.horizontalCenter
2025

21-
26+
// TODO: remove this before release
2227
Timer {
2328
id: snapshotSimulationTimer
2429
interval: 50 // Update every 50ms
@@ -29,7 +34,7 @@ ColumnLayout {
2934
snapshotVerificationProgress += 0.01
3035
} else {
3136
snapshotVerificationCycles++
32-
if (snapshotVerificationCycles < 1) {
37+
if (snapshotVerificationCycles < 3) {
3338
snapshotVerificationProgress = 0
3439
} else {
3540
running = false
@@ -42,7 +47,7 @@ ColumnLayout {
4247

4348
StackLayout {
4449
id: settingsStack
45-
currentIndex: 0
50+
currentIndex: onboarding ? 0 : snapshotVerified ? 2 : snapshotLoading ? 1 : 0
4651

4752
ColumnLayout {
4853
Layout.alignment: Qt.AlignHCenter
@@ -78,8 +83,25 @@ ColumnLayout {
7883
Layout.alignment: Qt.AlignCenter
7984
text: qsTr("Choose snapshot file")
8085
onClicked: {
81-
settingsStack.currentIndex = 1
82-
snapshotSimulationTimer.start()
86+
fileDialog.open()
87+
}
88+
}
89+
90+
FileDialog {
91+
id: fileDialog
92+
folder: shortcuts.home
93+
selectMultiple: false
94+
selectExisting: true
95+
nameFilters: ["Snapshot files (*.dat)", "All files (*)"]
96+
onAccepted: {
97+
console.log("File chosen:", fileDialog.fileUrls)
98+
snapshotFileName = fileDialog.fileUrl.toString()
99+
console.log("Snapshot file name:", snapshotFileName)
100+
if (snapshotFileName.endsWith(".dat")) {
101+
nodeModel.initializeSnapshot(true, snapshotFileName)
102+
} else {
103+
console.error("Snapshot loading failed")
104+
}
83105
}
84106
}
85107
}
@@ -102,17 +124,37 @@ ColumnLayout {
102124
Layout.leftMargin: 20
103125
Layout.rightMargin: 20
104126
header: qsTr("Loading Snapshot")
127+
description: qsTr("This might take a while...")
105128
}
106129

107130
ProgressIndicator {
108131
id: progressIndicator
109132
Layout.topMargin: 20
110133
width: 200
111134
height: 20
112-
progress: snapshotVerificationProgress
135+
progress: nodeModel.snapshotProgress
113136
Layout.alignment: Qt.AlignCenter
114137
progressColor: Theme.color.blue
115138
}
139+
140+
Connections {
141+
target: nodeModel
142+
function onSnapshotProgressChanged() {
143+
progressIndicator.progress = nodeModel.snapshotProgress
144+
}
145+
146+
function onSnapshotLoaded(success) {
147+
if (success) {
148+
chainModel.isSnapshotActiveChanged()
149+
snapshotVerified = chainModel.isSnapshotActive
150+
snapshotInfo = chainModel.getSnapshotInfo()
151+
settingsStack.currentIndex = 2 // Move to the "Snapshot Loaded" page
152+
} else {
153+
// Handle snapshot loading failure
154+
console.error("Snapshot loading failed")
155+
}
156+
}
157+
}
116158
}
117159

118160
ColumnLayout {
@@ -137,8 +179,11 @@ ColumnLayout {
137179
descriptionColor: Theme.color.neutral6
138180
descriptionSize: 17
139181
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.")
182+
description: snapshotInfo && snapshotInfo["date"] ?
183+
qsTr("It contains transactions up to %1. Newer transactions still need to be downloaded." +
184+
" The data will be verified in the background.").arg(snapshotInfo["date"]) :
185+
qsTr("It contains transactions up to DEBUG. Newer transactions still need to be downloaded." +
186+
" The data will be verified in the background.")
142187
}
143188

144189
ContinueButton {
@@ -188,16 +233,26 @@ ColumnLayout {
188233
font.pixelSize: 14
189234
}
190235
CoreText {
191-
text: qsTr("200,000")
236+
text: snapshotInfo && snapshotInfo["height"] ?
237+
snapshotInfo["height"] : qsTr("DEBUG")
192238
Layout.alignment: Qt.AlignRight
193239
font.pixelSize: 14
194240
}
195241
}
196242
Separator { Layout.fillWidth: true }
197243
CoreText {
198-
text: qsTr("Hash: 0x1234567890abcdef...")
244+
// The CoreText component displays the hash of the loaded snapshot.
245+
text: snapshotInfo && snapshotInfo["hashSerialized"] ?
246+
qsTr("Hash: %1").arg(snapshotInfo["hashSerialized"].substring(0, 13) + "...") :
247+
qsTr("Hash: DEBUG")
199248
font.pixelSize: 14
200249
}
250+
251+
Component.onCompleted: {
252+
if (snapshotVerified) {
253+
snapshotInfo = chainModel.getSnapshotInfo()
254+
}
255+
}
201256
}
202257
}
203258
}

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+
}

0 commit comments

Comments
 (0)