Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export function buildApp(config: Config, deps: AppDeps = {}) {

const app = express();

// Behind exactly one proxy hop (Cloud Run's frontend). Without this req.ip is the
// proxy address, so the /post rate limit would be one shared bucket for everyone.
app.set("trust proxy", 1);

app.use(cors({
origin: config.corsOrigins === "*" ? true : config.corsOrigins.split(",").map(s => s.trim()),
}));
Expand Down
15 changes: 5 additions & 10 deletions src/controllers/PostController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,11 @@ export class PostController {

let build;
try {
build = await this.sponsor.buildSpendingTo(script);
// Build, submit and advance under one lock so concurrent posts chain
// off each other's change output instead of double-spending one UTXO.
build = await this.sponsor.buildSubmitAndAdvance(script, async (b) => {
await this.overlay.submit(b.beefHex, [this.config.overlayTopic]);
});
} catch (e) {
if (e instanceof InsufficientFundsError) {
res.status(503).json({ error: "sponsor wallet out of funds" });
Expand All @@ -159,12 +163,6 @@ export class PostController {
res.status(503).json({ error: "sponsor wallet has no UTXO state" });
return;
}
throw e;
}

try {
await this.overlay.submit(build.beefHex, [this.config.overlayTopic]);
} catch (e) {
if (e instanceof OverlayError) {
console.error("[PostController] overlay rejected:", e.message);
res.status(502).json({ error: "overlay rejected broadcast", detail: e.message });
Expand All @@ -173,9 +171,6 @@ export class PostController {
throw e;
}

// Overlay accepted + admitted — commit the new UTXO chain.
this.sponsor.advance(build.changeUtxo);

res.json({
txid: build.txid,
script_hex: script.toHex(),
Expand Down
21 changes: 21 additions & 0 deletions src/services/SponsorWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,27 @@ export class SponsorWallet {
return next;
}

/**
* Build, submit and commit in one critical section. buildSpendingTo() alone
* releases the lock before the caller has submitted and advanced, so two
* concurrent posts would both spend the same UTXO. Here the next build
* starts only after `submit` resolved and the change output was committed,
* or after it rejected (state unchanged).
*/
async buildSubmitAndAdvance(
opReturnScript: Script,
submit: (build: BroadcastBuildResult) => Promise<void>,
): Promise<BroadcastBuildResult> {
const next = this.buildLock.then(async () => {
const build = await this._build(opReturnScript);
await submit(build);
this.advance(build.changeUtxo);
return build;
});
this.buildLock = next.catch(() => undefined);
return next;
}

private async _build(opReturnScript: Script): Promise<BroadcastBuildResult> {
const utxo = this.currentUtxo;
if (!utxo) throw new NoSeededUtxoError();
Expand Down
26 changes: 26 additions & 0 deletions test/post.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,11 @@ class FakeWab extends WabClient {
class FakeOverlay extends OverlayClient {
public submitCalls: { beefHex: string; topics: string[] }[] = [];
public mode: "ok" | "no-admit" | "http-500" = "ok";
public delayMs = 0;
constructor() { super("http://fake-overlay"); }
public override async submit(beefHex: string, topics: string[] = ["peck-schema"]) {
this.submitCalls.push({ beefHex, topics });
if (this.delayMs) await new Promise(r => setTimeout(r, this.delayMs));
if (this.mode === "no-admit") {
throw new OverlayError(200, "overlay admitted no outputs (test)");
}
Expand Down Expand Up @@ -386,4 +388,28 @@ describe("POST /post — broadcast layer", () => {
expect(res1.body.txid).not.toBe(res2.body.txid);
expect(overlay.submitCalls.length).toBe(2);
});

it("concurrent posts chain off each other instead of spending the same UTXO", async () => {
const { app, overlay } = await setup();
overlay.delayMs = 50;
const send = (n: string) => request(app).post("/post").send({
url: `https://example.com/${n}`, comment: n, id_token: "valid",
});
const [r1, r2] = await Promise.all([send("a"), send("b")]);
expect(r1.status).toBe(200);
expect(r2.status).toBe(200);
expect(overlay.submitCalls.length).toBe(2);
const [first, second] = overlay.submitCalls.map(c => Transaction.fromHexBEEF(c.beefHex));
expect(second.inputs[0].sourceTXID).toBe(first.id("hex"));
});
});

describe("POST /post — rate limit key", () => {
it("limits per X-Forwarded-For client, not one bucket for every caller", async () => {
const { app } = await setup();
const hit = (ip: string) => request(app).post("/post").set("X-Forwarded-For", ip).send({});
for (let i = 0; i < 10; i++) expect((await hit("198.51.100.1")).status).toBe(400);
expect((await hit("198.51.100.1")).status).toBe(429);
expect((await hit("198.51.100.2")).status).toBe(400);
});
});
Loading