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
|
#!/bin/bash
set -e
# CLN SQLite → Postgres migration
# Copies all data from the running CLN SQLite database into Postgres,
# then switches CLN to use Postgres as its backend.
#
# Prerequisites: pgcl container running, cl container running with SQLite
DB="/root/.lightning/regtest/lightningd.sqlite3"
PG="postgres://lightning:lightning@pgcl:5432/lightning"
echo "=== CLN SQLite → Postgres Migration ==="
echo ""
# ── 1. Verify current state ─────────────────────────────────────────
echo "1. Current CLN state (SQLite):"
docker exec cl lightning-cli getinfo 2>&1 | grep -E '"id"|"num_peers"|"num_active_channels"' || true
echo ""
# ── 2. Stop CLN ─────────────────────────────────────────────────────
echo "2. Stopping CLN..."
docker compose stop cl
sleep 2
echo ""
# ── 3. Ensure Postgres is up ────────────────────────────────────────
echo "3. Ensuring Postgres is ready..."
docker compose up -d pgcl
until docker exec pgcl pg_isready -U lightning > /dev/null 2>&1; do sleep 1; done
echo " Ready"
echo ""
# ── 4. Create Postgres schema via temp CLN ──────────────────────────
echo "4. Creating Postgres schema..."
docker exec pgcl psql -U lightning -d postgres -c "DROP DATABASE IF EXISTS lightning;" > /dev/null 2>&1
docker exec pgcl psql -U lightning -d postgres -c "CREATE DATABASE lightning;" > /dev/null 2>&1
# Use a temp CLN instance to create the schema
rm -rf /tmp/cln-schema-seed
mkdir -p /tmp/cln-schema-seed
cat > /tmp/cln-schema-seed/config << 'CONF'
network=regtest
bitcoin-rpcconnect=bc
bitcoin-rpcport=18443
bitcoin-rpcuser=admin1
bitcoin-rpcpassword=123
wallet=postgres://lightning:lightning@pgcl:5432/lightning
database-upgrade=true
developer
CONF
docker run -d --name cln-schema --network net \
-e LIGHTNINGD_NETWORK=regtest \
-v /tmp/cln-schema-seed:/root/.lightning \
elementsproject/lightningd:v25.12.1 > /dev/null 2>&1
sleep 10
TABLES=$(docker exec pgcl psql -U lightning -d lightning -tAc \
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public';")
docker stop cln-schema > /dev/null 2>&1 && docker rm cln-schema > /dev/null 2>&1
rm -rf /tmp/cln-schema-seed
echo " Created $TABLES tables"
echo ""
# ── 5. Truncate all Postgres tables (remove seed data) ──────────────
echo "5. Clearing seed data from Postgres..."
docker exec pgcl psql -U lightning -d lightning -tAc \
"SELECT tablename FROM pg_tables WHERE schemaname='public';" | while read tbl; do
docker exec pgcl psql -U lightning -d lightning -c "TRUNCATE \"$tbl\" CASCADE;" > /dev/null 2>&1
done
echo " Done"
echo ""
# ── 6. Install tools ────────────────────────────────────────────────
echo "6. Installing migration tools..."
docker exec pgcl apt-get update -qq > /dev/null 2>&1
docker exec pgcl apt-get install -y -qq sqlite3 python3 > /dev/null 2>&1
echo " Done"
echo ""
# ── 7. Copy SQLite file into pgcl container ─────────────────────────
echo "7. Copying SQLite database..."
docker cp "$(docker inspect cl --format '{{.GraphDriver.Data.MergedDir}}')/root/.lightning/regtest/lightningd.sqlite3" /tmp/lightningd.sqlite3 2>/dev/null \
|| docker exec cl cat "$DB" > /tmp/lightningd.sqlite3
docker cp /tmp/lightningd.sqlite3 pgcl:/tmp/lightningd.sqlite3
echo " Done"
echo ""
# ── 8. Run migration ────────────────────────────────────────────────
echo "8. Migrating data..."
docker exec pgcl bash -c 'cat > /tmp/migrate.py << '"'"'PYEOF'"'"'
import sqlite3, subprocess, json, sys
sq = sqlite3.connect("/tmp/lightningd.sqlite3")
sq.row_factory = sqlite3.Row
# Get table list from Postgres
result = subprocess.run(
["psql", "-U", "lightning", "-d", "lightning", "-tAc",
"SELECT tablename FROM pg_tables WHERE schemaname='"'"'public'"'"';"],
capture_output=True, text=True
)
pg_tables = set(result.stdout.strip().split("\n"))
# Get table list from SQLite
sq_tables = [r[0] for r in sq.execute(
"SELECT name FROM sqlite_master WHERE type='"'"'table'"'"' ORDER BY name").fetchall()]
total = 0
errors = []
for tbl in sq_tables:
if tbl not in pg_tables:
print(f" SKIP {tbl} (not in Postgres schema)")
continue
rows = sq.execute(f"SELECT * FROM [{tbl}]").fetchall()
if not rows:
continue
cols = rows[0].keys()
ncols = len(cols)
# Get Postgres column types
type_result = subprocess.run(
["psql", "-U", "lightning", "-d", "lightning", "-tAc",
f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name='"'"'{tbl}'"'"' ORDER BY ordinal_position;"],
capture_output=True, text=True
)
pg_types = {}
for line in type_result.stdout.strip().split("\n"):
if "|" in line:
parts = line.split("|")
pg_types[parts[0].strip()] = parts[1].strip()
count = 0
for row in rows:
values = []
for col in cols:
val = row[col]
if val is None:
values.append("NULL")
elif isinstance(val, bytes):
hex_str = val.hex()
values.append(f"'"'"'\\x{hex_str}'"'"'::bytea")
elif isinstance(val, int):
values.append(str(val))
elif isinstance(val, float):
values.append(str(val))
else:
escaped = str(val).replace("'"'"'", "'"'"''"'"'")
values.append(f"'"'"'{escaped}'"'"'")
col_list = ", ".join(f'"{c}"' for c in cols)
val_list = ", ".join(values)
sql = f"INSERT INTO \"{tbl}\" ({col_list}) VALUES ({val_list});"
result = subprocess.run(
["psql", "-U", "lightning", "-d", "lightning", "-c", sql],
capture_output=True, text=True
)
if result.returncode != 0:
err = result.stderr.strip()
if "duplicate key" not in err:
errors.append(f"{tbl}: {err[:120]}")
break
count += 1
total += count
print(f" {tbl}: {count} rows")
print(f"\nTotal: {total} rows migrated")
if errors:
print(f"\nErrors ({len(errors)}):")
for e in errors:
print(f" {e}")
sys.exit(1)
PYEOF
python3 /tmp/migrate.py'
echo ""
# ── 9. Verify row counts ────────────────────────────────────────────
echo "9. Verifying migration..."
echo " Key table row counts (SQLite → Postgres):"
for tbl in version channels peers outputs payments invoices vars datastore; do
SQ=$(docker exec pgcl sqlite3 /tmp/lightningd.sqlite3 "SELECT COUNT(*) FROM $tbl;" 2>/dev/null)
PG=$(docker exec pgcl psql -U lightning -d lightning -tAc "SELECT COUNT(*) FROM \"$tbl\";" 2>/dev/null)
STATUS="✓"
[ "$SQ" != "$PG" ] && STATUS="✗"
echo " $STATUS $tbl: $SQ → $PG"
done
echo ""
# ── 10. Switch CLN config to Postgres ────────────────────────────────
echo "10. Switching CLN config to Postgres..."
CONFIG_FILE="data/lightning/config"
if ! grep -q "^wallet=postgres" "$CONFIG_FILE"; then
sed -i '/^developer/i wallet=postgres://lightning:lightning@pgcl:5432/lightning' "$CONFIG_FILE"
fi
echo " Config updated"
echo ""
# ── 11. Start CLN on Postgres ───────────────────────────────────────
echo "11. Starting CLN with Postgres backend..."
docker compose up -d cl
sleep 8
for i in $(seq 1 20); do
if docker exec cl lightning-cli getinfo > /dev/null 2>&1; then
break
fi
sleep 2
done
echo ""
echo "=== Post-migration verification ==="
docker exec cl lightning-cli getinfo 2>&1 | grep -E '"id"|"num_peers"|"num_active_channels"|"blockheight"'
echo ""
echo "Funds:"
docker exec cl lightning-cli listfunds 2>&1 | jq '{outputs: (.outputs | length), channels: (.channels | length), total_sats: ([.outputs[].amount_msat] | add / 1000)}'
echo ""
echo "=== Migration complete ==="
|