@johnhenry/browsermesh-apps 0.0.0 → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/payments.mjs +536 -16
package/package.json
CHANGED
package/src/payments.mjs
CHANGED
|
@@ -53,6 +53,67 @@ function generateEscrowId() {
|
|
|
53
53
|
return `esc_${Date.now().toString(36)}_${(++_escrowSeq).toString(36)}`;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
// ---------------------------------------------------------------------------
|
|
57
|
+
// Signature helpers
|
|
58
|
+
// ---------------------------------------------------------------------------
|
|
59
|
+
//
|
|
60
|
+
// PaymentChannel accepts an injected signFn/verifyFn pair rather than
|
|
61
|
+
// hardcoding a crypto mechanism, so callers can wire a real
|
|
62
|
+
// MeshIdentityManager (see @johnhenry/browsermesh-core's identity.mjs)
|
|
63
|
+
// in without this published, general-purpose package taking a hard
|
|
64
|
+
// dependency on it. Shape matches peer-chat.mjs's convention:
|
|
65
|
+
// signFn: async (data: Uint8Array) => Uint8Array
|
|
66
|
+
// verifyFn: async (pubKey: Uint8Array, data: Uint8Array, sig: Uint8Array) => boolean
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Encode a Uint8Array to a base64 string.
|
|
70
|
+
* Falls back to manual encoding when btoa is unavailable (Node tests).
|
|
71
|
+
*
|
|
72
|
+
* @param {Uint8Array} bytes
|
|
73
|
+
* @returns {string}
|
|
74
|
+
*/
|
|
75
|
+
function bytesToBase64(bytes) {
|
|
76
|
+
if (typeof btoa === 'function') {
|
|
77
|
+
let binary = '';
|
|
78
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
79
|
+
return btoa(binary);
|
|
80
|
+
}
|
|
81
|
+
if (typeof Buffer !== 'undefined') {
|
|
82
|
+
return Buffer.from(bytes).toString('base64');
|
|
83
|
+
}
|
|
84
|
+
throw new Error('No base64 encoder available');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Decode a base64 string to a Uint8Array.
|
|
89
|
+
*
|
|
90
|
+
* @param {string} b64
|
|
91
|
+
* @returns {Uint8Array}
|
|
92
|
+
*/
|
|
93
|
+
function base64ToBytes(b64) {
|
|
94
|
+
if (typeof atob === 'function') {
|
|
95
|
+
const binary = atob(b64);
|
|
96
|
+
const bytes = new Uint8Array(binary.length);
|
|
97
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
98
|
+
return bytes;
|
|
99
|
+
}
|
|
100
|
+
if (typeof Buffer !== 'undefined') {
|
|
101
|
+
return new Uint8Array(Buffer.from(b64, 'base64'));
|
|
102
|
+
}
|
|
103
|
+
throw new Error('No base64 decoder available');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Canonical bytes for a plain fields object, used as the signing/verification
|
|
108
|
+
* payload for both PaymentUpdate and close claims/acks.
|
|
109
|
+
*
|
|
110
|
+
* @param {object} fields
|
|
111
|
+
* @returns {Uint8Array}
|
|
112
|
+
*/
|
|
113
|
+
function canonicalBytes(fields) {
|
|
114
|
+
return new TextEncoder().encode(JSON.stringify(fields));
|
|
115
|
+
}
|
|
116
|
+
|
|
56
117
|
// ---------------------------------------------------------------------------
|
|
57
118
|
// LedgerEntry typedef
|
|
58
119
|
// ---------------------------------------------------------------------------
|
|
@@ -258,6 +319,52 @@ export class CreditLedger {
|
|
|
258
319
|
* @property {number} closedAt
|
|
259
320
|
*/
|
|
260
321
|
|
|
322
|
+
// ---------------------------------------------------------------------------
|
|
323
|
+
// CloseClaim / CloseAck typedefs (two-phase mutual close)
|
|
324
|
+
// ---------------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Signed claim produced by the initiator of a mutual close. Sent to the
|
|
328
|
+
* counterparty, which must verify it and cross-check its own ledger state
|
|
329
|
+
* before co-signing an ack (see PaymentChannel#handleCloseMessage).
|
|
330
|
+
*
|
|
331
|
+
* @typedef {object} CloseClaim
|
|
332
|
+
* @property {string} channelId
|
|
333
|
+
* @property {number} finalLocalBalance - Initiator's claimed final balance
|
|
334
|
+
* @property {number} finalRemoteBalance - Counterparty's claimed final balance
|
|
335
|
+
* @property {number} entryCount
|
|
336
|
+
* @property {number} closedAt
|
|
337
|
+
* @property {string} signature - base64-encoded signature over the fields above
|
|
338
|
+
*/
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Signed acknowledgement of a CloseClaim, produced by the counterparty once
|
|
342
|
+
* it has verified the claim and confirmed it matches its own local ledger.
|
|
343
|
+
* Echoes the claim's fields (co-signed) so the initiator can finalize.
|
|
344
|
+
*
|
|
345
|
+
* @typedef {object} CloseAck
|
|
346
|
+
* @property {string} channelId
|
|
347
|
+
* @property {number} finalLocalBalance
|
|
348
|
+
* @property {number} finalRemoteBalance
|
|
349
|
+
* @property {number} entryCount
|
|
350
|
+
* @property {number} closedAt
|
|
351
|
+
* @property {string} signature - base64-encoded signature, by the counterparty
|
|
352
|
+
*/
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Raised when a close claim or ack fails signature verification, or its
|
|
356
|
+
* balances don't match the receiving side's own local ledger state --
|
|
357
|
+
* i.e. the counterparty is claiming a settlement this side doesn't agree to.
|
|
358
|
+
*
|
|
359
|
+
* @typedef {object} PaymentDispute
|
|
360
|
+
* @property {string} channelId
|
|
361
|
+
* @property {'invalid-signature'|'balance-mismatch'|'invalid-ack-signature'|'ack-mismatch'} reason
|
|
362
|
+
* @property {object} evidence - The claim or ack that triggered the dispute
|
|
363
|
+
* @property {number} localBalance - This side's local balance at dispute time
|
|
364
|
+
* @property {number} remoteBalance - This side's remote balance at dispute time
|
|
365
|
+
* @property {number} raisedAt
|
|
366
|
+
*/
|
|
367
|
+
|
|
261
368
|
// ---------------------------------------------------------------------------
|
|
262
369
|
// PaymentChannel
|
|
263
370
|
// ---------------------------------------------------------------------------
|
|
@@ -305,12 +412,38 @@ export class PaymentChannel {
|
|
|
305
412
|
/** @type {number} */
|
|
306
413
|
#sequence = 0;
|
|
307
414
|
|
|
415
|
+
/** @type {((data: Uint8Array) => Promise<Uint8Array>)|null} */
|
|
416
|
+
#signFn;
|
|
417
|
+
|
|
418
|
+
/** @type {((pubKey: Uint8Array, data: Uint8Array, sig: Uint8Array) => Promise<boolean>)|null} */
|
|
419
|
+
#verifyFn;
|
|
420
|
+
|
|
421
|
+
/** @type {Uint8Array|null} */
|
|
422
|
+
#remotePublicKey;
|
|
423
|
+
|
|
424
|
+
/** @type {PaymentDispute[]} */
|
|
425
|
+
#disputes = [];
|
|
426
|
+
|
|
427
|
+
/** @type {Map<string, Set<Function>>} */
|
|
428
|
+
#listeners = new Map();
|
|
429
|
+
|
|
308
430
|
/**
|
|
309
431
|
* @param {string} localPodId
|
|
310
432
|
* @param {string} remotePodId
|
|
311
433
|
* @param {object} [opts]
|
|
312
434
|
* @param {number} [opts.capacity]
|
|
313
435
|
* @param {number} [opts.ttlMs]
|
|
436
|
+
* @param {Function} [opts.signFn] - async (data: Uint8Array) => Uint8Array.
|
|
437
|
+
* When omitted, PaymentUpdate/close signatures stay `null` and close()
|
|
438
|
+
* stays unilateral -- fully backward compatible.
|
|
439
|
+
* @param {Function} [opts.verifyFn] - async (pubKey, data, sig) => boolean
|
|
440
|
+
* @param {Uint8Array} [opts.remotePublicKey] - Remote pod's raw public key,
|
|
441
|
+
* required alongside verifyFn to verify incoming updates/claims.
|
|
442
|
+
* @param {string} [opts.channelId] - Use this exact channel ID instead of
|
|
443
|
+
* generating a new one. Lets both sides of a channel agree on the same
|
|
444
|
+
* ID (e.g. echoed back from a PAYMENT_OPEN handshake) so signed
|
|
445
|
+
* updates/close messages -- which are keyed by channelId -- validate
|
|
446
|
+
* against each other. Defaults to auto-generated, as before.
|
|
314
447
|
*/
|
|
315
448
|
constructor(localPodId, remotePodId, opts = {}) {
|
|
316
449
|
if (!localPodId || !remotePodId) {
|
|
@@ -318,10 +451,13 @@ export class PaymentChannel {
|
|
|
318
451
|
}
|
|
319
452
|
this.#localPodId = localPodId;
|
|
320
453
|
this.#remotePodId = remotePodId;
|
|
321
|
-
this.#channelId = generateChannelId(localPodId, remotePodId);
|
|
454
|
+
this.#channelId = opts.channelId || generateChannelId(localPodId, remotePodId);
|
|
322
455
|
this.#capacity = opts.capacity || DEFAULT_CAPACITY;
|
|
323
456
|
this.#ttlMs = opts.ttlMs || DEFAULT_TTL_MS;
|
|
324
457
|
this.#createdAt = Date.now();
|
|
458
|
+
this.#signFn = opts.signFn || null;
|
|
459
|
+
this.#verifyFn = opts.verifyFn || null;
|
|
460
|
+
this.#remotePublicKey = opts.remotePublicKey || null;
|
|
325
461
|
}
|
|
326
462
|
|
|
327
463
|
/** Channel identifier. */
|
|
@@ -379,8 +515,13 @@ export class PaymentChannel {
|
|
|
379
515
|
/**
|
|
380
516
|
* Send a payment to the remote pod.
|
|
381
517
|
*
|
|
518
|
+
* When a signFn was injected at construction, the returned PaymentUpdate
|
|
519
|
+
* is signed and this method returns a Promise (awaited by the caller).
|
|
520
|
+
* Without a signFn, behavior is unchanged: synchronous return, signature
|
|
521
|
+
* stays `null`.
|
|
522
|
+
*
|
|
382
523
|
* @param {number} amount
|
|
383
|
-
* @returns {PaymentUpdate}
|
|
524
|
+
* @returns {PaymentUpdate|Promise<PaymentUpdate>}
|
|
384
525
|
*/
|
|
385
526
|
pay(amount) {
|
|
386
527
|
if (this.#state !== 'open') {
|
|
@@ -397,21 +538,40 @@ export class PaymentChannel {
|
|
|
397
538
|
this.#localBalance -= amount;
|
|
398
539
|
this.#remoteBalance += amount;
|
|
399
540
|
this.#sequence += 1;
|
|
400
|
-
|
|
541
|
+
const base = {
|
|
401
542
|
channelId: this.#channelId,
|
|
402
543
|
sequence: this.#sequence,
|
|
403
544
|
amount,
|
|
404
545
|
localBalance: this.#localBalance,
|
|
405
546
|
remoteBalance: this.#remoteBalance,
|
|
406
547
|
timestamp: Date.now(),
|
|
407
|
-
|
|
408
|
-
|
|
548
|
+
};
|
|
549
|
+
if (!this.#signFn) {
|
|
550
|
+
return Object.freeze({ ...base, signature: null });
|
|
551
|
+
}
|
|
552
|
+
return this.#signUpdate(base);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Sign a PaymentUpdate's fields and return the frozen, signed update.
|
|
557
|
+
* @param {object} base - Unsigned update fields
|
|
558
|
+
* @returns {Promise<PaymentUpdate>}
|
|
559
|
+
*/
|
|
560
|
+
async #signUpdate(base) {
|
|
561
|
+
const sigBytes = await this.#signFn(canonicalBytes(base));
|
|
562
|
+
return Object.freeze({ ...base, signature: bytesToBase64(sigBytes) });
|
|
409
563
|
}
|
|
410
564
|
|
|
411
565
|
/**
|
|
412
566
|
* Receive a payment update from the remote pod.
|
|
413
567
|
*
|
|
568
|
+
* When a verifyFn (+ remotePublicKey) was injected at construction, the
|
|
569
|
+
* update's signature is verified before it's applied; unsigned or invalid
|
|
570
|
+
* updates are rejected (this method returns a rejected Promise). Without
|
|
571
|
+
* a verifyFn, behavior is unchanged: synchronous, unconditional apply.
|
|
572
|
+
*
|
|
414
573
|
* @param {PaymentUpdate} update
|
|
574
|
+
* @returns {void|Promise<void>}
|
|
415
575
|
*/
|
|
416
576
|
receive(update) {
|
|
417
577
|
if (this.#state !== 'open') {
|
|
@@ -425,31 +585,285 @@ export class PaymentChannel {
|
|
|
425
585
|
`Stale sequence: got ${update.sequence}, expected > ${this.#sequence}`
|
|
426
586
|
);
|
|
427
587
|
}
|
|
588
|
+
if (!this.#verifyFn) {
|
|
589
|
+
this.#applyReceive(update);
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
return this.#verifyAndApplyReceive(update);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Verify an incoming update's signature and, if valid, apply it.
|
|
597
|
+
* Throws if the signature is missing or invalid.
|
|
598
|
+
* @param {PaymentUpdate} update
|
|
599
|
+
*/
|
|
600
|
+
async #verifyAndApplyReceive(update) {
|
|
601
|
+
const fields = {
|
|
602
|
+
channelId: update.channelId,
|
|
603
|
+
sequence: update.sequence,
|
|
604
|
+
amount: update.amount,
|
|
605
|
+
localBalance: update.localBalance,
|
|
606
|
+
remoteBalance: update.remoteBalance,
|
|
607
|
+
timestamp: update.timestamp,
|
|
608
|
+
};
|
|
609
|
+
const valid = await this.#verifySigned(fields, update.signature);
|
|
610
|
+
if (!valid) {
|
|
611
|
+
throw new Error(
|
|
612
|
+
`Rejected payment update seq ${update.sequence}: missing or invalid signature`
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
this.#applyReceive(update);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** Apply a verified (or verification-not-required) update's balance delta. */
|
|
619
|
+
#applyReceive(update) {
|
|
428
620
|
// From our perspective: remote sent to us, so our local goes up
|
|
429
621
|
this.#localBalance += update.amount;
|
|
430
622
|
this.#remoteBalance -= update.amount;
|
|
431
623
|
this.#sequence = update.sequence;
|
|
432
624
|
}
|
|
433
625
|
|
|
626
|
+
/**
|
|
627
|
+
* Verify a signature over a canonical fields object using the injected
|
|
628
|
+
* verifyFn + remotePublicKey. Never throws -- returns false on any
|
|
629
|
+
* failure (missing config, missing signature, decode error, mismatch).
|
|
630
|
+
*
|
|
631
|
+
* @param {object} fields
|
|
632
|
+
* @param {string|null|undefined} signatureB64
|
|
633
|
+
* @returns {Promise<boolean>}
|
|
634
|
+
*/
|
|
635
|
+
async #verifySigned(fields, signatureB64) {
|
|
636
|
+
if (!this.#verifyFn || !this.#remotePublicKey) return false;
|
|
637
|
+
if (!signatureB64) return false;
|
|
638
|
+
try {
|
|
639
|
+
const data = canonicalBytes(fields);
|
|
640
|
+
const sigBytes = base64ToBytes(signatureB64);
|
|
641
|
+
return await this.#verifyFn(this.#remotePublicKey, data, sigBytes);
|
|
642
|
+
} catch {
|
|
643
|
+
return false;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
434
647
|
/**
|
|
435
648
|
* Close the channel and produce a settlement.
|
|
436
649
|
*
|
|
437
|
-
*
|
|
650
|
+
* Without a signFn, this is unchanged: unilateral and synchronous -- the
|
|
651
|
+
* channel closes immediately with whatever local balances it holds.
|
|
652
|
+
*
|
|
653
|
+
* With a signFn, closing becomes a two-phase mutual protocol: this method
|
|
654
|
+
* signs a CloseClaim of the current local view and moves to the `closing`
|
|
655
|
+
* state, returning a Promise<CloseClaim> to send to the counterparty. The
|
|
656
|
+
* counterparty verifies it via handleCloseMessage(); once its ack comes
|
|
657
|
+
* back, call finalizeClose(ack) to actually reach `closed`.
|
|
658
|
+
*
|
|
659
|
+
* @returns {ChannelSettlement|Promise<CloseClaim>}
|
|
438
660
|
*/
|
|
439
661
|
close() {
|
|
440
662
|
if (this.#state !== 'open') {
|
|
441
663
|
throw new Error(`Cannot close channel in state: ${this.#state}`);
|
|
442
664
|
}
|
|
665
|
+
if (!this.#signFn) {
|
|
666
|
+
this.#state = 'closing';
|
|
667
|
+
const settlement = Object.freeze({
|
|
668
|
+
channelId: this.#channelId,
|
|
669
|
+
finalLocalBalance: this.#localBalance,
|
|
670
|
+
finalRemoteBalance: this.#remoteBalance,
|
|
671
|
+
entryCount: this.#sequence,
|
|
672
|
+
closedAt: Date.now(),
|
|
673
|
+
});
|
|
674
|
+
this.#state = 'closed';
|
|
675
|
+
return settlement;
|
|
676
|
+
}
|
|
677
|
+
return this.#initiateSignedClose();
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* Initiator side of a signed mutual close: sign a claim of the current
|
|
682
|
+
* local view and move to `closing` (not yet `closed`).
|
|
683
|
+
* @returns {Promise<CloseClaim>}
|
|
684
|
+
*/
|
|
685
|
+
async #initiateSignedClose() {
|
|
443
686
|
this.#state = 'closing';
|
|
444
|
-
const
|
|
687
|
+
const claimFields = {
|
|
445
688
|
channelId: this.#channelId,
|
|
446
689
|
finalLocalBalance: this.#localBalance,
|
|
447
690
|
finalRemoteBalance: this.#remoteBalance,
|
|
448
691
|
entryCount: this.#sequence,
|
|
449
692
|
closedAt: Date.now(),
|
|
693
|
+
};
|
|
694
|
+
const sigBytes = await this.#signFn(canonicalBytes(claimFields));
|
|
695
|
+
return Object.freeze({ ...claimFields, signature: bytesToBase64(sigBytes) });
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* Counterparty side of a signed mutual close. Verifies the initiator's
|
|
700
|
+
* claim and cross-checks it against this side's own local ledger state
|
|
701
|
+
* before agreeing. Requires both verifyFn (to check the claim) and
|
|
702
|
+
* signFn (to co-sign the ack) to be configured.
|
|
703
|
+
*
|
|
704
|
+
* On agreement, this channel transitions straight to `closed` (the
|
|
705
|
+
* counterparty doesn't need a further round trip -- it already holds the
|
|
706
|
+
* balances it's attesting to). On mismatch or invalid signature, a
|
|
707
|
+
* PaymentDispute is raised and the channel is left as-is (`open`) so it
|
|
708
|
+
* can be inspected/retried rather than silently accepting the claim.
|
|
709
|
+
*
|
|
710
|
+
* @param {CloseClaim} claim
|
|
711
|
+
* @returns {Promise<{ ok: true, ack: CloseAck }|{ ok: false, dispute: PaymentDispute }>}
|
|
712
|
+
*/
|
|
713
|
+
async handleCloseMessage(claim) {
|
|
714
|
+
if (this.#state !== 'open') {
|
|
715
|
+
throw new Error(`Cannot handle close message in state: ${this.#state}`);
|
|
716
|
+
}
|
|
717
|
+
if (!claim || claim.channelId !== this.#channelId) {
|
|
718
|
+
throw new Error('Channel ID mismatch');
|
|
719
|
+
}
|
|
720
|
+
const claimFields = {
|
|
721
|
+
channelId: claim.channelId,
|
|
722
|
+
finalLocalBalance: claim.finalLocalBalance,
|
|
723
|
+
finalRemoteBalance: claim.finalRemoteBalance,
|
|
724
|
+
entryCount: claim.entryCount,
|
|
725
|
+
closedAt: claim.closedAt,
|
|
726
|
+
};
|
|
727
|
+
const valid = await this.#verifySigned(claimFields, claim.signature);
|
|
728
|
+
// From the initiator's perspective, finalLocalBalance is *their*
|
|
729
|
+
// balance and finalRemoteBalance is *ours* -- so it must mirror what
|
|
730
|
+
// we independently hold.
|
|
731
|
+
const matches = valid
|
|
732
|
+
&& claim.finalRemoteBalance === this.#localBalance
|
|
733
|
+
&& claim.finalLocalBalance === this.#remoteBalance;
|
|
734
|
+
|
|
735
|
+
if (!matches) {
|
|
736
|
+
const dispute = this.#raiseDispute(
|
|
737
|
+
valid ? 'balance-mismatch' : 'invalid-signature',
|
|
738
|
+
claim
|
|
739
|
+
);
|
|
740
|
+
return { ok: false, dispute };
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
if (!this.#signFn) {
|
|
744
|
+
const dispute = this.#raiseDispute('invalid-signature', claim);
|
|
745
|
+
return { ok: false, dispute };
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
const sigBytes = await this.#signFn(canonicalBytes(claimFields));
|
|
749
|
+
const ack = Object.freeze({ ...claimFields, signature: bytesToBase64(sigBytes) });
|
|
750
|
+
this.#state = 'closed';
|
|
751
|
+
return { ok: true, ack };
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Initiator side: finalize a close after receiving the counterparty's
|
|
756
|
+
* ack. Verifies the ack and cross-checks it against the claim this side
|
|
757
|
+
* already sent. On agreement, moves to `closed` and returns the
|
|
758
|
+
* settlement. On mismatch or invalid signature, raises a PaymentDispute
|
|
759
|
+
* instead of trusting the wire message.
|
|
760
|
+
*
|
|
761
|
+
* @param {CloseAck} ack
|
|
762
|
+
* @returns {Promise<{ ok: true, settlement: ChannelSettlement }|{ ok: false, dispute: PaymentDispute }>}
|
|
763
|
+
*/
|
|
764
|
+
async finalizeClose(ack) {
|
|
765
|
+
if (this.#state !== 'closing') {
|
|
766
|
+
throw new Error(`Cannot finalize close in state: ${this.#state}`);
|
|
767
|
+
}
|
|
768
|
+
if (!ack || ack.channelId !== this.#channelId) {
|
|
769
|
+
throw new Error('Channel ID mismatch');
|
|
770
|
+
}
|
|
771
|
+
const ackFields = {
|
|
772
|
+
channelId: ack.channelId,
|
|
773
|
+
finalLocalBalance: ack.finalLocalBalance,
|
|
774
|
+
finalRemoteBalance: ack.finalRemoteBalance,
|
|
775
|
+
entryCount: ack.entryCount,
|
|
776
|
+
closedAt: ack.closedAt,
|
|
777
|
+
};
|
|
778
|
+
const valid = await this.#verifySigned(ackFields, ack.signature);
|
|
779
|
+
const matches = valid
|
|
780
|
+
&& ack.finalLocalBalance === this.#localBalance
|
|
781
|
+
&& ack.finalRemoteBalance === this.#remoteBalance;
|
|
782
|
+
|
|
783
|
+
if (!matches) {
|
|
784
|
+
const dispute = this.#raiseDispute(
|
|
785
|
+
valid ? 'ack-mismatch' : 'invalid-ack-signature',
|
|
786
|
+
ack
|
|
787
|
+
);
|
|
788
|
+
return { ok: false, dispute };
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
const settlement = Object.freeze({
|
|
792
|
+
channelId: this.#channelId,
|
|
793
|
+
finalLocalBalance: this.#localBalance,
|
|
794
|
+
finalRemoteBalance: this.#remoteBalance,
|
|
795
|
+
entryCount: this.#sequence,
|
|
796
|
+
closedAt: ack.closedAt,
|
|
450
797
|
});
|
|
451
798
|
this.#state = 'closed';
|
|
452
|
-
return settlement;
|
|
799
|
+
return { ok: true, settlement };
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* Record a PaymentDispute, emit it to listeners, and return it.
|
|
804
|
+
* @param {PaymentDispute['reason']} reason
|
|
805
|
+
* @param {object} evidence - The claim/ack that triggered the dispute
|
|
806
|
+
* @returns {PaymentDispute}
|
|
807
|
+
*/
|
|
808
|
+
#raiseDispute(reason, evidence) {
|
|
809
|
+
const dispute = Object.freeze({
|
|
810
|
+
channelId: this.#channelId,
|
|
811
|
+
reason,
|
|
812
|
+
evidence,
|
|
813
|
+
localBalance: this.#localBalance,
|
|
814
|
+
remoteBalance: this.#remoteBalance,
|
|
815
|
+
raisedAt: Date.now(),
|
|
816
|
+
});
|
|
817
|
+
this.#disputes.push(dispute);
|
|
818
|
+
this.#emit('dispute', dispute);
|
|
819
|
+
return dispute;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* List all PaymentDisputes raised on this channel.
|
|
824
|
+
* @returns {PaymentDispute[]}
|
|
825
|
+
*/
|
|
826
|
+
listDisputes() {
|
|
827
|
+
return [...this.#disputes];
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Register a listener for 'dispute' events. Convenience wrapper over on().
|
|
832
|
+
* @param {(dispute: PaymentDispute) => void} cb
|
|
833
|
+
*/
|
|
834
|
+
onPaymentDispute(cb) {
|
|
835
|
+
this.on('dispute', cb);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Register a listener for a channel event ('dispute' today).
|
|
840
|
+
* @param {string} event
|
|
841
|
+
* @param {Function} cb
|
|
842
|
+
*/
|
|
843
|
+
on(event, cb) {
|
|
844
|
+
if (!this.#listeners.has(event)) {
|
|
845
|
+
this.#listeners.set(event, new Set());
|
|
846
|
+
}
|
|
847
|
+
this.#listeners.get(event).add(cb);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Remove a listener registered via on()/onPaymentDispute().
|
|
852
|
+
* @param {string} event
|
|
853
|
+
* @param {Function} cb
|
|
854
|
+
*/
|
|
855
|
+
off(event, cb) {
|
|
856
|
+
const set = this.#listeners.get(event);
|
|
857
|
+
if (set) set.delete(cb);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** @param {string} event @param {*} data */
|
|
861
|
+
#emit(event, data) {
|
|
862
|
+
const set = this.#listeners.get(event);
|
|
863
|
+
if (!set) return;
|
|
864
|
+
for (const cb of set) {
|
|
865
|
+
try { cb(data); } catch (e) { silentCatch('clawser-mesh-payments', 'channel-listener', e) }
|
|
866
|
+
}
|
|
453
867
|
}
|
|
454
868
|
|
|
455
869
|
/**
|
|
@@ -483,12 +897,17 @@ export class PaymentChannel {
|
|
|
483
897
|
/**
|
|
484
898
|
* Restore a PaymentChannel from serialized data.
|
|
485
899
|
* @param {object} data
|
|
900
|
+
* @param {object} [extraOpts] - Additional constructor opts not covered by
|
|
901
|
+
* `data` (signFn/verifyFn/remotePublicKey aren't serializable, so they
|
|
902
|
+
* aren't part of toJSON()'s output -- pass them here to restore a
|
|
903
|
+
* signing-capable channel).
|
|
486
904
|
* @returns {PaymentChannel}
|
|
487
905
|
*/
|
|
488
|
-
static fromJSON(data) {
|
|
906
|
+
static fromJSON(data, extraOpts = {}) {
|
|
489
907
|
const ch = new PaymentChannel(data.localPodId, data.remotePodId, {
|
|
490
908
|
capacity: data.capacity,
|
|
491
909
|
ttlMs: data.ttlMs,
|
|
910
|
+
...extraOpts,
|
|
492
911
|
});
|
|
493
912
|
ch.#channelId = data.channelId;
|
|
494
913
|
ch.#createdAt = data.createdAt;
|
|
@@ -696,6 +1115,12 @@ export class PaymentRouter {
|
|
|
696
1115
|
/** @type {ReturnType<typeof setInterval>|null} */
|
|
697
1116
|
#escrowSweeperTimer = null;
|
|
698
1117
|
|
|
1118
|
+
/** @type {PaymentDispute[]} */
|
|
1119
|
+
#disputes = [];
|
|
1120
|
+
|
|
1121
|
+
/** @type {Set<Function>} */
|
|
1122
|
+
#disputeListeners = new Set();
|
|
1123
|
+
|
|
699
1124
|
/**
|
|
700
1125
|
* @param {string} localPodId
|
|
701
1126
|
*/
|
|
@@ -721,13 +1146,19 @@ export class PaymentRouter {
|
|
|
721
1146
|
*
|
|
722
1147
|
* @param {string} remotePodId
|
|
723
1148
|
* @param {number} [capacity]
|
|
1149
|
+
* @param {object} [signingOpts] - Forwarded to PaymentChannel to enable
|
|
1150
|
+
* signed updates and mutual close. Omit for unchanged, unsigned behavior.
|
|
1151
|
+
* @param {Function} [signingOpts.signFn]
|
|
1152
|
+
* @param {Function} [signingOpts.verifyFn]
|
|
1153
|
+
* @param {Uint8Array} [signingOpts.remotePublicKey]
|
|
724
1154
|
* @returns {PaymentChannel}
|
|
725
1155
|
*/
|
|
726
|
-
openChannel(remotePodId, capacity) {
|
|
1156
|
+
openChannel(remotePodId, capacity, signingOpts) {
|
|
727
1157
|
if (this.#channels.has(remotePodId)) {
|
|
728
1158
|
throw new Error(`Channel to ${remotePodId} already exists`);
|
|
729
1159
|
}
|
|
730
|
-
const opts =
|
|
1160
|
+
const opts = { ...(signingOpts || {}) };
|
|
1161
|
+
if (capacity != null) opts.capacity = capacity;
|
|
731
1162
|
const ch = new PaymentChannel(this.#localPodId, remotePodId, opts);
|
|
732
1163
|
this.#channels.set(remotePodId, ch);
|
|
733
1164
|
return ch;
|
|
@@ -746,15 +1177,60 @@ export class PaymentRouter {
|
|
|
746
1177
|
/**
|
|
747
1178
|
* Close a channel and return the settlement.
|
|
748
1179
|
*
|
|
1180
|
+
* When the channel has signing configured, this only *initiates* the
|
|
1181
|
+
* two-phase close: it broadcasts a signed CloseClaim and returns a
|
|
1182
|
+
* Promise that resolves once the claim is sent (not once the
|
|
1183
|
+
* counterparty has acked). The channel itself stays in the router's
|
|
1184
|
+
* map until wireTransport's PAYMENT_CLOSE handler receives the ack and
|
|
1185
|
+
* removes it -- see wireTransport() below.
|
|
1186
|
+
*
|
|
749
1187
|
* @param {string} remotePodId
|
|
750
|
-
* @returns {ChannelSettlement|null}
|
|
1188
|
+
* @returns {ChannelSettlement|Promise<{ pending: true, claim: CloseClaim }>|null}
|
|
751
1189
|
*/
|
|
752
1190
|
closeChannel(remotePodId) {
|
|
753
1191
|
const ch = this.#channels.get(remotePodId);
|
|
754
1192
|
if (!ch) return null;
|
|
755
|
-
const
|
|
1193
|
+
const result = ch.close();
|
|
1194
|
+
if (result && typeof result.then === 'function') {
|
|
1195
|
+
// Signed two-phase close: `result` resolves to a CloseClaim. Leave
|
|
1196
|
+
// the channel in the map (state 'closing') until the counterparty's
|
|
1197
|
+
// ack arrives over the wire and finalizes it.
|
|
1198
|
+
return result.then((claim) => {
|
|
1199
|
+
this.broadcastClose(remotePodId, { claim });
|
|
1200
|
+
return { pending: true, claim };
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
756
1203
|
this.#channels.delete(remotePodId);
|
|
757
|
-
return
|
|
1204
|
+
return result;
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
/**
|
|
1208
|
+
* List all PaymentDisputes raised across every channel handled by this
|
|
1209
|
+
* router (signed close mismatches or invalid signatures).
|
|
1210
|
+
* @returns {PaymentDispute[]}
|
|
1211
|
+
*/
|
|
1212
|
+
listDisputes() {
|
|
1213
|
+
return [...this.#disputes];
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* Register a listener called whenever a PaymentDispute is raised on any
|
|
1218
|
+
* channel wired through this router.
|
|
1219
|
+
* @param {(dispute: PaymentDispute) => void} cb
|
|
1220
|
+
*/
|
|
1221
|
+
onPaymentDispute(cb) {
|
|
1222
|
+
this.#disputeListeners.add(cb);
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
/**
|
|
1226
|
+
* Record a dispute and notify onPaymentDispute() listeners.
|
|
1227
|
+
* @param {PaymentDispute} dispute
|
|
1228
|
+
*/
|
|
1229
|
+
#recordDispute(dispute) {
|
|
1230
|
+
this.#disputes.push(dispute);
|
|
1231
|
+
for (const cb of this.#disputeListeners) {
|
|
1232
|
+
try { cb(dispute); } catch (e) { silentCatch('clawser-mesh-payments', 'onPaymentDispute-callback', e) }
|
|
1233
|
+
}
|
|
758
1234
|
}
|
|
759
1235
|
|
|
760
1236
|
/**
|
|
@@ -842,14 +1318,58 @@ export class PaymentRouter {
|
|
|
842
1318
|
try {
|
|
843
1319
|
const ch = this.#channels.get(fromPodId);
|
|
844
1320
|
if (ch) {
|
|
845
|
-
ch.receive(
|
|
1321
|
+
// ch.receive() is synchronous when the channel has no verifyFn
|
|
1322
|
+
// (unchanged legacy behavior) or returns a Promise that rejects
|
|
1323
|
+
// on an unsigned/invalid update when verification is active.
|
|
1324
|
+
const result = ch.receive(payload);
|
|
1325
|
+
if (result && typeof result.then === 'function') {
|
|
1326
|
+
result.catch((e) => silentCatch('clawser-mesh-payments', 'ignore-invalid-signed-update', e));
|
|
1327
|
+
}
|
|
846
1328
|
}
|
|
847
1329
|
} catch (e) { silentCatch('clawser-mesh-payments', 'ignore-invalid-updates', e) }
|
|
848
1330
|
});
|
|
849
1331
|
|
|
850
1332
|
// Inbound: channel close
|
|
851
1333
|
subscribeFn(PAYMENT_CLOSE, (payload, fromPodId) => {
|
|
852
|
-
try {
|
|
1334
|
+
try {
|
|
1335
|
+
const ch = this.#channels.get(fromPodId);
|
|
1336
|
+
|
|
1337
|
+
if (ch && payload && payload.claim) {
|
|
1338
|
+
// Two-phase signed close: this is the initiator's signed claim.
|
|
1339
|
+
// Verify + cross-check against our own ledger, then either
|
|
1340
|
+
// co-sign an ack or raise a dispute -- never accept the wire
|
|
1341
|
+
// message's numbers unconditionally.
|
|
1342
|
+
Promise.resolve(ch.handleCloseMessage(payload.claim))
|
|
1343
|
+
.then((result) => {
|
|
1344
|
+
if (result.ok) {
|
|
1345
|
+
this.#channels.delete(fromPodId);
|
|
1346
|
+
this.broadcastClose(fromPodId, { ack: result.ack });
|
|
1347
|
+
} else {
|
|
1348
|
+
this.#recordDispute(result.dispute);
|
|
1349
|
+
}
|
|
1350
|
+
})
|
|
1351
|
+
.catch((e) => silentCatch('clawser-mesh-payments', 'handleCloseMessage', e));
|
|
1352
|
+
return;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
if (ch && payload && payload.ack) {
|
|
1356
|
+
// Two-phase signed close: this is the counterparty's ack of our
|
|
1357
|
+
// claim. Verify + cross-check before finalizing.
|
|
1358
|
+
Promise.resolve(ch.finalizeClose(payload.ack))
|
|
1359
|
+
.then((result) => {
|
|
1360
|
+
if (result.ok) {
|
|
1361
|
+
this.#channels.delete(fromPodId);
|
|
1362
|
+
} else {
|
|
1363
|
+
this.#recordDispute(result.dispute);
|
|
1364
|
+
}
|
|
1365
|
+
})
|
|
1366
|
+
.catch((e) => silentCatch('clawser-mesh-payments', 'finalizeClose', e));
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// Legacy unilateral close (no signing configured on this channel).
|
|
1371
|
+
this.closeChannel(fromPodId);
|
|
1372
|
+
} catch (e) { silentCatch('clawser-mesh-payments', 'this.closeChannel', e) }
|
|
853
1373
|
});
|
|
854
1374
|
|
|
855
1375
|
// Inbound: escrow creation
|