Compare commits

...
2 Commits
Author SHA1 Message Date
Unheard0840 810bca8154 Merge remote server updates with address cache 2026-08-29 16:44:42 +02:00
Unheard0840 0c78b1ddd5 Add persistent server-side address cache 2026-08-29 16:39:44 +02:00
+140 -360
View File
@@ -149,11 +149,7 @@ function refreshAddressCache(
return refresh return refresh
} }
function queryFulcrum( function queryFulcrum(fulcrumUrl, method, params = []) {
fulcrumUrl,
method,
params = [],
) {
return new Promise((resolve) => { return new Promise((resolve) => {
if (!fulcrumUrl) { if (!fulcrumUrl) {
resolve({ resolve({
@@ -229,9 +225,7 @@ function queryFulcrum(
params, params,
}) + '\n' }) + '\n'
console.log( console.log(`Sending Fulcrum request: ${request.trim()}`)
`Sending Fulcrum request: ${request.trim()}`,
)
socket.write(request) socket.write(request)
}) })
@@ -239,9 +233,7 @@ function queryFulcrum(
socket.on('data', (data) => { socket.on('data', (data) => {
const chunk = data.toString() const chunk = data.toString()
console.log( console.log(`Fulcrum response data: ${chunk.trim()}`)
`Fulcrum response data: ${chunk.trim()}`,
)
response += chunk response += chunk
@@ -324,17 +316,14 @@ function queryFulcrum(
finish({ finish({
ok: false, ok: false,
result: null, result: null,
error: error: 'Connection closed before a response was received',
'Connection closed before a response was received',
}) })
} }
}) })
}) })
} }
async function getFulcrumStatus( async function getFulcrumStatus(fulcrumUrl) {
fulcrumUrl,
) {
const version = await queryFulcrum( const version = await queryFulcrum(
fulcrumUrl, fulcrumUrl,
'server.version', 'server.version',
@@ -367,20 +356,13 @@ async function getFulcrumStatus(
headers.ok && headers.result headers.ok && headers.result
? headers.result.height ?? null ? headers.result.height ?? null
: null, : null,
error: headers.ok error: headers.ok ? null : headers.error,
? null
: headers.error,
} }
} }
async function getStatus() { async function getStatus() {
const fulcrumUrl = const fulcrumUrl = process.env.MUNIN_FULCRUM_URL || null
process.env.MUNIN_FULCRUM_URL || null const fulcrum = await getFulcrumStatus(fulcrumUrl)
const fulcrum =
await getFulcrumStatus(
fulcrumUrl,
)
return { return {
service: 'running', service: 'running',
@@ -445,23 +427,15 @@ async function getAddressDataFromFulcrum(
address, address,
scripthash, scripthash,
confirmedBalance: confirmedBalance:
Number( Number(balance.result?.confirmed || 0),
balance.result?.confirmed || 0,
),
unconfirmedBalance: unconfirmedBalance:
Number( Number(balance.result?.unconfirmed || 0),
balance.result?.unconfirmed || 0,
),
utxos: utxos:
Array.isArray( Array.isArray(utxos.result)
utxos.result,
)
? utxos.result ? utxos.result
: [], : [],
history: history:
Array.isArray( Array.isArray(history.result)
history.result,
)
? history.result ? history.result
: [], : [],
lastSynced: lastSynced:
@@ -469,16 +443,12 @@ async function getAddressDataFromFulcrum(
} }
} }
async function getAddressData( async function getAddressData(address) {
address,
) {
let scripthash let scripthash
try { try {
scripthash = scripthash =
addressToScripthash( addressToScripthash(address)
address,
)
} catch (error) { } catch (error) {
throw new Error( throw new Error(
error instanceof Error error instanceof Error
@@ -488,9 +458,7 @@ async function getAddressData(
} }
const cached = const cached =
readAddressCache( readAddressCache(scripthash)
scripthash,
)
if (cached) { if (cached) {
if ( if (
@@ -523,49 +491,31 @@ async function getAddressData(
} }
async function getAddressesWithData() { async function getAddressesWithData() {
const addresses = const addresses = await listAddresses()
await listAddresses()
const results = [] const results = []
for ( for (const entry of addresses) {
const entry of addresses
) {
try { try {
const data = const data = await getAddressData(entry.address)
await getAddressData(
entry.address,
)
results.push({ results.push({
...entry, ...entry,
scripthash: scripthash: data.scripthash,
data.scripthash, confirmedBalance: data.confirmedBalance,
confirmedBalance: unconfirmedBalance: data.unconfirmedBalance,
data.confirmedBalance, utxos: data.utxos,
unconfirmedBalance: history: data.history,
data.unconfirmedBalance,
utxos:
data.utxos,
history:
data.history,
lastSynced: lastSynced:
data.lastSynced || data.lastSynced || null,
null,
cacheAgeMs: cacheAgeMs:
Number( Number(data.cacheAgeMs || 0),
data.cacheAgeMs ||
0,
),
error: null, error: null,
}) })
} catch (error) { } catch (error) {
results.push({ results.push({
...entry, ...entry,
confirmedBalance: confirmedBalance: null,
null, unconfirmedBalance: null,
unconfirmedBalance:
null,
utxos: [], utxos: [],
history: [], history: [],
lastSynced: null, lastSynced: null,
@@ -581,13 +531,8 @@ async function getAddressesWithData() {
return results return results
} }
const server = const server = http.createServer(async (req, res) => {
http.createServer( if (req.method === 'POST' && req.url === '/api/login') {
async (req, res) => {
if (
req.method === 'POST' &&
req.url === '/api/login'
) {
let body = '' let body = ''
req.on('data', (chunk) => { req.on('data', (chunk) => {
@@ -596,48 +541,31 @@ const server =
req.on('end', () => { req.on('end', () => {
try { try {
const input = const input = JSON.parse(body)
JSON.parse(body)
if ( if (!checkPassword(input.password)) {
!checkPassword( res.writeHead(401, {
input.password, 'Content-Type': 'application/json',
) })
) {
res.writeHead(
401,
{
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Invalid password',
'Invalid password',
}), }),
) )
return return
} }
const token = const token = createSession()
createSession()
res.writeHead( res.writeHead(200, {
200, 'Content-Type': 'application/json',
{
'Content-Type':
'application/json',
'Set-Cookie': 'Set-Cookie':
'munin_session=' + 'munin_session=' +
encodeURIComponent( encodeURIComponent(token) +
token,
) +
'; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=86400', '; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=86400',
}, })
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
@@ -645,18 +573,13 @@ const server =
}), }),
) )
} catch { } catch {
res.writeHead( res.writeHead(400, {
400, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Invalid request',
'Invalid request',
}), }),
) )
} }
@@ -665,25 +588,15 @@ const server =
return return
} }
if ( if (req.url === '/api/status') {
req.url === if (!isValidSession(req)) {
'/api/status' res.writeHead(401, {
) { 'Content-Type': 'application/json',
if ( })
!isValidSession(req)
) {
res.writeHead(
401,
{
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Authentication required',
'Authentication required',
}), }),
) )
@@ -691,42 +604,27 @@ const server =
} }
try { try {
const status = const status = await getStatus()
await getStatus()
res.writeHead( res.writeHead(200, {
200, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(JSON.stringify(status))
JSON.stringify(
status,
),
)
} catch (error) { } catch (error) {
console.error( console.error(
'Failed to get service status:', 'Failed to get service status:',
error, error,
) )
res.writeHead( res.writeHead(500, {
500, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
service: service: 'running',
'running', error: 'Failed to determine service status',
error:
'Failed to determine service status',
}), }),
) )
} }
@@ -734,26 +632,15 @@ const server =
return return
} }
if ( if (req.method === 'GET' && req.url === '/api/addresses') {
req.method === 'GET' && if (!isValidSession(req)) {
req.url === res.writeHead(401, {
'/api/addresses' 'Content-Type': 'application/json',
) { })
if (
!isValidSession(req)
) {
res.writeHead(
401,
{
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Authentication required',
'Authentication required',
}), }),
) )
@@ -761,16 +648,11 @@ const server =
} }
try { try {
const addresses = const addresses = await listAddresses()
await listAddresses()
res.writeHead( res.writeHead(200, {
200, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
@@ -783,18 +665,13 @@ const server =
error, error,
) )
res.writeHead( res.writeHead(500, {
500, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Failed to list addresses',
'Failed to list addresses',
}), }),
) )
} }
@@ -804,24 +681,16 @@ const server =
if ( if (
req.method === 'GET' && req.method === 'GET' &&
req.url === req.url === '/api/addresses/data'
'/api/addresses/data'
) { ) {
if ( if (!isValidSession(req)) {
!isValidSession(req) res.writeHead(401, {
) { 'Content-Type': 'application/json',
res.writeHead( })
401,
{
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Authentication required',
'Authentication required',
}), }),
) )
@@ -829,16 +698,11 @@ const server =
} }
try { try {
const addresses = const addresses = await getAddressesWithData()
await getAddressesWithData()
res.writeHead( res.writeHead(200, {
200, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
@@ -851,18 +715,13 @@ const server =
error, error,
) )
res.writeHead( res.writeHead(500, {
500, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Failed to get address data',
'Failed to get address data',
}), }),
) )
} }
@@ -872,24 +731,16 @@ const server =
if ( if (
req.method === 'POST' && req.method === 'POST' &&
req.url === req.url === '/api/addresses'
'/api/addresses'
) { ) {
if ( if (!isValidSession(req)) {
!isValidSession(req) res.writeHead(401, {
) { 'Content-Type': 'application/json',
res.writeHead( })
401,
{
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Authentication required',
'Authentication required',
}), }),
) )
@@ -902,40 +753,24 @@ const server =
body += chunk body += chunk
}) })
req.on( req.on('end', async () => {
'end',
async () => {
try { try {
const input = const input = JSON.parse(body)
JSON.parse(body)
const entry = const entry = await addAddress(
await addAddress(
input.address, input.address,
input.label, input.label,
) )
res.writeHead( res.writeHead(201, {
201, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(JSON.stringify(entry))
JSON.stringify(
entry,
),
)
} catch (error) { } catch (error) {
res.writeHead( res.writeHead(400, {
400, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
@@ -946,32 +781,23 @@ const server =
}), }),
) )
} }
}, })
)
return return
} }
if ( if (
req.method === 'DELETE' && req.method === 'DELETE' &&
req.url === req.url === '/api/addresses'
'/api/addresses'
) { ) {
if ( if (!isValidSession(req)) {
!isValidSession(req) res.writeHead(401, {
) { 'Content-Type': 'application/json',
res.writeHead( })
401,
{
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Authentication required',
'Authentication required',
}), }),
) )
@@ -984,24 +810,15 @@ const server =
body += chunk body += chunk
}) })
req.on( req.on('end', async () => {
'end',
async () => {
try { try {
const input = const input = JSON.parse(body)
JSON.parse(body)
await removeAddress( await removeAddress(input.address)
input.address,
)
res.writeHead( res.writeHead(200, {
200, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
@@ -1009,13 +826,9 @@ const server =
}), }),
) )
} catch (error) { } catch (error) {
res.writeHead( res.writeHead(400, {
400, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
@@ -1026,74 +839,45 @@ const server =
}), }),
) )
} }
}, })
)
return return
} }
if ( if (
req.method === 'GET' && req.method === 'GET' &&
req.url.startsWith( req.url.startsWith('/api/transactions/')
'/api/transactions/',
)
) { ) {
if ( if (!isValidSession(req)) {
!isValidSession(req) res.writeHead(401, {
) { 'Content-Type': 'application/json',
res.writeHead( })
401,
{
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
error: error: 'Authentication required',
'Authentication required',
}), }),
) )
return return
} }
const txid = const txid = decodeURIComponent(
decodeURIComponent( req.url.slice('/api/transactions/'.length),
req.url.slice(
'/api/transactions/'
.length,
),
) )
try { try {
const transaction = const transaction = await getTransaction(txid)
await getTransaction(
txid,
)
res.writeHead( res.writeHead(200, {
200, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(JSON.stringify(transaction))
JSON.stringify(
transaction,
),
)
} catch (error) { } catch (error) {
res.writeHead( res.writeHead(400, {
400, 'Content-Type': 'application/json',
{ })
'Content-Type':
'application/json',
},
)
res.end( res.end(
JSON.stringify({ JSON.stringify({
@@ -1110,14 +894,10 @@ const server =
res.writeHead(404) res.writeHead(404)
res.end('Not found') res.end('Not found')
}, })
)
server.listen( server.listen(port, () => {
port,
() => {
console.log( console.log(
`Status API listening on port ${port}`, `Status API listening on port ${port}`,
) )
}, })
)