Skip to content

feat: add BRC-170 LCH reference implementation - #501

Open
ty-everett wants to merge 21 commits into
mainfrom
codex/lch-reference-implementation
Open

feat: add BRC-170 LCH reference implementation#501
ty-everett wants to merge 21 commits into
mainfrom
codex/lch-reference-implementation

Conversation

@ty-everett

@ty-everett ty-everett commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

BRC-170 is published at https://bsv.brc.dev/apps/0170. This implementation
remains unpublished until normal TS Stack review and release approval.

Program and scope

  • Published standard: BRC-170, https://github.com/bsv-blockchain/BRCs/blob/master/apps/0170.md
  • Related storage standard: BRC-167 CHIRP, https://bsv.brc.dev/overlays/0167
  • Program gate(s) advanced: neutral reference implementation, portable vectors,
    executable profile feedback, recovery-safe multilateral settlement, and a
    complete consumer/deployment documentation set for the published standard.
  • Why this change is needed: downstream creators, players, DAWs, storefronts,
    wallets, Payees, content hosts, and implementation agents need concrete,
    interoperable LCH building blocks and an explicit way to combine them with
    CHIRP without changing UHRP.
  • Explicitly out of scope: npm publication from this PR, live storefront
    operation, application-specific catalogue/social schemas, future selective
    composition mapping, partial-host CHIRP coverage, and a streaming LCH decoder.
  • Exact head SHA reviewed: 6c7b287b69dbabc3b6a74cf56d4c7c353c55ce95.

Impact

  • No public package source or manifest changed
  • Public package source or manifest changed; affected packages are listed below
  • Infrastructure source, dependency, image, or deployment configuration changed
  • Public API, exports, types, runtime targets, or browser/mobile behavior changed
  • Security-sensitive boundary changed
  • Documentation or examples changed

Affected packages/services and intended versions (publication occurs only
through the release workflow after approval):

  • New public @bsv/lch 0.1.0 package with deterministic BRC-170 framing,
    encryption, rights, acquisition, multilateral settlement, key delivery,
    authority/revocation, transport, composition/provenance, CLI, UHRP, and CHIRP
    adapters.
  • Existing additive @bsv/chirp 0.1.1 package remains the BRC-167 storage layer;
    its APIs and every existing UHRP API remain backward compatible.
  • New private apps/lch-reference neutral workbench with creator, server,
    player, wallet-module, all six initial usage profiles, both settlement
    profiles, repeated placements, time warp, reversal, distortion, offline
    Payee recovery, provider outage, and conflict cases.
  • New docs/guides/chirp-lch-production.md consumer and operator guide covering
    layer selection, public APIs by role, resumable publication, acquisition,
    payment destinations, independent Payee topology, persistence, failure and
    recovery, security, observability, rollout/rollback, production gates, and an
    agent implementation contract.
  • No package publication or deployment performed.

Verification

  • Local full workspace test: all 40 test projects passed. The suite includes
    6,690 conformance vectors; LCH 118/118; CHIRP 109/109; reference workbench 15/15;
    and the complete SDK, Wallet Toolbox, overlay, messaging, helper, browser, and
    mobile suites.
  • Local repository gates: root typecheck, zero-warning lint, formatting,
    repository health, contributor policy, dependency/release governance,
    license and third-party notices, operations docs, resource profiles, browser
    governance, service policies, and runtime-copy checks passed.
  • Documentation: package facts and generated migration ledger are current for
    33 public packages; documentation policy reports 44 package docs, 100 fresh
    records, and zero findings; eight examples compile against 21 exact package
    tarballs; the site prerendered 120 routes, indexed 125 pages, and passed built
    link and bundle-license validation.
  • Package artifacts: both @bsv/lch and @bsv/chirp pass exact tarball,
    conditional export, source-map, publint, strict type, ESM consumer, CLI, Vite,
    and esbuild browser checks. apps/lch-reference builds browser and Node
    bundles and copies its scoped notice plus exact license archive.
  • Runtime smoke: the built Node reference server returned status: ready, its
    independently routed issuer/Payee/provider endpoints, walletMode: fixture,
    and contentAdapter: reference-memory; deployment guidance requires those
    fixture/memory boundaries to be replaced before real purchases.
  • Hosted exact-head CI: 37 checks succeeded, three scope-based jobs were
    correctly skipped, and zero checks failed, were cancelled, or remained pending.
    The merge gate, aggregate coverage, CodeQL, Sonar, Socket, dependency review,
    mutation, conformance, docs, browser/mobile, package, and policy lanes passed
    at the exact head SHA.
  • Exact-head quality evidence: aggregate changed-code coverage passed its 90%
    gate; lch-cbor mutation scored 92.47%; CodeQL passed; and Sonar reported zero
    new issues and zero unreviewed security hotspots.
  • I self-reviewed the complete diff for correctness, security, compatibility,
    public API, artifacts, dependencies, docs, and operations
  • All applicable checks are terminal and successful on the exact head

Dependency evidence

  • The change adds the public @bsv/lch manifest and the private
    apps/lch-reference workspace manifest. The lockfile adds only those two
    importer records and reuses versions already resolved by the workspace; it
    adds no registry package snapshot or dependency override.
  • @bsv/lch has no direct runtime dependency. It declares @bsv/sdk as a
    peer and @bsv/chirp as an optional peer so LCH-only consumers do not pull
    CHIRP, while the reference app links both packages from the workspace.
  • Hosted dependency review, high/critical audit, frozen workspace install,
    exact-package artifact checks, npm release dry run, package-license policy,
    third-party-material policy, and bundled-notice validation pass on the exact
    head. No advisory was dismissed for this change.

Security, dependencies, and compatibility

  • New-package manifests and lockfile importers are documented in Dependency
    evidence; no registry snapshot, override, advisory dismissal, quality
    suppression, or required-test skip was introduced
  • Existing StorageUploader, StorageDownloader, StorageUtils, UHRP
    identifiers, overlays, advertisements, and routes remain unchanged
  • CHIRP and LCH fail closed on unknown critical profiles/extensions and
    document bounded parsing, SSRF/DNS rebinding, early-consumption, credential,
    key, recovery, and provider-trust boundaries
  • Wallet transaction creation remains explicit; funded Atomic BEEF and signed
    Deliveries must be persisted before fan-out and retried without replacement
  • Payee endpoints, wallets, Payment Ledgers, evidence providers, Delivery
    providers, issuers, and content hosts can be independently operated
  • Receipt-complete and authorized-output availability/privacy/finality
    tradeoffs are documented and exercised
  • The bounded in-memory LCH 0.1 reader/publisher limit is explicit; raw CHIRP
    ciphertext ranges are never described as authenticated playable plaintext

Release and operations

  • No npm publication was performed from a workstation or from this PR
  • Documentation, changelog, release notes, third-party notices, and operator
    guidance are current for published BRC-170
  • Durable-state ownership, independent wallet topology, health expectations,
    retention/renewal, recovery, backup/restore, rollout, and rollback are documented
  • Published BRC-167 and BRC-170 remain authoritative where implementation
    behavior differs

Completion evidence

  • BRC-170 is merged and published
  • Review conversations are resolved; no review thread is currently open
  • Comprehensive consumer, integrator, operator, and agent guidance is present
  • Package/release/notice documentation is regenerated and current
  • Exact-head hosted checks are terminal and successful
  • One qualified maintainer approval has been received

@ty-everett

Copy link
Copy Markdown
Collaborator Author

Exact head 971eb4f6690a4ca9f8fa65fc872a5a507b978cd4 is now fully green: 36 successful checks, three expected scope skips, zero pending/failing checks, and merge-gate success. Hosted changed-code coverage is 90.19% (1,452/1,610), LCH CBOR mutation score is 92.47%, and Sonar reports 0 unresolved issues / 0 hotspots. The draft also includes the neutral reference-workbench pass, release-consistent third-party notices, and the repeat/reversal/exact-ratio time-warp/distortion conformance scenarios. This PR remains draft pending joint review with BRC-170.

@ty-everett

Copy link
Copy Markdown
Collaborator Author

Exact head 2d78df64c54a00248641f0f6f579c43ff5af627b turns the LCH draft into an executable acquisition stack.

The reference path is now concrete end to end: a creator wizard publishes protected content and an Offer; the issuer produces buyer-bound Payment Demands; a BRC-100 buyer wallet funds one Atomic BEEF transaction; each Payee verifies and internalizes its exact BRC-29 wallet-payment output; the issuer verifies the signed receipts and releases the License; and the player decrypts and exercises every initial profile. Ambiguous delivery recovery reuses the same funded transaction and cannot double-pay.

The package includes the deterministic-CBOR HTTP binding, reusable server/client, Payee receiver and ledger boundary, multilateral payment client, endpoint policy, recovery, and deployment adapters. The executable reference server exposes health, asset publication, acquisition, and range-capable content endpoints; DEPLOYMENT.md defines single-process and durable topologies, connected-wallet module wiring, and CHIRP/UHRP content adapters. The neutral workbench visibly exercises repeat, trim, exact rational time-warp, reversal, distortion, mixing, C2PA placement, training provenance, and all six initial profiles. Release-consistent third-party notices are retained in the built artifact.

Exact-head hosted CI is fully green: 36 successful checks, 3 expected scope skips, 0 pending/failing; merge gate, Sonar, CodeQL, dependency review, browser/mobile lanes, package artifact checks, and mutation gates all pass. Hosted changed-code coverage is 90.65% (2,122/2,341 points; 90% target). Local @bsv/lch coverage is 94.03% statements / 83.87% branches / 95.11% functions / 95.00% lines, with a 92.47% mutation score. Package tests are 82/82 and reference-app tests are 11/11. A live Node smoke acquisition completed 7+5 satoshis across two Payees, issued a License, decrypted the content, and recovered idempotently.

There are no unresolved review threads. This remains draft for joint review with the current BRC-170 text and for a second-implementation interoperability pass.

@ty-everett

ty-everett commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator Author

Federated Payee delivery and the final coverage hardening are now on exact head aefdbecd90ce139f529d8cfc55d22edefe78dfcd.

  • Every signed Payment Demand retains its Payee-chosen endpoint. The reference server now mounts issuer coordination separately from independently routed recording/composition Payee handlers and rejects a Demand delivered to the wrong Payee route.
  • LCHAcquisitionTransport is the injectable client boundary, with deterministic-CBOR HTTP remaining the default. A message-box gateway/adapter can preserve the signed objects and recovery workflow; native asynchronous wire semantics remain explicit profile work.
  • The package interoperability test runs issuer, drummer, and composer at three distinct HTTPS origins with three independent LCHHttpServer instances. It verifies direct per-Demand dispatch, distinct wallets, wrong-route rejection, and recovery-safe reuse of the same funded transaction.
  • Deployment documentation now shows where value lands (internalizeAction in each Payee BRC-100 wallet), who persists partial Receipts, and both collapsed and federated topologies.

Validation on this head:

  • GitHub: 37 successful checks, 3 expected skips, 0 failures/pending; merge gate, CodeQL, Sonar zero-new-findings, dependency/security, browser/mobile, release artifacts, aggregate coverage, and mutation are green.
  • @bsv/lch: 91 tests; reference app: 11 tests.
  • Local @bsv/lch coverage: 96.25% statements, 86.08% branches, 96.11% functions, 97.18% lines.
  • Mutation score: 92.47% (134 killed, 11 survived, 1 timeout).
  • Codecov reports 91.04193% patch coverage (1,433 hits, 57 misses, 84 partials).
  • Repository health passes after narrowly revalidating the TypeScript compiler-API and Stryker/typed-rest-client compatibility holds through 2026-09-27.
  • No unresolved review threads; local and remote heads match.

The PR remains draft for joint BRC-170 review and independent interoperability work.

@ty-everett

Copy link
Copy Markdown
Collaborator Author

Availability and authorized-output settlement refinement is complete at d0fddb9.

What is now concrete:

  • receipt-complete-v1 remains the baseline direct-Payee settlement profile.
  • authorized-output-v1 is explicit opt-in per Demand and uses Payee-signed output authorization, accepted transaction evidence, durable byte-exact Delivery custody, authenticated late retrieval, and profile-specific License fulfillment.
  • settleDelivery tries the direct Payee Receipt first and falls back only for an opted-in authorized-output Demand.
  • The Payee independently derives and verifies the exact BRC-29 output script before authorizing it.
  • Authorization-to-first-txid binding, repeat-safe Delivery storage, conflicting-byte rejection, provider outage retry without a second funded transaction, late retrieval, and exactly-once wallet internalization are exercised.
  • The reference app exposes roles, wallets, money flow, readiness, providers, pending settlement, offline recovery, repeats, reversal, rational time warp, distortion, and profile edge cases.
  • The reference distribution includes the project license and third-party notices; this layer adds no dependency.

Validation:

  • @bsv/lch: 16 suites and 96 tests pass; 95.18% statements, 84.99% branches, 94.98% functions, and 96.23% lines locally.
  • Browser contract, exact-tarball pack checks, reference client and SSR production builds, reference integration tests, repository health, documentation examples, licensing policy, and the live browser recovery flow pass.
  • Exact-head CI: 37 successful checks, 3 intentionally skipped non-applicable checks, merge gate green, CodeQL green, mutation quality green, and zero unresolved Sonar issues.
  • Codecov patch coverage is 90.20619% and green. The final offline-Payee workflow test raised it from 89.12371%.
  • No unresolved review threads.

The matching BRC-170 refinement is bsv-blockchain/BRCs#236 at 418ed7ed4a56fd6fa16b7a02f1eaf361929519e0. This TS Stack PR remains draft for coordinated spec and implementation review.

@ty-everett
ty-everett marked this pull request as ready for review August 28, 2026 18:29
@raspi-user

Copy link
Copy Markdown

I reviewed the current head 32ba2eabb36001f1a8db8200e51ce3126c4468bd. CI is green and the implementation looks serious: deterministic CBOR, endpoint validation, bounded HTTP bodies, signed-object validation, payment output matching, recovery tests, and the reference app all appear to have had substantial coverage.

I do have a few points I would want addressed or explicitly answered before treating this as ready:

  1. License response is not fully bound before returning to the buyer

    In packages/content/lch/src/multipayClient.ts, complete() verifies the returned license signature, requestId, and subject, but it does not appear to verify that the license is for the same assetId, offerId, paid selection, fulfilments, or key grants from the quote/request. For a paid acquisition path, the buyer should not return a license as valid unless it is explicitly bound to the thing just paid for. The issuer may be trusted, but client-side validation should still catch a wrong or buggy license response deterministically.

  2. Authorized-output fallback may be too broad

    In packages/content/lch/src/multipayClient.ts, settleDelivery() falls back to authorized-output evidence on any direct-delivery error for that settlement profile. That catches the intended offline-Payee case, but it also appears to catch malformed receipts, wrong receipt data, unexpected endpoint behaviour, or other protocol errors. I would prefer the fallback to distinguish transport/unavailability failures from validation failures, or for the security rationale to be documented very explicitly.

  3. IndexedDB persistence resolves before transaction completion

    In packages/content/lch/src/storage.ts, transactionPromise() resolves on request success, not transaction.oncomplete. For license storage/recovery state, callers may believe a write is durable before IndexedDB has actually committed the transaction. This should wait for transaction completion, and ideally close DB handles after operations to avoid long-lived browser resource growth.

Overall, this is a strong PR and the architecture is broadly in the right direction. My main concern is not the amount of code, but making sure the buyer-side validation and persistence boundaries are strict enough for a payment/licensing protocol.

Tests reviewed: GitHub shows green checks on the current head. I did not run the full workspace locally.

@ty-everett
ty-everett marked this pull request as draft August 30, 2026 23:43
@sonarqubecloud

Copy link
Copy Markdown

@ty-everett

Copy link
Copy Markdown
Collaborator Author

Addressed the review feedback on exact head 6c7b287b69dbabc3b6a74cf56d4c7c353c55ce95.

For the three acquisition/persistence points:

  • complete() now verifies the returned License signature and exact acquisition context: version, issue time, agreement shape, Asset ID, Offer ID, Request ID, issuer, subject, normalized Selection and optional segment Selection, the exact multiset of submitted Receipt/authorized-output fulfilments, and profile-exact key grants. The caller supplies an explicit key-grant expectation derived from the verified Asset encryption descriptor and Offer delivery mechanism. Mutation tests cover wrong Asset, Selection, fulfilments, and unexpected grants.
  • settleDelivery() now catches only rejection of the direct transport call. Receipt parsing and verification happen after that boundary, so malformed, misrouted, or otherwise invalid Receipts fail closed and never invoke authorized-output fallback. A regression test proves an invalid returned Receipt does not contact fallback providers.
  • IndexedDB writes resolve only on transaction.oncomplete, reject on transaction error/abort, and all put/get/delete/list operations close their database handles. The storage test holds a successful request pending until commit and verifies closure.

The additional review findings are also closed: URL-normalized IPv4-mapped IPv6 loopback is rejected before connection (with the regression constructed through new URL(...).hostname); endpoint classification was refactored without weakening the SSRF/DNS-rebinding policy; the workbench says Published BRC-170; deployment guidance treats reference-memory health as non-production; composition traversal is bounded and expands shared provenance states once; malformed co-signatures no longer abort otherwise-valid verification; unknown Selections return ERR_LCH_SELECTION; and UHRP resolution fails over across verified hosts.

The time-bound wallet manual-suite inventory was re-audited after UTC expiry. All 30 exact dispositions remain current, and the inspection also restored six mechanically weakened string/number assertions without running funded/live suites.

Validation is terminal on this exact head: 36 checks succeeded, three scope-based checks were skipped, and none failed or remain pending. Repository health, dependency review, build/typecheck/lint/format, exact package artifacts, npm supply-chain dry run, docs, aggregate coverage, lch-cbor mutation, CodeQL, Sonar (0 issues / 0 hotspots), browser/mobile, Wallet Toolbox, and conformance all pass. The PR description now records the exact head and dependency evidence.

@ty-everett
ty-everett marked this pull request as ready for review August 31, 2026 00:31

@BraydenLangley BraydenLangley left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixes look good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants