Our first escrow model was simple: one deal, one hold invoice, one payout at the end. That is fine for a small website. It is terrible for a six-week renovation, a multi-stage design contract, or any job where the client wants to review progress before the next chunk of money moves.
We needed milestones. But adding milestones to an escrow system is not just adding a table. It creates two state machines, one for the deal and one for each milestone, and they can disagree. It also creates a money path that can be entered from more than one button in the UI. That is exactly where bugs that cost real money live.
Ganji is a freelance platform built around Bitcoin Lightning escrow. In this post I'll walk through the milestone design we landed on, the mistakes we closed off, and the invariants we now treat as non-negotiable.
A Quick Primer: Hold Invoices
Escrow on Lightning is built on hold invoices. When a client pays one, the payment is accepted but locked in transit (as an HTLC) rather than completed. The receiving side then either settles it by revealing the secret preimage, which we call R, or cancels it, which returns the funds to the payer. Nothing is final until one of those two things happens.
That gives us a real escrow primitive: the client's money is committed but not yet the freelancer's. Everything below is about deciding, safely, which of the two happens.
The Options We Rejected
There were three plausible models.
One job as many deals. Easy to build with existing code, but the UX and admin surface get heavier, and the coherence of a single job is lost. Every exit and dispute becomes N separate stories.
One big hold with internal accounting. Keep a single invoice and subtract amounts from a balance as milestones complete. This doesn't fit using the Lightning network itself as the escrow: a hold invoice settles or cancels as a whole and doesn't support partial capture the way a card authorization does. We would be maintaining a fake ledger on top of a real HTLC, and the fake ledger would be where the money bugs go.
Sequential per-milestone holds. Each milestone is its own escrow leg with its own hold invoice, preimage, and payout tracking. More invoices, but the network truth and the business truth line up. This is the one we shipped.
The sequence is strict: fund M1, submit, release and pay M1, then create and fund M2, and so on. There is no upfront deal-level hold in milestone mode, and no milestone can be paid before its own hold exists. The deal row mirrors the active milestone's invoice and status for compatibility, and the deal itself is only released when the final milestone is released.
Vocabulary Is a Money Control
The most important thing we did was make "paid" mean one thing, everywhere.
| Status | What it actually means |
|---|---|
funded / in_progress
|
Hold accepted on the escrow node; work may start |
work_submitted |
Deliverable uploaded, client can review |
completed |
Approved, payout pending, not paid |
released |
Hold settled and freelancer paid; terminal |
rejected / disputed
|
Under independent review; hold stays frozen |
refunded |
Hold cancelled or expired; sats returned to the client |
If completed and released both render as a green checkmark, someone will eventually pay twice or tell a freelancer they have money they don't have. We updated API views and UI labels to say released = paid and completed = payout pending. That is a small copy change with a large blast radius.
We also enforce the state machine in two places. ValidMilestoneTransitions in Go defines which transitions are legal, and awaiting_payment → released is deliberately not among them. A CHECK constraint in Postgres restricts the column to the set of known statuses, so if you add a status constant in Go and forget the database, Postgres will be the one to remind you. The two layers do different jobs: the Go map guards the transitions, and the constraint guards the values.
One Door Into released
Early on, approve, accept-next, and operator resolution each had their own idea of how to mark a milestone paid. That is how you get bypasses: a UI path that flips a status without settling a hold.
We made a single canonical function, ReleaseMilestone, and routed every money-moving path through it, via a small gate in front of it. The gate is deliberately blunt:
func (s *Service) releaseMilestoneViaCanonicalPath(ctx context.Context, deal *Deal, m *Milestone) (*Milestone, error) {
if m.Status == MilestoneReleased {
return m, nil
}
if m.PreimageHash == "" && m.CheckingID == "" {
return nil, fmt.Errorf("%w: milestone %d has no escrow hold (fund it first)", ErrInvalidInput, m.Order)
}
return s.ReleaseMilestone(ctx, deal, m.ID)
}
"No escrow hold (fund it first)" is not a soft warning. A milestone with no hold can never be marked released, and the sequence cannot advance as paid. We hardened this in separate commits after realizing how many code paths could otherwise reach the status field. Direct UpdateMilestoneStatus calls now refuse to write released or refunded. Only the canonical payout path or an explicit operator resolution can write them.
A related rule: the generic freelancer status PATCH cannot set locked, released, disputed, or refunded on a deal either. Money states belong to the backend, not to a form field.
The Three-Phase Payout
Releasing a milestone means two network legs: reveal the preimage to settle its hold, then pay the freelancer's invoice. Those calls can hang, fail, or succeed after the response is lost. A single database transaction across them is not an option.
ReleaseMilestone follows the same shape as our deal-level release, with three phases.
Phase 1: durable intent. Re-read the milestone under a row lock. If a previous payout exists, check it. A confirmed payment means finalize without paying again. A confirmed failure means clear the tracking and retry. An ambiguous result means stop. If no attempt exists, commit payout_attempted_at before any money moves, so a crash after this commit leaves a visible marker.
Phase 2: network. Settle the milestone hold and pay the freelancer, with no lock and no open transaction. If the payout is provably refused (a 4xx), clear the marker so a retry is legal. If it times out or returns a 5xx, keep the marker and return ErrPayoutInFlight. We do not guess.
Phase 3: finalize. Re-lock, re-validate the transition, and only then write released. If the milestone became disputed while the network legs were running, for example because a client rejected during a slow payout, we abort the status write instead of silently overriding the freeze. The money may already have moved. The database simply refuses to claim the client approved it.
That last guard is uncomfortable but correct. It mirrors the deal-level path and came out of the same class of race: user intent changed while an external call was in flight.
Rejection Is a Freeze, Not a Refund
This is the rule that makes milestone work reviewable. If a client rejects after work is submitted, we do not reveal R, we do not settle, cancel, or fail the HTLC, and we do not auto-refund. The milestone moves to disputed and the hold stays exactly where it is.
Why so strict? Because "reject" must not be a cheap way to get the deliverable and then claw back the money. Independent review decides the outcome:
- An operator's release resolution calls the canonical payout path, reveals
R, pays the freelancer, advances the sequence, and funds the next milestone. - An operator's refund resolution cancels the hold using the
payment_hash, with noR, marks the milestonerefunded, and does not auto-fund the next milestone. Cancellation is idempotent: a hold that is already expired or cancelled counts as success. A hold that is still committed and cannot be cancelled leaves the milestonedisputed.
One constraint comes with freezing a hold: it can't be frozen forever. A hold invoice and the HTLC behind it have a deadline, and if the hold expires before the review finishes, the funds return to the client. Review has to resolve inside that window.
Exit is symmetric for freelancers and clients. Before submission, an exit cancels the open hold and refunds the client, and pays nobody. After submission, an exit moves no money, and the milestone goes to review. Participants cannot use the exit button to bypass arbitration.
Evidence Is Part of the State Machine
Milestone mode requires at least one artifact on the deal before work can be submitted. That sounds bureaucratic until you remember that the entire point of a milestone is reviewable progress. A payment checkpoint with no evidence is just a timer.
Artifacts can be tagged with milestone_id (nullable, so old deals keep working) and listed per milestone. The first pass still gates submission on a deal-level artifact, with per-milestone tagging wired through the database, model, repository, and service layers. Tagging at upload time in the frontend is a follow-up. We try to be explicit about which parts are done instead of letting the docs imply a perfect system.
How We Kept Ourselves Honest
We wrote 23 tests around the milestone release and resolution paths, covering:
- double-call idempotency
- confirmed, failed, and ambiguous payouts
- the crash window where only
payout_attempted_atexists - cancellation races
- milestones with no escrow
- already-settled holds
- disputes raised during release
- reject and exit money rules
- transition validation
These are not "does the function return" tests. They encode the money rules as executable claims.
The hardening came as a series of commits: routing payouts through the canonical path, requiring escrow to release, adding phase-3 revalidation and cancel idempotency, then clarifying the UI vocabulary. Each one closed a specific way for the two state machines to disagree.
What Is Still Imperfect
Deal-level and milestone-level disputes are mirrored for compatibility, not fully unified. The hold-expiry sweep reconciles deal-level holds (which mirror M1 in milestone mode), while later per-milestone holds currently rely on public views and poll paths for refresh. Rework-after-reject policy and deeper coherence between deal and milestone disputes are still open items in our tracker.
We can live with those as known, written-down boundaries. What we cannot live with is an ambiguous answer to "did this milestone pay?" Every path that can answer yes has to go through the same function, with the same durable markers, and the same rule that an accepted hold is the only thing that makes money real.
The Takeaway
When money is involved, a status field is not a label. It is a claim about the outside world. Design the state machine so the claim can only be made after the world has cooperated, give every irreversible action exactly one canonical entry point, and make ambiguous failures stop the line instead of moving it forward.
That is less glamorous than adding a new route. It is also the difference between a demo and an escrow system.
Top comments (0)