aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-02-09 01:19:33 -0800
committerAdam Soltys <[email protected]>2026-02-09 01:19:33 -0800
commit6f933c6e989f934364a276815826364fec5a85b4 (patch)
tree54e5b7818250a8cadcbb20111f24c9a5ee4bc674
parent3cde20ead47bf2fc895ea37789b824098b984f7a (diff)
downloadcoinos-server-6f933c6e989f934364a276815826364fec5a85b4.tar.gz
coinos-server-6f933c6e989f934364a276815826364fec5a85b4.zip
ark fixes
-rw-r--r--index.ts2
-rw-r--r--lib/ark.ts13
-rw-r--r--routes/payments.ts207
-rw-r--r--test/forward.test.ts12
-rw-r--r--test/preload.ts8
5 files changed, 197 insertions, 45 deletions
diff --git a/index.ts b/index.ts
index 31c48f3e..c626a961 100644
--- a/index.ts
+++ b/index.ts
@@ -120,6 +120,8 @@ app.post("/bitcoin/tx", payments.txWebhook);
app.post("/bitcoin/fee", auth, payments.fee);
app.post("/bitcoin/send", auth, payments.send);
app.post("/ark/send", auth, payments.ark);
+app.post("/ark/vault-send", auth, payments.arkVaultSend);
+app.post("/ark/vault-receive", auth, payments.arkVaultReceive);
app.get("/account/:id", auth, users.account);
app.post("/account/:id", auth, users.updateAccount);
diff --git a/lib/ark.ts b/lib/ark.ts
index 44fa4fdd..00ea4db4 100644
--- a/lib/ark.ts
+++ b/lib/ark.ts
@@ -30,3 +30,16 @@ export const getArkBalance = async () => {
const w = await getWallet();
return w.getBalance();
};
+
+export const verifyArkVtxo = async (hash: string) => {
+ const { bech32m } = await import("@scure/base");
+ const serverAddr = await getArkAddress();
+ const decoded = bech32m.decode(serverAddr, 1023);
+ const words = new Uint8Array(bech32m.fromWords(decoded.words));
+ const vtxoHex = Buffer.from(words.slice(33, 65)).toString("hex");
+ const r = await fetch(
+ `http://arkd:7070/v1/indexer/vtxos?scripts=5120${vtxoHex}&spendable_only=true`,
+ );
+ const { vtxos } = await r.json();
+ return vtxos?.some((v: any) => v.outpoint?.txid === hash) ?? false;
+};
diff --git a/routes/payments.ts b/routes/payments.ts
index a93a1882..a9e14867 100644
--- a/routes/payments.ts
+++ b/routes/payments.ts
@@ -1,6 +1,6 @@
import config from "$config";
import api from "$lib/api";
-import { getArkAddress, sendArk } from "$lib/ark";
+import { getArkAddress, sendArk, verifyArkVtxo } from "$lib/ark";
import { requirePin } from "$lib/auth";
import { archive, db, g, gf, s } from "$lib/db";
import { getTx } from "$lib/esplora";
@@ -809,6 +809,82 @@ export default {
}
},
+ async arkVaultSend(req, res) {
+ try {
+ const { body, user } = req;
+ const { hash, amount, aid } = body;
+ const { id: uid } = user;
+
+ const rates = await g("rates");
+ const { currency } = user;
+ const rate = rates[currency];
+
+ const p = {
+ id: v4(),
+ aid,
+ amount: -amount,
+ hash,
+ confirmed: true,
+ rate,
+ currency,
+ type: PaymentType.ark,
+ uid,
+ created: Date.now(),
+ };
+
+ const m = db.multi();
+ m.set(`payment:${p.id}`, JSON.stringify(p))
+ .set(`payment:${aid}:${hash}`, JSON.stringify(p.id))
+ .lPush(`${aid}:payments`, p.id)
+ .set(`${aid}:payments:last`, p.created);
+ await m.exec();
+
+ res.send(p);
+ } catch (e) {
+ bail(res, e.message);
+ }
+ },
+
+ async arkVaultReceive(req, res) {
+ try {
+ const { body, user } = req;
+ const { amount, hash, aid } = body;
+ const { id: uid } = user;
+
+ if (amount <= 0) fail("Invalid amount");
+
+ const locked = await db.set(`arklock:${hash}`, "1", { NX: true, EX: 60 });
+ if (!locked) fail("Already processed");
+
+ const rates = await g("rates");
+ const { currency } = user;
+ const rate = rates[currency];
+
+ const p = {
+ id: v4(),
+ aid,
+ amount,
+ hash,
+ confirmed: true,
+ rate,
+ currency,
+ type: PaymentType.ark,
+ uid,
+ created: Date.now(),
+ };
+
+ const m = db.multi();
+ m.set(`payment:${p.id}`, JSON.stringify(p))
+ .lPush(`${aid}:payments`, p.id)
+ .set(`${aid}:payments:last`, p.created);
+ await m.exec();
+
+ res.send(p);
+ } catch (e) {
+ bail(res, e.message);
+ }
+ },
+
async arkAddress(_, res) {
res.send(await getArkAddress());
},
@@ -823,9 +899,19 @@ export default {
const invoice = await getInvoice(iid);
if (invoice.uid !== user?.id) fail("Unauthorized");
- invoice.received += amount;
let { aid, type, currency } = invoice;
+
+ // Verify VTXO belongs to the server's Ark wallet
+ if (hash) {
+ const locked = await db.set(`arklock:${hash}`, "1", { NX: true, EX: 60 });
+ if (!locked) fail("Already processed");
+
+ if (!(await verifyArkVtxo(hash)))
+ fail("VTXO not found in server wallet");
+ }
+
+ invoice.received += amount;
const rates = await g("rates");
const rate = rates[currency];
@@ -854,6 +940,26 @@ export default {
if (hash) m.set(`payment:${aid}:${hash}`, p.id);
+ // Record debit on the vault account if it differs from custodial
+ if (aid && aid !== uid) {
+ const d = {
+ id: v4(),
+ aid,
+ amount: -amount,
+ hash,
+ confirmed: true,
+ rate,
+ currency,
+ type,
+ uid,
+ created: p.created,
+ };
+
+ m.set(`payment:${d.id}`, JSON.stringify(d))
+ .lPush(`${aid}:payments`, d.id)
+ .set(`${aid}:payments:last`, d.created);
+ }
+
await m.exec();
await completePayment(invoice, p, user);
@@ -870,49 +976,74 @@ export default {
const { transactions, aid } = req.body;
const { id: uid, currency } = user;
- const rates = await g("rates");
- const rate = rates[currency];
+ // Per-account lock prevents concurrent syncs from racing
+ const lockKey = `arksynclock:${aid}`;
+ const gotLock = await db.set(lockKey, "1", { NX: true, EX: 30 });
+ if (!gotLock) return res.send({ synced: 0, received: 0, payments: [] });
+
+ try {
+ const rates = await g("rates");
+ const rate = rates[currency];
- let synced = 0;
- for (const tx of transactions) {
- const existingId = await g(`payment:${aid}:${tx.hash}`);
- if (existingId) {
- const existing = await g(`payment:${existingId}`);
- if (existing && !existing.confirmed && tx.settled) {
- existing.confirmed = true;
- await s(`payment:${existingId}`, existing);
+ let synced = 0;
+ let received = 0;
+ const payments = [];
+
+ for (const tx of transactions) {
+ const hashes = [tx.arkTxid, tx.commitmentTxid, tx.hash].filter(Boolean);
+ if (!hashes.length) continue;
+
+ // Check if any hash is already known
+ let found = false;
+ for (const h of hashes) {
+ const existingId = await g(`payment:${aid}:${h}`);
+ if (existingId) {
+ const existing = await g(`payment:${existingId}`);
+ if (existing && !existing.confirmed && tx.settled) {
+ existing.confirmed = true;
+ await s(`payment:${existingId}`, existing);
+ }
+ found = true;
+ break;
+ }
}
- continue;
- }
+ if (found) continue;
- // Skip received/change VTXOs — handled by arkReceive
- if (tx.amount > 0) continue;
+ const primaryHash = hashes[0];
- const p = {
- id: v4(),
- aid,
- amount: tx.amount,
- hash: tx.hash,
- confirmed: true,
- rate,
- currency,
- type: PaymentType.ark,
- uid,
- created: tx.createdAt,
- };
+ const p = {
+ id: v4(),
+ aid,
+ amount: tx.amount,
+ hash: primaryHash,
+ confirmed: true,
+ rate,
+ currency,
+ type: PaymentType.ark,
+ uid,
+ created: tx.createdAt,
+ };
- await s(`payment:${aid}:${tx.hash}`, p.id);
- await s(`payment:${p.id}`, p);
- await db
- .multi()
- .lPush(`${aid || uid}:payments`, p.id)
- .set(`${aid || uid}:payments:last`, p.created)
- .exec();
+ const m = db.multi();
+ m.set(`payment:${p.id}`, JSON.stringify(p))
+ .lPush(`${aid || uid}:payments`, p.id)
+ .set(`${aid || uid}:payments:last`, p.created);
- synced++;
- }
+ for (const h of hashes) {
+ m.set(`payment:${aid}:${h}`, JSON.stringify(p.id));
+ }
+
+ await m.exec();
- res.send({ synced });
+ payments.push(p);
+ synced++;
+ if (tx.amount > 0) received += tx.amount;
+ }
+
+ res.send({ synced, received, payments });
+ } finally {
+ await db.del(lockKey);
+ }
} catch (e) {
bail(res, e.message);
}
diff --git a/test/forward.test.ts b/test/forward.test.ts
index c387c489..1e0cd566 100644
--- a/test/forward.test.ts
+++ b/test/forward.test.ts
@@ -296,12 +296,12 @@ describe("arkReceive", () => {
describe("arkSync", () => {
beforeEach(resetAll);
- test("skips received/change VTXOs (positive amounts)", async () => {
+ test("records received VTXOs (positive amounts)", async () => {
const req = {
body: {
aid: arkAccountId,
transactions: [
- { hash: "change-vtxo-hash", amount: 9000, settled: true, createdAt: Date.now() },
+ { hash: "recv-vtxo-hash", amount: 9000, settled: true, createdAt: Date.now() },
],
},
user: makeUser(),
@@ -311,8 +311,9 @@ describe("arkSync", () => {
await routes.arkSync(req as any, res as any);
const sent = (res as any).getSent();
- expect(sent.synced).toBe(0);
- expect(store().listStore[`${arkAccountId}:payments`] ?? []).toHaveLength(0);
+ expect(sent.synced).toBe(1);
+ expect(sent.received).toBe(9000);
+ expect(store().listStore[`${arkAccountId}:payments`] ?? []).toHaveLength(1);
});
test("records sent transactions (negative amounts)", async () => {
@@ -335,7 +336,8 @@ describe("arkSync", () => {
});
test("deduplicates known transactions", async () => {
- // Pre-store a known tx hash
+ // Pre-store a known tx hash and its sync lock
+ store().kvStore[`arksync:${arkAccountId}:known-hash`] = "1";
store().kvStore[`payment:${arkAccountId}:known-hash`] = JSON.stringify("existing-id");
store().kvStore["payment:existing-id"] = JSON.stringify({ id: "existing-id", confirmed: false });
diff --git a/test/preload.ts b/test/preload.ts
index 0704561a..151c3c64 100644
--- a/test/preload.ts
+++ b/test/preload.ts
@@ -71,7 +71,11 @@ mock.module("$lib/db", () => {
return {
db: {
get: async (k: string) => kv()[k] ?? null,
- set: async (k: string, v: string) => { kv()[k] = v; return "OK"; },
+ set: async (k: string, v: string, opts?: any) => {
+ if (opts?.NX && kv()[k] !== undefined) return null;
+ kv()[k] = v;
+ return "OK";
+ },
del: async (k: string) => { delete kv()[k]; return 1; },
exists: async (k: string) => (kv()[k] !== undefined ? 1 : 0),
lPush: async (k: string, v: string) => {
@@ -185,7 +189,7 @@ mock.module("$lib/nostr", () => ({
}));
mock.module("$lib/mqtt", () => ({ default: { publish: () => {} } }));
mock.module("$lib/ark", () => ({
- getArkAddress: async () => "ark-addr", sendArk: async () => "ark-txid", getArkBalance: async () => 0,
+ getArkAddress: async () => "ark-addr", sendArk: async () => "ark-txid", getArkBalance: async () => 0, verifyArkVtxo: async () => true,
}));
mock.module("$lib/ecash", () => ({ request: async () => ({}) }));
mock.module("$lib/lightning", () => ({