Roadmap step 9: POST /api/v1/swap/:from/:to validates postage-ready ALP
txs (schema, maker fee, ±1% CP band), serializes fuel+sign+broadcast on
a process-local queue via PostageTx, returns txid + postagePaidSats.
No DB audit or platform-fee opt-in yet.
Details
- Reviewers
Fabien - Group Reviewers
Restricted Project - Commits
- rABC19b00eb15e9a: [alp-dex] Add postage-protocol settle API
- cd apps/alp-dex && pnpm test
- cd apps/alp-dex && pnpm run build
Diff Detail
- Repository
- rABC Bitcoin ABC
- Lint
Lint Not Applicable - Unit
Tests Not Applicable
Event Timeline
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) I am the one who bugs.
────────────────────────────────────────────────────────────────────────
minor [Maintainability & Code Quality] → ]8;;vscode://file//work/apps/alp-dex/SPEC.md:212apps/alp-dex/SPEC.md:212-214]8;; Document the required order of the optional change outputs. validatePartiallySignedTx enforces a strict order when two optional outputs are present. apps/alp-dex/src/settle/parseSwap.ts Lines 558-581 require the toToken change to slush first, then the fromToken change to a non-reserved script. A taker that emits the reverse order gets a 400. The spec section only says "Optional change outs (schema-allowed)", so client authors cannot derive that rule. Add the ordering rule and the single-optional-output cases to this section.
────────────────────────────────────────────────────────────────────────
minor [Maintainability & Code Quality]
→ ]8;;vscode://file//work/apps/alp-dex/test/settle.test.ts:77apps/alp-dex/test/settle.test.ts:77-83]8;;
Change the fixture sats default so the postage assertion can detect an
overcount.
Line 82 defaults sats to 1000n, which equals POSTAGE_SATS. The route
computes postagePaidSats by matching input sats against POSTAGE_SATS
(apps/alp-dex/src/routes/settle.ts Lines 278-281). Every token UTXO in
this fixture therefore counts as postage.
The assertion at Line 417 checks >= 0n, which every bigint value
satisfies, including 0n. So the test cannot detect either the overcount
or a total of zero.
Give token UTXOs a distinct sats value, then assert the exact postage
total.
💚 Proposed fix
const tokenUtxo = (
tokenId: string,
atoms: bigint,
outIdx: number,
txPrefix: string,
- sats: bigint = 1000n,
+ sats: bigint = DEFAULT_DUST_SATS,
): ScriptUtxo => ({
assert.strictEqual(typeof settle.body.postagePaidSats, 'string');
- assert.ok(BigInt(settle.body.postagePaidSats) >= 0n);
+ // Only node-added postage stamps count toward the reported total.
+ assert.strictEqual(
+ BigInt(settle.body.postagePaidSats) % POSTAGE_SATS,
+ 0n,
+ );
+ assert.ok(BigInt(settle.body.postagePaidSats) > 0n);
DEFAULT_DUST_SATS is already imported at Line 9.
Also applies to: 416-417────────────────────────────────────────────────────────────────────────
minor [Functional Correctness] → ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:278apps/alp-dex/src/routes/settle.ts:278-281]8;; postagePaidSats counts inputs by amount, so it can include non-postage inputs. The filter keeps every input whose signData.sats equals POSTAGE_SATS. Any seller input that happens to hold exactly 1000 sats is counted as postage. The test fixture at test/settle.test.ts Line 82 creates token UTXOs with sats: 1000n, which is POSTAGE_SATS, so the reported figure already includes token inputs there. The assertion at Line 417 only checks >= 0n, so the test cannot catch the overcount. The value is reported to the taker and is planned as an audit field, per SPEC.md Line 208. Identify postage inputs by outpoint instead. Compare the inputs of builtTx against the outpoints of deserializedTx and count only the inputs the node added.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:108apps/alp-dex/src/routes/settle.ts:108-115]8;;
Validate the range of prePostageInputSats; the route forwards it to fuel
selection unchecked.
calculatedPrePostageInputSats passes straight into
postageTx.addFuelAndSign at Line 274. Three gaps exist:
- The presence check at Lines 108-115 rejects only undefined and null.
BigInt('') returns 0n and BigInt(true) returns 1n, so an empty
string or a boolean passes as a silent zero or one.
- No positivity or upper-bound check follows the conversion. A negative
value reaches the fuel calculation.
- No value is derived from the transaction, so an understated value makes
the node attach more postage stamps than the transaction needs, and the
node pays the difference.
The node cannot recompute this total from the hex alone, because
serialized inputs carry no sats. Add explicit bounds now, and record the
cross-check against the input outpoints as follow-up work for the DB/ops
slice.
🛡️ Proposed fix: bound the converted value
} catch {
throw new ValidationError(
'prePostageInputSats must be an integer string or number',
);
}
+ if (calculatedPrePostageInputSats < 0n) {
+ throw new ValidationError(
+ 'prePostageInputSats must not be negative',
+ );
+ }
Reject non-string and non-number types in the presence check so '' and
true fail loudly:
if (
- prePostageInputSats === undefined ||
- prePostageInputSats === null
+ typeof prePostageInputSats !== 'string' &&
+ typeof prePostageInputSats !== 'number'
) {
Apply the same type narrowing to atoms at Lines 121-123.
Also applies to: 212-221────────────────────────────────────────────────────────────────────────
critical [Data Integrity & Integration]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:121apps/alp-dex/src/routes/settle.ts:121-144]8;;
Cross-check the body atoms against the parsed transaction before
selecting inventory.
toTokenAtomsNeeded comes only from the request body. The route never
compares it to parsedSwap.atomsTo or to the total toToken atoms the
transaction actually pays out. It then drives inventory selection at Lines
243 and 251-253, and numUtxosNeeded decides how many seller toToken
UTXOs become inputs at Lines 266-276.
The taker controls both sides of that mismatch:
- If atoms exceeds the parsed toToken total, the server attaches more
toToken input atoms than the fixed outputs account for. The taker built
every output already, so the surplus atoms have no output to land in and
are burned from seller inventory.
- If atoms is below the parsed total, too few UTXOs are attached and the
ALP send is short, so the transaction fails validation after the server
has already signed.
The band check at Lines 201-210 does not close this hole. It constrains
parsedSwap.atomsTo against the CP expectation. It does not constrain the
separate body field used for selection.
Derive the required amount from the parsed transaction, and treat the body
value as a declaration to confirm. Sum the toToken outputs in
parsedSwap.outputs, including the optional change to slush that the
schema permits, then reject any mismatch.
🛡️ Proposed fix: derive the amount, then confirm the declared value
if (toTokenAtomsNeeded <= 0n) {
throw new ValidationError('atoms must be positive');
}
Add after validatePartiallySignedTx at Line 210:
// toToken atoms the tx actually spends: buyer receive + optional change.
const parsedToTokenAtoms = parsedSwap.outputs
.filter(output => output.tokenId === parsedSwap.toTokenId)
.reduce((sum, output) => sum + output.atoms, 0n);
if (toTokenAtomsNeeded !== parsedSwap.atomsTo) {
throw new ValidationError(
`atoms mismatch: body ${toTokenAtomsNeeded}, tx buyer output ${parsedSwap.atomsTo}`,
);
}
Then select inventory against parsedToTokenAtoms rather than
toTokenAtomsNeeded:
- if (totalToTokenAvailable < toTokenAtomsNeeded) {
+ if (totalToTokenAvailable < parsedToTokenAtoms) {
throw new Error(
- `Insufficient ${toTokenId} balance: need ${toTokenAtomsNeeded} atoms, have ${totalToTokenAvailable} atoms`,
+ `Insufficient ${toTokenId} balance: need ${parsedToTokenAtoms} atoms, have ${totalToTokenAvailable} atoms`,
);
}
const numUtxosNeeded = Math.ceil(
- Number(toTokenAtomsNeeded) / Number(atomsPerUtxo),
+ Number(parsedToTokenAtoms) / Number(atomsPerUtxo),
);
Add a test that posts a valid taker transaction with an inflated atoms
value and asserts a 400.
Also applies to: 239-269────────────────────────────────────────────────────────────────────────
critical [Stability & Availability]
→ ]8;;vscode://file//work/apps/alp-dex/src/settle/parseSwap.ts:194apps/alp-dex/src/settle/parseSwap.ts:194-212]8;;
Fix the off-by-one loop bounds; a crafted transaction reads past
tx.outputs.
All three loops run `outIdx
🐛 Proposed fix
- for (let outIdx = 1; outIdx <= tx.outputs.length; outIdx++) {
+ for (let outIdx = 1; outIdx < tx.outputs.length; outIdx++) {
const tokenId = outputTokenIdMap.get(outIdx);
if (tokenId !== undefined && fromTokenId === undefined) {
fromTokenId = tokenId;
break;
}
}
- for (let outIdx = 1; outIdx <= tx.outputs.length; outIdx++) {
+ for (let outIdx = 1; outIdx < tx.outputs.length; outIdx++) {
const tokenId = outputTokenIdMap.get(outIdx);
- for (let outIdx = 1; outIdx <= tx.outputs.length; outIdx++) {
+ for (let outIdx = 1; outIdx < tx.outputs.length; outIdx++) {
const tokenId = outputTokenIdMap.get(outIdx);
const atoms = outputAtomsMap.get(outIdx) || 0n;
Also reject the inconsistency explicitly, so an over-long sendAtomsArray
produces a 400 rather than being ignored. Add this inside the push loop at
Lines 173-184:
const atoms = alpResult.sendAtomsArray[arrayIdx];
if (atoms && atoms > 0n) {
const outIdx = arrayIdx + 1;
+ if (outIdx >= tx.outputs.length) {
+ throw new ValidationError(
+ `Invalid swap: ALP send amount at index ${arrayIdx} has no matching output`,
+ );
+ }
outputAtomsMap.set(outIdx, atoms);
Note that the surrounding catch at Line 186 swallows non-ALP push
errors. Rethrow ValidationError there so this new check is not
discarded.
Add a test that builds a transaction whose ALP sendAtomsArray is longer
than the output list, and assert a ValidationError.
Also applies to: 233-254────────────────────────────────────────────────────────────────────────
major [Stability & Availability]
→ ]8;;vscode://file//work/apps/alp-dex/index.ts:69apps/alp-dex/index.ts:69-91]8;;
Serialize maintain passes; the post-settle callback can overlap the
scheduled loop.
runMaintain is now reachable from two independent drivers:
- The scheduled loop at Lines 148-164 awaits each pass, then sleeps.
- The settle route calls the injected maintainInventory as
fire-and-forget (apps/alp-dex/src/routes/settle.ts Lines 302-311).
Nothing coordinates those two paths. A settle that completes during a
scheduled pass starts a second concurrent maintainInventory. Both passes
read seller.utxos and build reshape/postage/sweep txs from that
snapshot, so they can select the same seller UTXOs and broadcast
conflicting spends. The comment at Line 146 ("so they cannot overlap") no
longer describes the runtime behavior.
Guard both drivers with one critical section. AsyncQueue from
src/methods/queue.ts already provides FIFO serialization.
🔒 Proposed fix: run every maintain pass on one queue
+import { AsyncQueue } from './src/methods/queue';
+
const main = async (): Promise<void> => {
+ const maintainQueue = new AsyncQueue();
const runMaintain = async (): Promise<void> => {
- const inventory = await maintainInventory({
- seller,
- slush,
- feeAddress: tradedConfig.feeAddress,
- tradedTokens,
- });
- logMaintainResult('post-settle', inventory);
+ await maintainQueue.enqueue(async () => {
+ const inventory = await maintainInventory({
+ seller,
+ slush,
+ feeAddress: tradedConfig.feeAddress,
+ tradedTokens,
+ });
+ logMaintainResult('post-settle', inventory);
+ });
};
Then route the scheduled pass at Lines 149-159 through the same
maintainQueue.────────────────────────────────────────────────────────────────────────
major [Security & Privacy]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:60apps/alp-dex/src/routes/settle.ts:60-66]8;;
Do not return raw internal error text to the client.
The 500 branch puts error.message in the response body. Errors from
seller.sync(), addFuelAndSign, and broadcast() reach this branch.
Those messages can carry Chronik URLs, seller UTXO details, and inventory
sizes. Lines 243-247 and 258-264 already build messages that state exact
seller balances and UTXO counts, and those throw plain Error, so they
are returned verbatim on the 500 path.
That discloses LP inventory to any unauthenticated caller.
ValidationError messages are intended for the client and should stay.
Log the internal detail, and return a fixed string for the 500 case.
🔒 Proposed fix
if (logLabel !== undefined) {
console.error(logLabel, error);
}
- res.status(500).json({
- error:
- error instanceof Error
- ? error.message
- : 'Failed to complete swap transaction',
- });
+ res.status(500).json({ error: 'Failed to complete swap transaction' });────────────────────────────────────────────────────────────────────────
minor [Maintainability & Code Quality]
→ ]8;;vscode://file//work/apps/alp-dex/test/parseSwap.test.ts:95apps/alp-dex/test/parseSwap.test.ts:95-99]8;;
Assert literal band bounds instead of recomputing the production formula.
Lines 98-99 duplicate the expression from
apps/alp-dex/src/settle/parseSwap.ts Lines 381-382. The test therefore
compares the implementation against itself. If the floor or ceil direction
is inverted, both sides change together and the test still passes.
For expected = 10_000n and SETTLE_BAND_BPS = 100n, the bounds are
9_900n and 10_100n. Use those literals, and add one case where the
ceil matters, for example expected = 3n, whose upper bound is 4n.
💚 Proposed fix
it('accepts atomsTo at ±1% band edges', () => {
const expected = 10_000n;
- const bps = 10_000n;
- const lower = (expected * (bps - SETTLE_BAND_BPS)) / bps;
- const upper = (expected * (bps + SETTLE_BAND_BPS) + (bps - 1n)) / bps;
+ const lower = 9_900n;
+ const upper = 10_100n;
Keep the SETTLE_BAND_BPS import for an assertion that pins the constant:
assert.strictEqual(SETTLE_BAND_BPS, 100n);────────────────────────────────────────────────────────────────────────
major [Data Integrity & Integration] → ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:189apps/alp-dex/src/routes/settle.ts:189-210]8;; Read reserves and validate the band inside the queued critical section. Lines 190-195 read seller.utxos and slush.utxos before the queue. Line 225 calls seller.sync() inside the queue. So the CP band is validated against a snapshot that is both stale and outside the serialized section, while UTXO selection uses the post-sync state. Two settles that arrive together both compute expectedToAtoms from the same pre-sync reserves. The first settle then changes those reserves. The second still passes the band check that the first invalidated. The queue prevents double-spending the same seller UTXOs. It does not prevent pricing the second fill against reserves that no longer exist. SPEC.md Lines 171-173 accept that quotes can race. This case is different, because the node's own price validation runs on a snapshot the node could have refreshed. Move the pairPricingReserves call, the quoteExactIn call, and validatePartiallySignedTx into the queued task, after `await seller.sync(). Sync slush` there as well, because slush atoms count toward the reserves. Also applies to: 223-226
────────────────────────────────────────
Review complete
10 findings ✔
Critical 2
Major 4
Minor 4
11 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/constants.ts
- apps/alp-dex/src/methods/queue.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/parseSwap.ts
- apps/alp-dex/test/parseSwap.test.ts
- apps/alp-dex/test/queue.test.ts
... and 1 more file
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Address CodeRabbit review: settle queue band after sync, postage by outpoint, body/parse hardening, opaque errors, maintain queue, SPEC change-out order, literal ±1% band edge tests.
Tail of the build log:
/work /work/abc-ci-builds/ai-review Connecting to CodeRabbit... 0s elapsed Preparing review... 1s elapsed ✗ Review limit reached Limit details: You’ve used all 5 included reviews currently available under your plan. Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. You're only billed for reviews past your plan's rate limits ($0.25/file). You can wait 20 minutes for the limit to reset. https://app.coderabbit.ai/settings/billing?tab=usage&orgId=79839cd4-7849-4bd5-8d6d-5ecaf453356e Build ai-review failed with exit code 1
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) For a good time, call 1-800-COD-RABT.
────────────────────────────────────────────────────────────────────────
major [Stability & Availability]
→ ]8;;vscode://file//work/apps/alp-dex/index.ts:68apps/alp-dex/index.ts:68-86]8;;
Share one queue between maintain and settle.
maintainQueue serializes only maintenance passes. createSettleRouter
constructs its own AsyncQueue at src/routes/settle.ts line 119. A
scheduled maintain pass can therefore run while a settle is fueling,
signing, and broadcasting. Both paths select seller UTXOs and broadcast,
so they can double-spend the same seller UTXOs. That contradicts the
comment here and the SPEC statement that a process-local settle queue
prevents double-spending the same seller UTXOs.
Inject a single queue instance into createApp and pass it to
createSettleRouter.
🔒 Proposed wiring for a shared queue
- // One queue for scheduled + post-settle maintain so they never race on
- // seller UTXO selection / broadcast.
- const maintainQueue = new AsyncQueue();
+ // One queue for settle + scheduled/post-settle maintain so they never
+ // race on seller UTXO selection / broadcast.
+ const walletQueue = new AsyncQueue();
const enqueueMaintain = async (label: string): Promise<void> => {
- await maintainQueue.enqueue(async () => {
+ await walletQueue.enqueue(async () => {
const app = createApp({
seller,
slush,
feeAddress: tradedConfig.feeAddress,
tradedConfig,
tradedTokens,
+ walletQueue,
maintainInventory: () => enqueueMaintain('post-settle'),
});
Then accept walletQueue in CreateAppDeps and SettleRouteDeps, and
use it instead of the local settleQueue. Keep a default `new
AsyncQueue() in createSettleRouter` so tests that omit it still work.
Also applies to: 95-95────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:313apps/alp-dex/src/routes/settle.ts:313-326]8;;
Identify postage inputs by role, not by sats value.
The filter counts every node-added input whose signData.sats equals
POSTAGE_SATS. Token inventory UTXOs are node-added too. If an inventory
UTXO holds exactly POSTAGE_SATS, the reported postagePaidSats is too
high. Derive the value from the postage stamps the node actually attached,
or exclude inputs that carry a token.
🐛 Proposed filter fix
.filter(
input =>
+ input.signData?.tokenId === undefined &&
(input.signData?.sats ?? 0n) ===
POSTAGE_SATS,
)
Confirm the field name on signData for token-carrying inputs in the
installed ecash-lib version before applying.
Also applies to: 347-362────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:159apps/alp-dex/src/routes/settle.ts:159-163]8;; Bound node-funded postage per settle. addFuelAndSign trusts prePostageInputSats and funds the difference between total output sats and the reported inputs. The validator does not constrain output sats, so a taker can inflate a buyer-controlled output and consume the seller wallet’s postage UTXOs. Validate output sats against the protocol-required budget, and cap the number of postage stamps per settle before calling addFuelAndSign.
────────────────────────────────────────
Review complete
3 findings ✔
Major 2
Minor 1
11 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/constants.ts
- apps/alp-dex/src/methods/queue.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/parseSwap.ts
- apps/alp-dex/test/parseSwap.test.ts
- apps/alp-dex/test/queue.test.ts
... and 1 more file
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Share settle/maintain wallet queue; count postage by inventory outpoint role; require token mid-outs to be dust (blocks postage drain via inflated sats).
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) e/acc/def/det: Effective accelerationism of defect detection.
────────────────────────────────────────────────────────────────────────
major [Data Integrity & Integration]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:282apps/alp-dex/src/routes/settle.ts:282-309]8;;
Reject toToken totals that are not a whole multiple of the inventory
size.
numUtxosNeeded rounds up. The node then attaches `numUtxosNeeded *
atomsPerUtxo atoms of toToken`. The tx outputs consume only
parsedToTokenAtoms, and the ALP section is fixed by the taker, so the
node cannot add change. If parsedToTokenAtoms is not an exact multiple
of atomsPerUtxo, the surplus LP atoms are burned, or the broadcast fails
after the LP already selected and signed inputs. Validate the multiple
before selection and return 400.
Math.ceil(Number(...)) also loses precision for atom counts above 2^53.
Use bigint division.
🐛 Proposed fix
const toToken = tradedTokens.get(toTokenId)!;
const atomsPerUtxo = toToken.utxoAtoms;
- const numUtxosNeeded = Math.ceil(
- Number(parsedToTokenAtoms) / Number(atomsPerUtxo),
- );
+ if (parsedToTokenAtoms % atomsPerUtxo !== 0n) {
+ throw new ValidationError(
+ `toToken outputs must total a multiple of ` +
+ `${atomsPerUtxo} atoms (inventory size)`,
+ );
+ }
+ const numUtxosNeeded = Number(
+ parsedToTokenAtoms / atomsPerUtxo,
+ );────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/settle/parseSwap.ts:170apps/alp-dex/src/settle/parseSwap.ts:170-203]8;; Reject overlapping ALP output assignments If a non-zero ALP amount maps to an output already colored by an earlier section, reject the swap. ALP coloring keeps the earlier section and discards the overlapping section. The current Map.set calls instead keep the later amount.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:165apps/alp-dex/src/routes/settle.ts:165-169]8;; Derive prePostageInputSats from the taker inputs. PostageTx.addFuelAndSign trusts this value. If it is understated, the method adds extra fuel UTXOs until the transaction covers its outputs and fee. The excess becomes miner fee paid by the LP. Derive the input sum from Chronik prevouts, or enforce a strict fuel limit and reject excess requirements.
────────────────────────────────────────
Review complete
3 findings ✔
Major 3
11 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/constants.ts
- apps/alp-dex/src/methods/queue.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/parseSwap.ts
- apps/alp-dex/test/parseSwap.test.ts
- apps/alp-dex/test/queue.test.ts
... and 1 more file
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Require toToken outs to be an exact inventory multiple (bigint, no Math.ceil); reject overlapping ALP output coloring.
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Every great developer you know got there by solving problems they were unqualified to solve until they actually did it. - Patrick McKenzie
────────────────────────────────────────────────────────────────────────
major [Security & Privacy]
→ ]8;;vscode://file//work/apps/alp-dex/src/settle/parseSwap.ts:276apps/alp-dex/src/settle/parseSwap.ts:276-297]8;;
Colored outputs of a third token before the buyer output escape
validation.
The classification loop handles only fromTokenId and toTokenId. It has
no else branch. The trailing loop at Line 372 starts at
atomsTokenBoughtToBuyerIdx + 1. So any output colored with a third
tokenId that sits before the buyer output is never pushed into
parsedSwap.outputs.
validatePartiallySignedTx only inspects parsedSwap.outputs. Its count
bounds, reserved-script checks, and change-pattern rules therefore never
see that output. With a multi-pair config.json the seller wallet holds
other traded tokens, so a taker can add an extra ALP SEND section for one
of those tokens and the node co-signs and broadcasts a transaction the
validator never examined.
Reject any colored output that is not fromTokenId or toTokenId during
parse.
🛡️ Proposed fix
for (let outIdx = 1; outIdx < tx.outputs.length; outIdx++) {
const tokenId = outputTokenIdMap.get(outIdx);
const atoms = outputAtomsMap.get(outIdx) || 0n;
+ if (
+ tokenId !== undefined &&
+ atoms > 0n &&
+ tokenId !== fromTokenId &&
+ tokenId !== toTokenId
+ ) {
+ throw new ValidationError(
+ `Invalid swap: output ${outIdx} carries unexpected token ${tokenId}`,
+ );
+ }
+
if (tokenId === fromTokenId && atoms > 0n) {────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:325apps/alp-dex/src/routes/settle.ts:325-330]8;; Reject unverified prePostageInputSats and seller-owned inputs PostageTx.addFuelAndSign calculates fuel from total output sats minus prePostageInputSats and consumes seller-wallet fuel without a change output. An understated value can therefore overfund the transaction with LP postage. Inside settleQueue.enqueue, resolve every deserializedTx.inputs prevout through Chronik. Require their satoshi sum to equal calculatedPrePostageInputSats. Reject any taker input owned by seller or slush before signing or broadcasting. Output dust checks do not enforce these invariants.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/settle/parseSwap.ts:170apps/alp-dex/src/settle/parseSwap.ts:170-208]8;; Reject non-SEND ALP sections. In ecash-lib 4.13.0, parseAlp returns AlpGenesis, AlpMint, and AlpBurn with txType values GENESIS, MINT, and BURN; none has sendAtomsArray. It can also return UNKNOWN for unknown token types. Reject every ALP result unless `txType === 'SEND' and tokenId matches fromTokenId or toTokenId`. Otherwise, the node can co-sign a transaction that burns seller inventory.
────────────────────────────────────────
Review complete
3 findings ✔
Major 3
11 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/constants.ts
- apps/alp-dex/src/methods/queue.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/parseSwap.ts
- apps/alp-dex/test/parseSwap.test.ts
- apps/alp-dex/test/queue.test.ts
... and 1 more file
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) I'm the Doctor. Well, a doctor of code, and I'm here to fix the timeline of your project.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:165apps/alp-dex/src/routes/settle.ts:165-169]8;; Validate prePostageInputSats against the taker inputs. The node takes prePostageInputSats from the request body and forwards it to addFuelAndSign as the sats already covered by taker inputs. Nothing cross-checks it against the real prevout values of deserializedTx.inputs. A taker who understates the value makes the node attach extra postage stamps, which the taker pays nothing for. The dust rules in parsePartiallySignedSwap limit where those sats can land, but they do not bound the fuel the node adds. Resolve the taker prevouts through Chronik inside the queued section and require the body value to match the sum, or derive the value entirely from Chronik and treat the body field as advisory. Also applies to: 325-330
────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/settle/parseSwap.ts:228apps/alp-dex/src/settle/parseSwap.ts:228-243]8;; Reject zero-sat non-token outputs or bound their count. Zero-sat non-token outputs bypass the 2–6 output limit because they are not added to parsedSwap.outputs. A taker can add arbitrary outputs and increase the LP’s transaction size and miner fee. Reject these outputs, as required by SPEC.md, or include them in the output-count limit.
────────────────────────────────────────
Review complete
2 findings ✔
Major 2
11 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/constants.ts
- apps/alp-dex/src/methods/queue.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/parseSwap.ts
- apps/alp-dex/test/parseSwap.test.ts
- apps/alp-dex/test/queue.test.ts
... and 1 more file
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Latest CodeRabbit can be ignored
- We do not have to worry about multiple 0-sat outputs. The node will fail to broadcast such txs unless there is some incredibly crazy OP_RETURN multi stuff going on
- Chronik checks for stats values on user inputs is also overkill. Worst case, we are adding a few extra stamps vs what needed to be added.