Payment channels
A payment channel lets a client pay a server many small amounts while only two transactions reach the chain: the funding and the settlement. This page shows how to configure channels, carry their messages, open and accept one, pay, close it, and recover the client’s funds when the server does not settle.
How a channel works
Section titled “How a channel works”The client locks funds in a 2-of-2 output shared with the server. Before it broadcasts that funding, it holds a refund the server has signed, which returns everything to the client once the channel’s lock time passes.
Each payment is a new transaction spending the funding output, signed by the client and paying the server a larger share. The server checks what it pays, its fee and the client’s signature, and keeps its own signature to itself: only the server ever holds a fully signed payment, so the client cannot broadcast an older state.
The server settles by broadcasting its latest payment. It does this when either side closes the channel, and on its own when the settlement margin before the lock time begins.
Configure the node
Section titled “Configure the node”A node that takes part in channels needs a peer id on your transport and a ChannelTiming. There is no
default timing: without one, the node requests, accepts and pays no channels.
await libspiffy.initialize( dataDirectory: './wallet-data', arcConfig: arcConfig, channelPeerId: myPeerId, // how your transport names this node channelTiming: ChannelTiming( settlementMargin: const Duration(hours: 1), minimumLifetime: const Duration(days: 1), ),);ChannelTiming (lib/src/models/channel_timing.dart):
| Field | Default | Meaning |
|---|---|---|
settlementMargin |
required | Within this time of the lock time, no payment is made or acknowledged, and the server settles. It must be positive. |
minimumLifetime |
required | A channel is requested or accepted only with at least this long to run. It must be longer than the margin. |
resendAfter |
2 seconds | How long the client waits for the server to answer a message before it sends it again. Each wait is twice the last. |
resendAtMost |
30 seconds | The longest wait between resends. It must be at least resendAfter. |
confirmWithin |
20 seconds | How long a payment may go unacknowledged before its request fails. It must be positive. |
The margin must cover the broadcast, clock skew between the parties, and that the network judges a time lock against the median time of the last eleven blocks, not the clock. A server accepts only a lock time that is a time, not a block height. A client should ask for comfortably more than its server’s minimum, because the server measures the remaining time when it accepts.
Carry the peer messages
Section titled “Carry the peer messages”libspiffy owns no transport. The channel protocol speaks through coordinator messages:
- Outgoing: the coordinator emits a
P2PMessageToSendEvent(toPeerId,messageType,payload). Send it to that peer. - Incoming: wrap what arrives in a
P2PMessageReceived(fromPeerId,messageType,payload) and tell it to the coordinator. - A send that failed: tell the coordinator a
P2PSendFailed(toPeerId,messageType,payload, optionalerror). The client then sends the message again sooner than it would otherwise.
// A sketch: `transport` is your own messaging layer.libspiffy.coordinator.on<P2PMessageToSendEvent>().listen((m) async { try { await transport.send(m.toPeerId, m.messageType, jsonEncode(m.payload)); } catch (e) { libspiffy.coordinator.tell(P2PSendFailed( toPeerId: m.toPeerId, messageType: m.messageType, payload: m.payload, error: '$e', )); }});
transport.onMessage((fromPeerId, messageType, body) { libspiffy.coordinator.tell(P2PMessageReceived( fromPeerId: fromPeerId, messageType: messageType, payload: (jsonDecode(body) as Map).cast<String, dynamic>(), ));});P2PMessageToSendEvent also carries the merkle-proof recovery messages (proof_request,
proof_response), which are not channel messages. Deliver messages in the order they were sent.
fromPeerId must name the sender the same way channelPeerId names it on its own node: a message about a
channel is accepted only from that channel’s counterparty, in that counterparty’s role.
The channel message types are channel_request, channel_accept, channel_reject,
refund_sign_request, refund_signed, channel_open, channel_opened, payment_update, payment_ack,
channel_close, channel_closed and channel_error. Treat the payloads as opaque.
Resends
Section titled “Resends”A message can be lost when a phone’s connection changes, so the client sends again what its server has not answered:
channel_openuntil the server’schannel_opened;- its latest
payment_updateuntil apayment_ackcovers it; - its
channel_closeuntil the server’schannel_closed.
The first resend waits resendAfter, and each wait is twice the last, up to resendAtMost. A
P2PSendFailed brings one resend forward per wait; the resends after it back off as usual. Without
P2PSendFailed the resends still come. A channel that closes, is rejected, expires or has its refund claimed
sends nothing more.
A peer that cannot be reached
Section titled “A peer that cannot be reached”When the waits have reached resendAtMost and the last send failed, the client stops resending and keeps the
messages. The coordinator emits ChannelPeerAwayEvent (walletId, channelId, peerId). Watch for that
peer on your transport, and when it is back, tell the coordinator ChannelPeerReachable(peerId:): every
message kept for it goes again at once, the waits starting over. Any channel message from that peer does the
same.
// A sketch: `presence` is your transport's way to see a peer come online.libspiffy.coordinator.on<ChannelPeerAwayEvent>().listen((away) { presence.whenOnline(away.peerId, () { libspiffy.coordinator.tell(ChannelPeerReachable(peerId: away.peerId)); });});A peer that never comes back leaves the channel to its lock time and the client’s refund.
Ask for each step
Section titled “Ask for each step”Every channel command is a CoordinatorRequest: coordinator.ask sends it and completes with its own reply
(see Waiting for an answer). A step that fails, including
the server’s channel_reject or channel_error during an open, arrives as an ErrorEvent naming the
request, and ask throws CoordinatorFailure.
| Request | Reply | Default timeout |
|---|---|---|
OpenChannelCommand |
ChannelOpenedEvent |
5 minutes |
AcceptChannelCommand |
ChannelAcceptedEvent |
1 minute |
RejectChannelCommand |
ChannelRejectedEvent |
1 minute |
ChannelPayCommand |
ChannelPaymentEvent |
1 minute |
CloseChannelCommand |
ChannelClosedEvent |
5 minutes |
ClaimChannelRefundCommand |
ChannelRefundClaimedEvent |
3 minutes |
ExpireChannelCommand |
ChannelExpiredEvent |
3 minutes |
RetryChannelFundingCommand |
ChannelFundingRetriedEvent |
3 minutes |
ResendChannelOpenCommand |
ChannelOpenResentEvent |
1 minute |
The open and the close wait on the counterparty over your transport, so their timeout is longer. A timeout does not cancel the step. Requests of one kind for one channel are answered in the order you made them.
Some failures are not final. When CoordinatorFailure.stillSent (from ErrorEvent.stillSent) is true, the
client is still sending what failed: a payment the server has not acknowledged in time, a channel_open
the server refused, or a channel_open the server answered but the client failed to record. If it lands
later, an event that answers no request says so: a ChannelPaymentEvent or a ChannelOpenedEvent with a
null requestId. Any other failure is final.
The other side’s events are not replies to anything it asked: the server hears the channel open, each
payment and the client’s close. Follow those with coordinator.on<E>(). Their requestId is null.
Open a channel (client)
Section titled “Open a channel (client)”final channel = await alice.coordinator.ask(OpenChannelCommand( walletId: 'alice-wallet', serverPeerId: bobPeerId, fundingAmountSats: 100000, lockTimeDurationSeconds: 7 * 24 * 3600, counterpartyMarker: 'bob', // optional; defaults to the server's peer id));final channelId = channel.channelId; // use it from now onThe client sends channel_request, gets the refund signed, then broadcasts the funding transaction with its
unconfirmed ancestors. Change of 1 sat or more comes back to the wallet. Once ARC takes the funding, the
client sends channel_open with a BEEF of the funding, and resends it until the server answers.
The server SPV-validates the funding, submits it to ARC, and opens the channel once ARC reports the network
holds it (SEEN_ON_NETWORK or MINED). It emits its own ChannelOpenedEvent and sends channel_opened,
for a repeated channel_open too. Each channel_open has the server look at the network again, so a
funding the network takes late still opens the channel.
The client opens only when channel_opened arrives: ask returns its ChannelOpenedEvent (walletId,
requestId, channelId, fundingTxId, fundingAmountSats). No payment can be made before.
What can go wrong:
- The server refuses the open with
channel_error.askthrows aCoordinatorFailurewith its reason andstillSenttrue:channel_openis still resent, and if the server opens later, aChannelOpenedEventwith a nullrequestIdsays so. - The settlement margin begins before the server opens.
channel_openis sent no more, and anErrorEventsays so. The refund returns the funding after the lock time. - The funding can never be mined. When the wallet fails the funding payment (ARC rejects it, or one
of its inputs is proven spent),
channel_openis sent no more, the open fails withstillSentfalse, and the channel can no longer open. The wallet releases the funding’s inputs as for any failed deferred payment.
Accept or reject (server)
Section titled “Accept or reject (server)”The server’s app hears ChannelRequestReceivedEvent and decides:
bob.coordinator.on<ChannelRequestReceivedEvent>().listen((r) async { try { if (!wantsChannel(r)) { await bob.coordinator.ask(RejectChannelCommand(channelId: r.channelId, reason: 'not now')); return; } await bob.coordinator.ask(AcceptChannelCommand( channelId: r.channelId, walletId: 'bob-wallet', clientPeerId: r.clientPeerId, clientPubKey: r.clientPubKey, clientAddress: r.clientAddress, fundingAmountSats: r.fundingAmountSats, lockTimeUnix: r.lockTimeUnix, )); } on CoordinatorFailure catch (failure) { print('Channel ${r.channelId}: ${failure.message}'); }});
bob.coordinator.on<ChannelOpenedEvent>(walletId: 'bob-wallet').listen((o) { print('Channel ${o.channelId} open, funded by ${o.fundingTxId}');});wantsChannel is your own policy. ChannelAcceptedEvent means the acceptance is journaled and
channel_accept handed to your transport; the channel opens when the client funds it.
ChannelRejectedEvent.clientTold says whether a request from that client was held and the client told.
try { final paid = await alice.coordinator.ask(ChannelPayCommand( channelId: channelId, walletId: 'alice-wallet', amountSats: 1000, purpose: 'coffee', // optional )); print('payment ${paid.sequence}: client ${paid.clientBalance}, server ${paid.serverBalance}');} on CoordinatorFailure catch (failure) { if (failure.stillSent) { print('not acknowledged yet; still sent, and goes with the close'); } else { print('refused: ${failure.message}'); }}The client records the payment, signs it and sends payment_update. It emits ChannelPaymentPendingEvent
(channelId, amountSats, sequence, clientBalance, serverBalance) to say the payment is signed and on
its way. ask returns the payment’s ChannelPaymentEvent (the same fields) when the server acknowledges it
with payment_ack. sequence counts payments from 1.
- No acknowledgement within
confirmWithin:askthrows withstillSenttrue. The payment is not withdrawn: the client signed it, and the server may hold it with only its acknowledgement lost. It is still resent and goes with the close. If its acknowledgement comes later, aChannelPaymentEventwith a nullrequestIdsays so. - Refused: a payment the channel refuses, such as one above the client’s balance, throws. So does one
the server refuses with
channel_error; it is not resent.
The server emits ChannelPaymentEvent when it checks and acknowledges a payment:
bob.coordinator.on<ChannelPaymentEvent>().where((p) => p.channelId == channelId).listen((p) { print('received payment ${p.sequence}: ${p.amountSats} sats');});Every payment carries the channel’s balances, so one that follows a lost payment pays that one too. The server takes any payment later than its latest, and acknowledges a repeat again at its latest, journaling nothing.
Each party’s share is paid as long as it is at least PaymentChannelBuilder.minimumOutputSats (1 sat);
only a share of nothing is left out. BSV has no dust limit. The server refuses a payment whose output to the
server does not carry its whole balance.
Close and settle
Section titled “Close and settle”Either side can close:
final closed = await alice.coordinator.ask(CloseChannelCommand(channelId: channelId, reason: 'checkout'));print('settled in ${closed.settlementTxId}: ' 'client ${closed.finalClientBalance}, server ${closed.finalServerBalance}');The client’s channel_close carries its latest payment, which the server takes before it settles, so a
lost payment_update is still paid. The client resends its close until channel_closed arrives. A client
that has paid nothing first records a payment of nothing and sends it with the close, so the server can
settle and pay the client back; a server that is already closing takes that payment too.
The server broadcasts its latest payment as the settlement and hands it to the client in channel_closed.
A close of a channel the server already closed is answered with the same settlement again. The client checks
the settlement and records its share. It takes a settlement from an earlier payment it signed, as long as it
pays the server no more than the client’s latest payment did: a server that never received the latest
payment settles with the one before.
Both sides emit ChannelClosedEvent (channelId, reason, settlementTxId, and finalClientBalance and
finalServerBalance, what the settlement pays each side); the side that asked gets it as its reply. On the
client, each payment still unacknowledged is then answered: as paid if the settlement pays it, as failed if it
does not. If nobody closes, the server settles by itself when the settlement margin begins. That close
answers no request: follow it with on<ChannelClosedEvent>().
A settlement ARC does not take leaves the channel closing. The failure is an ErrorEvent: it names your
close request, so ask throws CoordinatorFailure, and a failure no request caused (the settlement timer’s)
carries no requestId. Closing again retries it, and so does a restart.
The settlement goes to ARC with a BEEF of the funding transaction and the spend.
After a restart
Section titled “After a restart”Channels pick up where they were from their journal. When the coordinator starts:
- a client channel that was closing sends its close again, until
channel_closed; - a client channel whose funding was sent sends
channel_openagain, untilchannel_opened; - a server arms the settlement of each channel it serves that is open, and settles one left closing.
Events the projections apply again at start are not acted on twice: no channel message of the past is sent again, and the app is not told again of a channel opened or closed. See Recovery after a restart.
Recover the funds when the server does not settle (client)
Section titled “Recover the funds when the server does not settle (client)”Claim the refund
Section titled “Claim the refund”final claimed = await alice.coordinator.ask(ClaimChannelRefundCommand(channelId: channelId));print('refund ${claimed.refundTxId} broadcast');ChannelRefundClaimedEvent carries channelId, refundTxId, success and error; a claim that fails
throws.
The library broadcasts the fully signed refund the client holds, journals the claim and records the refund’s
output in the wallet as an unproven receive. Pass refundTxHex only to name a specific refund; it must spend
the channel’s funding output.
Claim it only once the chain’s median time past, read from your block headers, is after the lock time. The network judges the lock time against that, not the clock, and on mainnet it trails the clock by about an hour. Until then, nodes treat the refund as non-final and drop it for any final spend of the funding, such as the server’s settlement. A refund rejected as a double spend is final: nothing is journaled as claimed, and it is never retried at a higher fee.
The refund, like the settlement, goes to ARC with a BEEF of the funding transaction.
Record an expiry
Section titled “Record an expiry”await alice.coordinator.ask(ExpireChannelCommand( channelId: channelId, observedBy: 'client', // or 'server' settlementOrRefundTxId: txid, // optional: the transaction you saw end it));libspiffy does not watch lock times for you. Your app sends ExpireChannelCommand when it sees a channel
past its lock time. It journals the expiry and records the transaction that ended the channel and pays this
side (the client’s refund, or the server’s settlement) in the wallet, without broadcasting anything. It
converges with ClaimChannelRefundCommand: whichever runs first records the refund, and the other records
nothing new. The reply is ChannelExpiredEvent; an expiry that cannot be recorded is a reply with
success: false, and ask throws.
Repair an open that did not finish (client)
Section titled “Repair an open that did not finish (client)”At startup the coordinator emits UnfinishedChannelsFoundEvent (follow it with
on<UnfinishedChannelsFoundEvent>()) (walletId, channels) for each wallet
with channels that started opening and never reached open. Each UnfinishedChannel has channelId,
state (opening or funding), counterpartyPeerId, fundingAmountSats and lockTimeUnix. The event
reports; a channel whose funding was sent already resends its channel_open by itself. Your options:
| Situation | Command | Answer |
|---|---|---|
| The funding broadcast failed: ARC never took it | RetryChannelFundingCommand(channelId:) |
ChannelFundingRetriedEvent |
The funding was sent and you want channel_open sent again now |
ResendChannelOpenCommand(channelId:) |
ChannelOpenResentEvent |
| You want the funding inputs back | CancelDeferredPaymentCommand on the funding txid |
DeferredPaymentCancelledEvent |
A retry re-broadcasts the same funding transaction read from the channel’s journal; its inputs stay reserved
until ARC accepts it, so it cannot double-spend them. It refuses a channel whose funding was already sent. A
resend journals nothing; channel_open then goes again until channel_opened. It refuses a channel whose
funding can never be mined. Neither sends the counterparty a channel_error. See
Deferred payments for cancelling.
What counts as on the network
Section titled “What counts as on the network”A channel transaction the library submits (the server’s funding submission, the settlement, the refund)
counts as held only when ARC reports SEEN_ON_NETWORK or MINED. A double spend or an orphan fails the
step and nothing is recorded; repeating the step retries it. When ARC answers while still processing, the
library asks again until it gives a verdict.