BSV SDK
BSV BLOCKCHAIN | Software Development Kit for JavaScript and TypeScript
Welcome to the BSV Blockchain Libraries Project, the comprehensive TypeScript SDK designed to provide an updated and unified layer for developing scalable applications on the BSV Blockchain. This SDK addresses the limitations of previous tools by offering a fresh, peer-to-peer approach, adhering to SPV, and ensuring privacy and scalability.
LocalKVStore removal (4.1.1 patch candidate)
LocalKVStore.remove rejects if the wallet reports a positive totalOutputs
but returns an empty page, instead of repeating the same request indefinitely.
The error identifies the key, total and offset, and the per-key operation lock
is released. An absent key still returns []; ordinary removal, set and
get retain their behavior. No API, wire or stored-data migration is required.
GlobalKVStore tag compatibility (4.1.1 patch candidate)
GlobalKVStore has no fixed tag-count cap. A signed token may contain more than
32 tags, and tag-filter queries preserve the entire supplied array. Each tag
must remain a unique, non-empty string of at most 256 UTF-8 bytes. Existing
token field/payload byte bounds, signature verification and controller/locking-key
binding still apply. Wallet output tags and action labels are separate metadata
and are unchanged. A non-array tag container raises TypeError, an Error
subclass, with the existing diagnostic.
To read or publish larger tag sets, upgrade both the application's SDK and the
SDK used by the overlay, together with the updated @bsv/overlay-topics lookup
service. Older SDK validators or lookup services may still reject more than
32 tags. Existing token bytes and stored records do not need rewriting.
Optional client timeouts (4.0.1 patch candidate)
LookupResolverConfig.trackerTimeoutMs controls each SLAP discovery request;
its default remains 5,000 ms. The per-host query timeout and whole-query
deadlineMs remain independent. Increase the whole-query deadline as well when
discovery may exceed its existing 10,000 ms default:
import { AuthFetch, LookupResolver, type WalletInterface } from '@bsv/sdk'
declare const wallet: WalletInterface
const resolver = new LookupResolver({ trackerTimeoutMs: 20_000 })
await resolver.query({ service: 'ls_example', query: {} }, 20_000, { deadlineMs: 25_000 })
const auth = new AuthFetch(wallet, undefined, undefined, undefined, {
requestTimeoutMs: 60_000,
responseTimeoutMs: 60_000
})
AuthFetchOptions.responseTimeoutMs uses the existing fifth constructor
argument and defaults to 30,000 ms. It controls the authenticated response
waiter independently of the existing transport requestTimeoutMs (also
30,000 ms by default), which bounds fetch and response-body reads. Set both
when extending a request. Existing calls and other certificate, session and
operation deadlines retain their behavior.
Both new options require positive integer milliseconds: trackerTimeoutMs
accepts 1–60,000, matching the existing lookup timeout bound, and
responseTimeoutMs accepts 1–2,147,483,647, the portable timer bound. Invalid
explicit values throw RangeError at construction. Omission preserves all
previous defaults; no API, wire or wallet-data migration is required.
A timeout does not undo a request already dispatched to a server. Reconcile
an ambiguous financial operation before submitting it again.
DID serial-token API retirement (3.0 candidate)
The proposed SDK 3.0 release removes CanonicalDIDToken, DID_TOKEN_PROTOCOL,
MAX_DID_SERIAL_BYTES, decodeCanonicalDIDToken and normalizeDIDSerialNumber,
including the identity/DIDTokenValidation deep import. Existing wallet,
certificate and identity-discovery APIs remain supported.
Use @bsv/did for validated identity-key did:key encoding/resolution and the
proposed signature-preserving BRC-52 credential adapter. Use BRC-100 wallet
identity discovery or the existing tm_identity / ls_identity overlay for
public certificate candidates. Verify the original derived-key certificate
signature and apply selected certifier trust independently of discovery. A
resolved DID establishes its encoded key; live key control requires a separate
authentication protocol. Historical serial tokens provide no implicit issuer
or subject binding.
See identity integration and migration guidance before upgrading. This is a source candidate; publication and deployment are separate actions.
4.1.0 source candidate
The additive payment transport helpers, typed recovery outcomes and AuthFetch multipart support in this source are included with the SDK4 major release after immutable published 3.2.1. This candidate is built from this branch; changing its version does not publish it or replace any registry artifact. Existing non-multipart wire behavior and security limits remain. The complete dependency and supported peer matrix must qualify before release; an unavailable SDK2 version is not a compatibility implementation.
Numeric results and wallet wire compatibility (4.0.1 hotfix)
ListOutputsResult.totalOutputs is a number. Ordinary listings return counts;
BRC-112 balance <basket> and p <module> balance <basket> return nonnegative
integer summaries with empty outputs and no BEEF. Sums are computed exactly
before Number conversion. Values above 2^53 may round; enumerate outputs for
exact accounting or value movement. JSON can carry a larger finite summary;
the numeric binary serializer rejects values at or above 2^64.
Default binary requests retain deployed SDK2/3 bytes and imply spendable:true.
The #674 extension is preserved: new WalletWireTransceiver(wire, { listOutputsEncoding: 'spendable' }) explicitly requests and requires an
acknowledged spendability byte. JSON and this extension preserve reserved or
pending module inventory records. No format guessing or automatic retry occurs.
DecimalString and the previous module-balance helpers remain exported for
source compatibility. Existing applications retain numeric results without
selecting a separate compatibility profile.
Wallet integration
For application-to-wallet integrations, the SDK exposes the BRC-100 WalletClient interface. BSV Desktop and BSV Browser are the BSV Association reference implementations for this interface; vendor distributions such as Babbage's Metanet Desktop / Metanet Explorer and Hudos Browser can implement the same interface with their own branding and service defaults.
The BRC-100 CreateActionResult permits AtomicBEEF as either number[] or
Uint8Array. SDK BRC-29 remittance accepts both wallet representations and
emits a portable number[] settlement artifact so HTTP, WebSocket, Message Box,
and JSON transports preserve identical transaction bytes. The same boundary
protects overlay lookup queries and JSON BEEF responses.
Version 2.8.0 verifies bodyless authenticated HTTP responses
using the BRC-104 -1 body-length sentinel. Conforming 204 and empty error
responses now verify; non-empty response encoding is unchanged. Servers that
sign a zero body length for an empty response must adopt the specified sentinel.
AuthFetch stops pending certificate dispatch and session recovery after its request deadline. An already dispatched request may still complete on the server; callers must resolve its outcome before retrying a non-idempotent write.
AuthFetch's automatic BRC-105 payment path delegates spending authorization to
the configured wallet's createAction policy. Use a wallet that requires the
intended user or policy approval. Payment logs and terminal errors omit URL
credentials/path/query, header values other than Content-Type, transaction
bytes, and derivation material. Buffered received certificates are capped at
the most recent 1,000 entries. Simplified authenticated HTTP frames, bodies,
headers, signatures, request IDs, and certificate-request headers have fixed
size/count limits and redirects are rejected.
Ordinary HTTP fallback preserves native fetch body semantics: text, URLSearchParams, typed Blob and FormData retain their generated media types and serialization. Mutable inputs are snapshotted before discovery; authenticated payment retries continue to use owned bytes. Explicit caller Content-Type headers take precedence.
The next release adds negotiated BRC-118 multipart payments. AuthFetch prepares
with noSend, validates the actual final payment/request size, then submits that
same payment with sendWith. The wallet must support prepare/submit and
abortAction. Oversized header-only requests and multipart GET/HEAD requests
fail before broadcast; uncertain submission or delivery requires reconciliation
instead of another automatic spend. See the BRC-118 guide
for receiver-first rollout, limits, cancellation, raw-byte payloads and typed
PaymentTransportError outcomes. Nonempty non-multipart authentication remains compatible; empty byte bodies use
the BRC-104 -1 sentinel and require the matching auth middleware 2.3.0 receiver.
BRC-29 receipt derives the recipient's own child key (forSelf: true). Independent
sender/recipient wallet tests protect this distinction; the payer's sibling
output is not a valid payment to the recipient.
SDK 2.8.10 accepts full WhatsOnChain block headers with up to 64 own data properties, matching the existing header-list response bound. Normal provider metadata no longer causes valid mainnet Merkle proofs to fail a 16-property limit. Merkle-root matching, hash and height checks, HTTP limits, and rejection of accessors, symbols and inherited objects remain enforced. No API, wire, proof or wallet-data migration is required.
SDK 2.8.9 gives AuthFetch a finite binary payload budget matching its existing HTTP request and configured response capacity. A full 4 MiB CHIRP chunk no longer consumes the generic authentication envelope's JSON expansion budget before HTTP dispatch. Request framing remains capped at 16 MiB, configured response body limits remain enforced, and handshake, certificate, signature, nonce and redirect checks are unchanged. No API, wire or wallet-data migration is required.
The unpublished 4.0.0 candidate captures byte-array descriptor values once while validating and owning authenticated payloads. It avoids repeated copy validation and retaining a descriptor object for every byte of a large request. Dense-byte checks, payload capacities, signature bytes and response deadlines remain unchanged; no API, wire or wallet-data migration is required.
For signature payloads of at least 64 KiB, ProtoWallet uses asynchronous
platform SHA-256 when Web Crypto is available, avoiding long synchronous
hashing on browser UI threads. Unsupported or failed native hashing falls back
to the existing implementation using the same input snapshot. Short payloads,
explicit digests, signature bytes, and verification rules remain compatible.
No host registration or API migration is required. The additional portable
path measures 742,126 raw bytes in the SDK Vite fixture and 555,548 raw bytes
in UMD; their reviewed ceilings are 742,500 and 556,000 bytes respectively.
The combined sync and security candidate measures 560,560 raw bytes with esbuild;
its reviewed raw ceiling is 561,000 bytes. Compression ceilings are unchanged.
SDK 2.8.1 fixes portable AES-GCM decryption of authenticated empty plaintext. Encryption bytes and full 16-byte tag verification are unchanged; invalid tags, keys and IVs remain rejected.
SDK 2.8.2 separates wallet discovery timeouts from normal operations.
Automatic React Native and XDM discovery remains bounded, while subsequent
calls can wait for user approval without inheriting the one-second/200-millisecond
probe deadline. Explicit substrate responseTimeout values remain enforced.
The 2.8.3 candidate preserves the configured BRC100 originator in automatic
HTTP WalletWire discovery and binds the browser's default JSON fetch receiver.
It also restores negative listActions net amounts using their historical signed
int64 wire bytes, matching existing JSON validation. Counts, lengths and individual
output values remain unsigned and bounded.
Applications affected by these client defects can update their bundled SDK
without changing calls. Wallet upgrades continue to support the existing BRC100
contract; an ecosystem-wide application migration is not required. No API, wire
or account-data migration is required. These compatibility fixes are also included in the unpublished 3.0.0 candidate.
Action history compatibility
The 2.8.4 candidate accepts empty stored listActions descriptions and empty
basket names, as returned by established wallets for generated change and
unassigned outputs. It preserves those values rather than inventing metadata.
Nonempty descriptions retain their 5–2,000 UTF-8 byte bounds, and basket names
retain their 300-byte ceiling. Required scripts, label binding, transaction
identifiers, monetary values and new-action request validation are unchanged.
Affected SDK clients can update without changing their BRC100 calls; wallet
upgrades do not require an ecosystem-wide application migration. No wire or
account-data migration is required. Publication uses the protected npm workflow.
HTTP header compatibility
The 2.8.5 candidate raises authenticated HTTP header capacity by 4x in both request and signed-response handling:
| Limit | Previous | 2.8.5 |
|---|---|---|
| Ordinary header value | 8 KiB | 32 KiB |
| Aggregate header names and values | 64 KiB | 256 KiB |
| Header count | 128 | 512 |
| Individual header name | 256 bytes | 1 KiB |
| Requested-certificate policy header | 64 KiB | 256 KiB |
BRC-105 x-bsv-payment request headers may use the full aggregate budget,
including their name and other request headers. This accommodates larger
Atomic BEEF proofs without truncating or changing their bytes. The separate
certificate-policy limit applies before JSON parsing. Finite limits remain;
wire framing, response-body limits, deadlines and signature validation are
unchanged. The response-frame overhead allowance increases from 128 KiB to
512 KiB to carry the larger headers alongside even a small configured body limit. Server, proxy and fetch-runtime limits still apply independently;
operators accepting larger proofs should verify the full HTTP path.
No BRC100 call, public API, wire or wallet-data migration is required. Affected applications can update their SDK without changing calls; existing conforming applications remain compatible with upgraded wallets. Publication is a separate protected workflow step.
Fresh authentication byte ownership
Authentication byte ownership captures each external array element through its own data descriptor once. Shape validation then checks values in the private arrays produced by the completed bounded snapshot traversal. Sparse arrays, accessors, invalid byte values and all size, depth and node limits retain their existing refusals. Every operation constructs fresh owned data; no caller input or validation verdict is cached. Public declarations, wire bytes, signature and session checks, errors and defaults are unchanged. No consumer migration is required. Complete composed qualification remains required; this implementation change alone establishes no performance improvement.
Authenticated transport failure evidence
Authenticated fetch network failures retain their original thrown value in the
wrapper's optional Error.cause, including Errors from another runtime realm.
The existing diagnostic message, Error name and stack behavior remain compatible.
Cause inspection does not authenticate a seller decision or authorize replay or
payment. Keep protected error details private and reconcile uncertain financial
outcomes through the original durable operation.
Transport-owned general payload policy
SDK 2.8.5 adds an optional seventh Peer constructor argument,
AuthMessageValidationOptions, also accepted as the second argument to
snapshotAuthMessage. maxGeneralPayloadBytes may be a positive safe integer
for a separate general-message payload budget, or null to delegate payload
capacity to the transport. Omission preserves the prior aggregate message
budget. The setting is local configuration and is never taken from a peer's
message; Peer snapshots it when constructed.
const peer = new Peer(wallet, transport, undefined, undefined, undefined, undefined, {
maxGeneralPayloadBytes: null
})
Delegation excludes only the top-level general-message byte payload from the SDK message-size accounting. Metadata budgets, dense byte validation, owned snapshots, signatures, session identity, nonce/replay handling, and handshake and certificate-message validation remain. Configure HTTP server and edge capacity before delegating. The HTTP SDK client's own request/response bounds still apply independently.
Authentication middleware 2.2.8 requires SDK 2.8.5 and selects this transport
policy itself, so its received payment headers do not hit a hidden SDK envelope
budget. Custom ExpressTransport/Peer integrations should select the same
policy when the HTTP layer owns payload admission.
Table of Contents
- Objective
- Getting Started
- Features & Deliverables
- Documentation
- Development and Distribution
- Contribution Guidelines
- Support & Contacts
Objective
The BSV Blockchain Libraries Project aims to structure and maintain a middleware layer of the BSV Blockchain technology stack. By facilitating the development and maintenance of core libraries, it serves as an essential toolkit for developers looking to build on the BSV Blockchain.
Getting Started
Package entry points
The SDK3 retirement candidate removes identity/DIDTokenValidation; use the
identity/DID/VC migration guide
for the identity-key DID and original BRC52 envelope replacements.
@bsv/sdk/umd is an ESM entry that installs globalThis.bsv with the classic
bundle's export descriptors and re-exports the canonical SDK constructors.
@bsv/sdk/umd.ts supports ESM and CommonJS through the existing wildcard.
The explicit ./umd condition remains import-only. The standalone
dist/umd/bundle.js keeps its classic-script interface. These packaging fixes
preserve its bytes after the intentional DID-token retirement; they do not
create a second module class graph. Importing the global facade retains all
SDK exports, so its size is measured separately from selective module imports.
Cold BasePoint/JacobianPoint leaf entries retain their initialization wrappers
and original class identity in Node and browser bundlers.
Installation
To install the SDK, run:
npm install @bsv/sdk
Basic Usage
Here's a simple example of using the SDK to create and sign a transaction:
import { PrivateKey, P2PKH, Transaction, ARC } from '@bsv/sdk'
const privKey = PrivateKey.fromWif('L5EY1SbTvvPNSdCYQe1EJHfXCBBT4PmnF6CDbzCm9iifZptUvDGB')
const sourceTransaction = Transaction.fromHex(
'0200000001849c6419aec8b65d747cb72282cc02f3fc26dd018b46962f5de48957fac50528020000006a473044022008a60c611f3b48eaf0d07b5425d75f6ce65c3730bd43e6208560648081f9661b0220278fa51877100054d0d08e38e069b0afdb4f0f9d38844c68ee2233ace8e0de2141210360cd30f72e805be1f00d53f9ccd47dfd249cbb65b0d4aee5cfaf005a5258be37ffffffff03d0070000000000001976a914acc4d7c37bc9d0be0a4987483058a2d842f2265d88ac75330100000000001976a914db5b7964eecb19fcab929bf6bd29297ec005d52988ac809f7c09000000001976a914c0b0a42e92f062bdbc6a881b1777eed1213c19eb88ac00000000'
)
const version = 1
const input = {
sourceTransaction,
sourceOutputIndex: 0,
unlockingScriptTemplate: new P2PKH().unlock(privKey)
}
const output = {
lockingScript: new P2PKH().lock(privKey.toAddress()),
change: true
}
const tx = new Transaction(version, [input], [output])
await tx.fee()
await tx.sign()
await tx.broadcast()
For a more detailed tutorial and advanced examples, check our Documentation.
Script ASM
Script.toASM() includes the top-level OP_RETURN of a script read from
bytes. Ordinary data pushes still use plain hex. For example,
OP_0 OP_RETURN 6869 encodes as 006a026869.
If ordinary ASM would lose bytes in the suffix, such as an incomplete push or
a longer-than-needed push encoding, toASM() prints the entire suffix as a
single final 0x<hex> token immediately after the top-level OP_RETURN.
Script.fromASM('OP_0 OP_RETURN 0x02ab') produces 006a02ab byte for byte.
The raw token requires a nonempty, even number of hex digits.
Script verification
Spend accepts explicit verifyFlags for applications that know the spending
block's flags and the source output's era. The default JavaScript interpreter
does not know either height, so its version-based behavior is not a substitute
for node consensus validation. Transaction.verify() uses that default when no
optional verification backend is selected.
OP_NUM2BIN sizes above the node's signed 32-bit limit are invalid. There is
no default local allocation cap. Callers evaluating untrusted scripts can pass
an optional finite memoryLimit to bound local work before allocation.
ScriptResourceLimitError means the local evaluator did not complete, rather
than that the script is invalid.
Features & Deliverables
Sound Cryptographic Primitives: Secure key management, signature computations, and encryption protocols.
Script Level Constructs: Network-compliant script interpreter with support for custom scripts and serialization formats.
Transaction Construction and Signing: Comprehensive transaction builder API, ensuring versatile and secure transaction creation.
Transaction Broadcast Management: Mechanisms to send transactions to both miners and overlays, ensuring extensibility and future-proofing.
ARCsnapshots its URL, credentials, callback settings, deployment ID, and own custom headers when it is constructed. Reconstruct the broadcaster to rotate those values; later mutation of the supplied configuration has no effect. Custom headers must have valid HTTP token names and bounded, control-free string values. An injectedHttpClientis application-trusted code and can select different transport behavior than the SDK defaults. Provider responses remain untrusted: single and batch acknowledgements must name the exact submitted transaction and a recognized ARC state before the SDK returns success.The Block Headers Service and What's On Chain trackers likewise accept only canonical roots, bounded heights, own-data provider records, and an exact confirmation for the requested root and height. Their configuration and API credentials are snapshotted at construction. A caller-supplied Block Headers Service URL and any injected
HttpClientare explicit application trust decisions. Teranode's submission protocol supplies status rather than a returned transaction ID, so a successful HTTP status is authoritative only to the extent that the caller trusts the selected Teranode endpoint.Merkle Proof Verification: Tools for representing and verifying merkle proofs, adhering to various serialization standards.
BUMP transaction offsets retain their exact nonnegative safe-integer domain, including positions above 32 bits. Root calculation, proof extraction, combination, and trimming use the same full-width arithmetic. Offsets outside that domain are rejected; no new wire format or application migration is needed.
Serializable SPV Structures: Structures and interfaces for full SPV verification.
Secure Encryption and Signed Messages: Enhanced mechanisms for encryption and digital signatures, replacing outdated methods.
P2P Authentication: Robust peer-to-peer authentication mechanisms to ensure secure connections between parties.
Authenticated HTTP handshakes register their response waiter before sending, and each authenticated request has a bounded 30-second response window. A client retains at most 1,000 pending authenticated requests. Invalid or rejected peer responses reject and clean up the owning request; they do not become unhandled process errors or leave listeners behind.
Authenticated HTTP responses are streamed into a bounded buffer before they enter the signed-message parser. Application bodies default to 16 MiB and handshake bodies to 1 MiB; pass
maxResponseBytesormaxHandshakeResponseBytesinSimplifiedFetchTransportOptionswhen a deployment needs a different ceiling. The parser also bounds header count and bytes and rejects truncated, overlong, or trailing wire data.For BRC-105 payments, a recipient may include the optional
x-bsv-payment-known-txidsresponse header on its 402 challenge. The value is a comma-separated list of 64-character hexadecimal transaction IDs the recipient already possesses and has validated.AuthFetchpasses at most 256 unique lowercase IDs to the wallet's preparedcreateActionoptions. Changed payment requirements stop retries and require reconciliation. This lets compatible wallets omit known ancestors from payment BEEF. Whitespace, duplicates, and malformed entries are ignored; an absent or invalid-only header preserves existing payment behavior. Browser services must expose the optional response header through their existing CORS policy. The header is an optional SDK extension, not a standardized BRC-105 header.Identity: Comprehensive identity management system supporting identity verification and certificate management.
IdentityClient.resolveByAttributes({ attributes: { any: query } }, true)searches saved contact names and keys with case-insensitive substring matching. Named contact selectors retain exact case-insensitive matching. All supplied selectors must match; empty or malformed selectors never match a contact. Sequential mode retains the contact-hit shortcut;parallel: trueincludes matching contacts alongside fresh public results, with one local override per matching identity key. Contacts are personal assertions, not proof of a third-party certification.Contacts are disabled by default. Existing boolean and object callers retain their contact-error behavior. Search UIs can opt into bounded contact recovery:
const identities = await client.resolveByAttributes( { attributes: { any: query } }, { useContacts: true, contactErrorMode: 'fallback', contactTimeoutMs: 2000, onContactError: () => showContactWarning() } )Fallback uses a two-second contact deadline unless overridden by an integer from 1 to 60000 milliseconds. It continues public discovery after a contact error or timeout and preserves public-discovery errors and certificate checks. The same options work with
resolveByIdentityKey. A deadline bounds this call's wait; it cannot cancel a wallet request or dismiss its permission prompt. Render an error separately from a successful empty result, and use the callback for a partial-result warning. Callback exceptions propagate. Omit recovery options to retain strict legacy behavior; omituseContactswhen contacts are unnecessary. The options require this SDK candidate; upgrading a wallet does not upgrade an application's bundled SDK or its React search component.Key Value Store: Distributed key-value store for decentralized data storage and retrieval.
Identity publication rejects a certificate unless its certifier signature
verifies affirmatively. GlobalKVStore treats overlay responses as untrusted:
it requires a canonical, bounded controller-signed token whose locking key is
derived from the claimed controller, binds the exact BEEF output to the lookup
selector, and rejects ambiguous unique lookups or failed overlay acknowledgments.
Optional history follows only the selected controller's exact spent-output
lineage, excluding sibling outputs and unrelated funding ancestry. The configured
lookup resolver remains authoritative for which signed outpoints are current:
transaction inclusion and a field signature do not prove that an outpoint remains
unspent. Do not use a remotely resolved current value as the sole basis for an
authorization decision without independently verifying fresh active-state evidence.
LocalKVStore likewise authenticates the exact wallet-listed BEEF output,
wallet-derived locking key, and field signature before reading or spending it.
Distributed Storage: Scalable and secure distributed data storage solutions to support blockchain applications.
StorageDownloadertreats overlay advertisements as untrusted. It requires the canonical six-field UHRP PushDrop token, host signature and derived locking-key linkage, exact requested hash, non-expired metadata, bounded ordinary or Atomic BEEF tied to the advertised output/transaction, and a credential-free public HTTPS location. Ordinary BEEF remains supported for existing lookup services; an additive transaction-ID hint, when supplied, is required to select the exact transaction in that bundle. The reusabledecodeAndVerifyUHRPAdvertisement()export applies the same public-token validation for overlay and service implementations.Node.js public-network fetch helpers resolve, reject private/special-use addresses, and pin the approved address into the connection. Browser runtimes do not expose DNS resolution or connection pinning to JavaScript, so their fallback can validate URL syntax and literal IPs only. Browser applications must enforce private-network egress at a trusted proxy or service boundary; URL validation alone is not DNS-rebinding protection.
Wallet Interface: Standardized interface for wallet operations, supporting multiple cryptocurrencies and protocols.
A BRC-100 originator is permission-scoped by its lowercase DNS hostname. Callers may include a numeric port (including local-development ports), but the wallet deliberately treats every port on that hostname as the same originator. Schemes, credentials, paths, queries, fragments, IP literals, and malformed ports are not originator values.
Overlay Tools: Advanced tools for overlay network management and optimization.
The proposed BRC-192–194 extensions add explicitly selected output observations, progressive lookup representations, canonical protocol JSON, signed capability validation and endpoint construction.
parseOutputProposalPut,parseOutputProposalGetandparseOutputProposalFinalize, with their respective response parsers, enforce BRC-194's closed endpoint envelopes. Provider lifecycle state remains separate from the author's unchanged signed proposal. Parsing a packet checks its representation; it does not by itself authorize a source, validate a transaction or establish unspentness. Stateful orchestration and durable storage are implemented in the separate@bsv/output-knowledgepackage. Existing lookup and submission interfaces keep their current behavior.BRC-195/196 release helpers preserve that distinction for private acquisitions.
parseOutputReleaseEvidencechecks bounded representation and exact height arithmetic;bindOutputReleaseEvidencematches independently selected chain, transaction and policy.verifyOutputProcessorAcceptanceverifies the registered processor's exact BRC-77 statement. None proves mined inclusion, secret delivery or usability. See the release-evidence guide.OutputPurchaseProtocoladds closed preparation, submission, recovery and STEAK/POTATOES envelopes, seller-signed original-request terms and separately authenticated private-result bindings. Persist the verified original contract and exact transaction before dispatch; these codecs do not reserve, pay or durably admit an acquisition.OutputPurchaseTransportperforms one explicitly selected authenticated preparation, submission or recovery exchange, preserving the original signed terms, recipient, topic, domain and transaction binding. It rejects HTTP payment challenges. Restore the original durable owner before retrying; this finite transport does not allocate, sign, broadcast or persist a purchase, validate Script, or make delivered keys usable. See the purchase custody guide.OutputPrivatePublicationProtocoladds bounded protected-publication requests and semantic digests that exclude only alternate BEEF proof bytes.OutputPaidLookupProtocoladds frozen quote and recovery-state representations, exact amount/deadline checks and bindings to the original request, selected seller/rules and purchased output. Its unsigned quote and full response require authenticated transport; parsing does not internalize a payment or release a key.Protocol JSON maps have a null prototype and ordinary writable, configurable, enumerable own data fields, including keys that resemble object builtins. Parsing and canonical encoding enforce the same explicit byte and structural bounds; callers still validate each endpoint's closed schema. Canonical serialization creates a new private frame for each call, sharing closed module functions over an explicit per-call record. No frame is exposed to caller callbacks or retained after a call. Reentrant descriptor inspection and failed calls cannot reuse another frame's text, byte counter, bounds or ancestor set. Resource assertions retain their exact predicates and refusal messages. Validated safe integers use the same decimal text, including conversion of negative zero to zero. Program-value ownership completes this bounded canonical traversal before constructing a fresh graph from its generated text with native JSON parsing. A bounded private traversal selects null prototypes only on freshly created, unexposed records. Native parsing defines ordinary own data fields, including
__proto__, without invoking inherited setters. Caller objects never enter that traversal. Text-only serialization performs the same checks without constructing a graph. No input or verdict is retained between calls.Incoming JSON is lexically validated before native graph construction. Each object retains fresh decoded-key membership in a private Set; arrays retain an independent successful-value count. Duplicate keys are rejected before the map-size fence and before parsing their value. Collection sizes advance only after successful children. Every syntax, Unicode, safe-integer, resource and trailing-data check completes before native JSON parsing constructs the independently owned graph. A bounded private traversal selects null prototypes only on those newly created records. Dense arrays use direct iteration; records receive null prototypes before their own fields are traversed. This avoids intermediate values arrays without touching caller objects or inherited fields. Keys such as
__proto__remain ordinary writable, configurable, enumerable own data; inherited setters are not called. Caller objects never enter that traversal. The encoding inspector retains its independent canonical-byte check and flag. Canonical property ordering sorts each fresh primitive-name array with one captured UTF-16 comparator, including numeric-looking and supplementary keys. The bounded serializer checks every caller descriptor in canonical order before ownership construction. No input, shape, schema or validation result is retained between calls.createClosedOutputObjectValidator(required, optional)captures its field names once and validates each supplied object independently. Mutating the original field lists does not change that validator.closedOutputObjectcontinues reading mutable field lists afresh on each call. Internal fixed protocol schemas likewise own their field names and callback references; every field callback and complete input check still runs on each call. Mutable user-defined schema behavior is preserved. Only grammar is retained, never values, validation results, authorization or chain-currentness. Shared normalization selects the fixed immutable default limits only by exact primitive equality; different bounds remain freshly validated. Every supplied value still receives full normalization and schema checks. For program values, the schema layer constructs the same fresh data-only graph after every canonical byte fence, then discards the temporary generated text. Full-text ownership and canonical serialization retain their original outputs. Sorting fresh primitive names uses the fixed locale-independent UTF-16 comparator, including numeric-looking and supplementary keys (ECMAScript CompareArrayElements).String tokens are bounded before decoding. Escaped strings and raw controls receive native JSON syntax validation; unescaped strings are copied directly after token recognition. Both paths retain Unicode validation, duplicate-key rejection and the same errors, limits and encoding inspection.
parseOutputJSONWithStringRecords(input, limits)explicitly selects a fresh string-record path with the same complete parsing and ownership contract. OrdinaryparseOutputJSONretains its original path. The opt-in path proves flat unescaped string framing, controls, duplicate decoded names, map size, depth, Unicode and bytes before native construction. A local cursor follows grammar-proven quote boundaries, including when punctuation occurs inside names or values. Other shapes and refusals use the original parser/error order. Only fixed grammar is retained. Each graph is newly owned; endpoint schemas, bindings, authentication and currentness checks remain independent. The owned-record companion below preserves this shallow fast path; current native bindings select that companion. Existing consumers may retain this entry.outputStringretains its nonempty primitive, 1,024-code-unit and 1,024-byte UTF-8 limits. Fresh ASCII evidence establishes well-formed Unicode and one UTF-8 byte per code unit within the original primitive bound. Non-ASCII strings retain the same fresh surrogate refusal before native UTF-8 encoding and the byte check. A bounded scalar cannot reach the serializer's structural or 4 MiB limits. Complete packets still receive every recursive representation and schema check; no string or validation result is cached.Byte inputs reuse only a lazy, private UTF-8 decoder with fixed fatal and ignore-BOM options. Each complete, non-streaming decode resets decoder state, including after malformed UTF-8 (Encoding Standard). Lexical, duplicate-key, Unicode and resource checks still inspect every input; results remain independently owned. The parser still rejects a decoded BOM.
decodeOutputBytesretains canonical alphabet and padding syntax, the encoded allocation bound and decoded-byte limit. After those checks it validates the final sextet's unused bits directly: four zero bits with two padding characters, two with one. Decoded bytes and refusal order are unchanged; this avoids a complete re-encoding solely to verify padding. No byte value or verdict is cached. A strict absolute end-of-input assertion rejects trailing line terminators before decoding, after the original encoded allocation bound.Purchase and release parsers retain fresh complete normalization at both public and nested packet boundaries. Nested ownership also preserves canonical property order and zero representation when the original parent is raw JSON. Every closed-field, scalar and intrinsic arithmetic check runs on each call; signatures, caller-selected bindings, release acceptance and current authorization remain separate fresh checks. No normalization or validation result is cached.
ownOutputJSON(value, limits)validates a program value and returns its bounded canonicaltextand an independentvaluewith those same data properties and null-prototype records. Nested arrays and records belong to the new copy. It applies every canonical representation and resource check before copying. UseparseOutputJSONfor incoming JSON text or bytes, where duplicate decoded keys must still be detected; passing a string toownOutputJSONcopies that string value. Ownership supplies neither a schema decision nor authorization. Endpoint schemas and current capability checks still apply to each operation.inspectOutputJSONEncoding(input, limits)parses incoming text or UTF-8 bytes with the same duplicate-key, Unicode and structural checks and returns{ value, canonical }. It checks the original and canonical byte sizes while parsing, without serializing the parsed value again. The flag describes the original encoding; the independently owned value remains mutable. This is useful when an authenticated record must already have canonical encoding. It supplies no schema, signature, custody or authorization decision, and ordinaryparseOutputJSONcontinues accepting noncanonical valid JSON.inspectOutputJSONEncodingWithScalarRecords(input, limits)is an explicit companion with the same complete inspection and independent-ownership contract. Compact flat records of unescaped strings, safe decimal integers, booleans and null receive fresh whole-text grammar, controls, Unicode, duplicate-name, key-order, map/depth and byte checks. Each call constructs a new null-prototype graph. Other shapes, number spellings, escapes and all refusals retain the original lexical observer and error order with the already captured input and limits. Caller limits and byteLength are observed once. The owned-record inspector below preserves this shallow path and is selected by current native ledger bindings. Ordinary SDK inspection retains its existing path. No input, shape, secret, currentness, authorization or validation verdict is cached. This addition requires no existing consumer, wire or stored-data migration.canonicalOutputJSONWithInlineStrings(value, limits)is an explicit serialization companion with the original canonical bytes, fresh validation and refusal order. Its per-call record walker emits unescaped ASCII string fields directly; Unicode, escaping, arrays and other scalar values retain the original checks. Descriptors are captured once in the same order, including proxies; cycles, plain prototypes, hidden/accessor/symbol fields, UTF-16 key order and all resource bounds remain enforced. The recursive record companion below is selected by current native serialization bindings; this earlier opt-in companion remains available. OrdinarycanonicalOutputJSONstays unchanged. No input, shape, graph, secret or verdict is cached, and no stored-data or consumer migration is required. Runtime qualification remains separate from this implementation choice.retainOutputCapability(manifest, request)validates a new selection and returns{ record, selection }as independent owned copies. Atomically persistrecordwith the operation before any effect.restoreOutputCapability(record, trust)verifies the saved signed manifest at its original selection time, with the original freshness policy and caller-supplied endpoint, provider identity, chain, service, profile and installed rule validators. Manifest expiry alone therefore does not abandon an existing recovery obligation. It never substitutes today's discovery contract or grants permission to start a new operation.The
output-capability-retention/1record is bounded local replay material, not a network request or authorization token. Storage integrity protects its local time and policy; the provider signature covers the manifest itself. Never accept a caller-supplied record as saved host state. Recheck current caller access and the operation's recovery/session deadline before disclosing data or performing work. Endpoint/key migration needs separately verified authority. Neither helper makes network requests, runs remote code, persists data or calls a wallet.OutputLookupTransportexecutes BRC-193open,readandcloseagainst one retained contract. Construct it with{ contract, trust, wallet };trustis the same recovery binding used byrestoreOutputCapability. A wallet is required only for the selectedbrc103authentication mode. The transport owns its contract and each request before asynchronous work. It appends endpoint suffixes to the complete base path, refuses redirects and cookie credentials, setsCache-Control: no-store, pins the selected authentication identity and verifies the signed capability/profile echoes. It never invokes BRC-105 payment or downgrades authentication. Explicit publicnoneprofiles use ordinary HTTPS and bind source scope to its origin. Local HTTP needs trusted development opt-in.Capture a fresh capability and persist a randomly generated opening request ID with the complete opening request before calling
open. A retained contract can retry that opening or continue its existing session after manifest expiry; it does not authorize a new opening under an expired contract. Forread, supply the previous durably committed batch and requested limits. The transport validates session, scope, fixed deadlines, negotiated limits and snapshot/live continuity, but cannot inspect your checkpoint store. Commit every returned observation group and its cursor together before issuing the next read. It neither saves nor advances cursors automatically, and never converts a reset, expiry, malformed response or service failure into empty successful data.outputLookupCheckpoint(batch)creates an owned compact continuity boundary containing the scope, phase, watermarks, session/cursor and fixed deadlines. Store that boundary in the same transaction as the complete groups; it does not replace their durable receipt.parseOutputLookupCheckpointvalidates restored metadata, andreadCheckpointresumes directly from it. This avoids storing evidence twice or fabricating a previous wire response during recovery. A valid checkpoint representation alone proves neither authentication nor a storage commit. Extensions requiring additional local state must retain it too.Complete transmitted UTF-8 bytes, including whitespace, count against response limits before decoding. The separate 4 KiB error budget still applies to tiny page requests.
OutputLookupServiceError.packetpreserves validated retry and capacity hints. BRC-104 authenticates the body, not its MIME label: strict JSON decoding also supports the existing middleware'sapplication/octet-streamresponse label. Content encoding must be absent or identity. The transport checks 16 KiB of HTTP header fields exposed by Fetch; browsers can hide fields and add their own, so the server/proxy must also enforce the complete wire-header bound and expose the required authentication and selection headers through CORS.Calls accept an
AbortSignal. The total deadline covers authentication, HTTP and body consumption (default 30 seconds, configurable up to 30 seconds). One request is active per instance. Cancellation returns promptly, but a non-cancellable wallet or injected Fetch operation keeps its capacity until it settles; later work cannot silently accumulate or dispatch after cancellation. Each authenticated call uses an isolated AuthFetch session. This trades another handshake for independent cancellation and avoids changing existing AuthFetch defaults.closeremains available after session expiry once pending I/O ends. This transport is a component, not a durable live service or checkpoint store; their complete integration and application demonstration remain in progress.parseOutputServiceErrorvalidates the common packet-service error envelope and its separate 4,096-byte budget;outputServiceErrorHTTPStatussupplies the exact BRC-193 status mapping. Capacity details are accepted only forlimited, with positive minimums bounded by the profile's hard maxima. Errors contain no successful cursor. Verify selected response authentication before acting on an error, and never interpret an unknown response or HTTP 402 as empty data or an instruction to pay. Local cancellation and localrevision-unavailableremain local failures; a service reports lost replay continuity asreset-required.For an unpaid authenticated request, pass
allowPayments: falsetoAuthFetch.fetch. It returns an authenticated 402 without creating a payment, and retains the explicit opt-out across authentication recovery even if the caller later changes its options. The default remains automatic BRC-105 payment under the configured wallet's authorization policy. Ordinary HTTP fallback failures retain their existing error behavior. This option controls payment; it does not itself establish the required provider identity or profile selection.For private requests, set
requireMutualAuth: trueto disable ordinary HTTP fallback. When the provider is known, setexpectedIdentityKeyto its canonical compressed public key; this implies required authentication, pins the handshake before application data is sent, and checks the authenticated response sender. A conflicting cached identity is rejected without silently rebinding the origin. These restrictions survive session recovery and later caller option changes. Omitted options preserve existing behavior. Mutual authentication does not encrypt application data: use HTTPS in production. Pinning authenticates the peer, not the application capability/profile; verify those bindings separately.const response = await authFetch.fetch(serviceUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(query), expectedIdentityKey: selectedProviderIdentity, allowPayments: false })Distributed Protocol and Certificate Registration: Efficient systems for registering and managing distributed protocols and certificates.
Documentation
Comprehensive documentation is available in several formats:
- Online Documentation: Our complete documentation:
- Get Started: Step-by-step lessons to learn by doing
- How-To Guides: Practical solutions to specific problems
- Reference: Complete technical specifications and API documentation
- Architecture: Architecture and design explanations
- Examples: Practical code examples
- Code Annotations: The SDK is richly documented with code-level annotations that show up in editors like VSCode
Development and Distribution
The workspace requires Node.js 24.11 or newer and pnpm 10. Install from the repository root, then run the SDK's complete contract:
pnpm install
pnpm --filter @bsv/sdk format:check
pnpm --filter @bsv/sdk lint
pnpm --filter @bsv/sdk typecheck
pnpm --filter @bsv/sdk test:coverage
pnpm --filter @bsv/sdk pack:check
pnpm --filter @bsv/sdk test:browser
pnpm --filter @bsv/sdk test:resource
test:resource is not part of the PR suite: it allocates more than 500 MiB to
verify the AES-GCM 2^32-bit length boundary. Run it only on a suitable isolated
machine and record release evidence when AES-GCM length handling changes.
pack:check installs the exact generated tarball into ESM and CommonJS
consumer projects and verifies public exports and conditional type resolution.
test:browser independently bundles that tarball with Vite and esbuild,
rejects Node/server dependencies, validates source maps, and enforces measured
raw, gzip, and Brotli budgets. The package publishes ESM, CommonJS, and a
classic UMD bundle; TypeScript declarations are selected through matching
conditional exports.
Publishing is performed only by the repository release workflow after these checks pass. Local development and validation must not rewrite versions or publish artifacts.
Contribution Guidelines
We're always looking for contributors to help us improve the SDK. Whether it's bug reports, feature requests, or pull requests - all contributions are welcome.
- Fork & Clone: Fork this repository and clone it to your local machine.
- Set Up: Run
pnpm installat thets-stackrepository root. - Make Changes: Create a new branch and make your changes.
- Test: Run the package checks listed in Development and Distribution.
- Commit: Commit your changes and push to your fork.
- Pull Request: Open a pull request from your fork to this repository. For more details, check the repository contribution guidelines.
For information on past releases, check out the changelog. For future plans, check the roadmap!
Support & Contacts
Project Owners: Thomas Giacomo and Darren Kellenschwiler
Development Team Lead: Ty Everett
For questions, bug reports, or feature requests, please open an issue on GitHub or contact us directly.
License
TS Stack first-party material is under the Apache License 2.0. Incorporated material remains under the separate terms identified in THIRD_PARTY_NOTICES.md, with complete texts in LICENSES/. Keep all three payloads with source and binary distributions.
Thank you for being a part of the BSV Blockchain Libraries Project. Let's build the future of BSV Blockchain together!
Certificate policy and observer callbacks
SDK 3.0 records the locally requested certificate policy for each BRC-103 session. Standalone responses must fit one complete locally recorded dynamic request allowlist or the session's handshake allowlist. Policies are copied before sending, so a later edit of the caller's object does not change validation. Responses never select their own validation policy. A different dynamic request cannot satisfy an unmet handshake requirement.
The legacy v0.1 RequestedCertificateSet has no all-of, any-of, threshold, or
optional-field expression. Compatibility validation therefore proves only that
each supplied certificate and each non-empty disclosed-field subset is allowed
by one locally recorded set. It does not prove that every listed certificate
type or every requested field was supplied. Each party chooses what to request,
what to provide, and how much to disclose. Before granting access, inspect the
actual certificate types, certifiers, and decrypted fields and enforce the
application's complete authorization policy. Terminate or constrain the
session or operation when those actual disclosures are insufficient; peer
authentication never declares the claims sufficient for the application.
The v0.1 AuthMessage fields, signatures and encodings are unchanged. Because a certificateResponse does not echo the request nonce, concurrent responses are matched against complete local requested sets, not individual request IDs. A successful dynamic response consumes one matching request; failed validation keeps it available for retry. Request the intended set explicitly instead of relying on unrequested certificates.
An initialRequest is unsigned, and the v0.1 initialResponse signature binds
the nonce pair and identity but not its requestedCertificates or
certificates members. Built-in wallet proving encrypts revealed field keys to
the requested identity, but a listenForCertificatesRequested callback can
observe only a claimed identity during the initial exchange. Do not disclose
plaintext or authorize side effects from that callback. Because the requested
set is mutable, make every decision from the certificates and fields actually
disclosed and validated, never from the request alone. Prefer wallet-backed
proof creation, and use a signed post-authentication certificate request or an
application-layer integrity check when request integrity itself matters.
listenForCertificatesReceived is an observer. The SDK commits certificate
validation and releases its waiters before invoking listeners. A throwing or
rejecting listener stops later listeners and rejects message handling, but does
not roll back validation. The callback's third argument is the local session
nonce and its optional fourth argument is the peer nonce, allowing adapters to
bind application approval to the exact validated exchange; existing two-argument
callbacks remain compatible. Apply the requested certificate policy and
explicit application authorization before performing protected work.
When a peer's initialResponse requests certificates, Peer answers after it
has validated the peer's certificates and run these listeners, so a listener
that throws prevents that disclosure. Until the answer has been sent or has
ended without one, toPeer on that session waits, at most 30 seconds. While
the session's certificates-received listeners run, its sends are not held, as
before, so a listener can send without waiting for the answer that follows it;
such a message precedes the answer. When the wallet holds
no requested certificate, nothing is sent unless the Peer options or the
AuthFetch options set sendEmptyCertificateResponses: true. Enable it only
for servers that accept an empty answer: @bsv/auth-express-middleware replies
400 ERR_CERTIFICATES_REQUIRED.
Custom AsyncSessionManager implementations must retain the complete
PeerSession, including the optional local certificatePolicy and
pendingCertificateRequests fields. They are never serialized into AuthMessage.
Peer serializes its own certificate read-modify-write operations; shared stores
must also coordinate writers across instances. Older stored sessions without
these fields use the configured handshake policy.
BRC-103 message nonces are one-time values. The in-process SessionManager
atomically consumes each verified signed nonce, retains at most 10,000 sessions
for 30 minutes of idle time by default, and caps replay claims per session. At
capacity it evicts only unauthenticated sessions; if every slot is
authenticated, new handshakes fail until a session expires or is removed.
Session reads validate only the addressed session or identity bucket, avoiding
a global scan on every authenticated message. The unsigned initial-request
replay cache is also bounded; at capacity it evicts its oldest claim instead of
letting unauthenticated traffic globally disable new handshakes. Replay
protection for those unsigned requests is therefore bounded by both the
configured idle lifetime and cache cardinality. Signed per-session message
nonces continue to fail closed at their configured cap.
Shared AsyncSessionManager implementations must provide an atomic
claimMessageNonce and claimInitialRequestNonce backed by uniqueness
constraints or compare-and-set; Peer fails closed when an asynchronous store
omits either operation. Their unsigned initial-request cache should likewise
apply global and identity-scoped bounds, evicting the oldest claim at capacity
instead of failing all new handshakes. An incoming initialRequest only claims
an identity and creates a partial session. The requester becomes authenticated
only after a valid signed follow-up proves control of that key. Exact
initial-request replay is rejected before session, wallet, or callback work.
When Peer is allowed to remember a destination, only a successful locally
initiated handshake updates that implicit destination. Inbound messages cannot
retarget a later call that omits identityKey.
These controls authenticate peers and protect message integrity and freshness; they do not encrypt the transport. Applications must use a confidential transport such as correctly verified TLS and must separately authorize the authenticated identity for every protected operation.
verifyNonce reports a boolean. A wallet HMAC mismatch (ERR_INVALID_HMAC,
or an error whose message is exactly HMAC is not valid) is false, not a
rejection. Other wallet failures still reject. Peer treats false as an
authentication failure so a server can return 401 and the client can replace a
stale session. A true result still does not prove freshness or single use.
Callers that previously used a thrown ERR_INVALID_HMAC as the invalid-nonce
signal must branch on the returned boolean.
Revenue listing script codec
The optional BRC-197 exemplar is under pre-adoption replacement by BRC PR295.
@bsv/sdk/script/templates/RevenueListingProfile supplies its portable two-stage
codec: both literal programs are pinned, stage choice is explicit, and the shared
717-byte metadata binds the immutable schedule, public children and mandatory
expiry. See the profile guide.
RevenueListingProfilePlan and RevenueListingProfileSpend separately plan
exact outputs and construct funded 114/15-value witnesses, requesting a protected
seller-child signature only for split or early retirement. Complete positive
transactions, all eight recipients and original property controls exercise these
components. Separately installed application and wallet companions compose fixed-child
native remittance, signed activation lineage, selected-chain expiry finality and
durable alias recovery. The current authenticated native fixtures exercise these
boundaries together. Earlier six-route codec and native receipts remain historical
compatibility evidence and do not qualify the current profile. See
specification alignment.
Conservative witness sizing uses the installed Script push encoder and preserves the existing fixed-program bounds. Funded construction separately checks header ranges, source evidence, mandatory outputs, monetary conservation, protected-child signatures and the completed transaction byte limit. Boundary regressions retain the original positive Script executions and 300-history property controls; complete current-source qualification remains required.
The unpublished SDK3.3 source candidate preserves the superseded RevenueListing,
RevenueListingPlan and RevenueListingSpend interfaces for existing consumers. Their earlier single-program/revision/six-route behavior is historical
and must not be used to construct or qualify the PR295 exemplar. A portable codec
recognizes bytes; it does not establish lineage, currentness, valid spending or
fulfillment. Checkpoint two remains open until the complete replacement is qualified.
Lineage, wallet integration and fulfillment are separate. Existing root imports remain unchanged.
The optional overlay funding helpers parse bounded BRC-195 payment headers and inspect the exact single BRC-29 payment output against a retained quote and independently derived seller key. They return a proof-independent wallet operation identifier; chain acceptance, acquisition reservation and durable wallet credit remain separate. See the private overlay release guide.
The optional OutputRootEvictionProtocol helpers parse and authenticate BRC-199
root requests/results, exact advertisement targets and independent restoration
bases. Their new-request clock check is separate from retained-outcome recovery.
They do not authorize suppression, verify BEEF, persist tombstones or guard
serving paths. See the root coordination guide.
Existing SHIP/SLAP, lookup and GASP behavior remains unchanged.
OutputRootEvictionTransport composes those contracts with bounded BRC-103/104
HTTP. Supply an integrity-protected original capability/request record, separately
retained policy digest, trusted root configuration and wallet. submit() retries
only that signed operation and status() derives its original key. Both require
the expected root identity, prohibit payment and validate results against the
original selection. Cancellation retains physical capacity until pending I/O
settles. Durable storage, polling, current server authority and serving decisions
remain separate; existing lookup transport APIs and defaults are unchanged.
The SDK3 candidate also adds OutputProposalTransport for one durably saved
BRC-194 put/get/finalize operation. Retries retain the original selected capability
and request, with mutual authentication, bounded delivery and no automatic payment.
Finalization reports whether a returned reservation matches that saved operation
and transaction. See the proposal guide
before adopting it; storage, current authority, domain acceptance and Bitcoin
verification remain separate responsibilities.
Explicit paid lookup operations
OutputPaidLookupTransport performs one selected-host BRC-195 quote, explicit
payment or original-acquisition recovery. It owns the original request and
retained contract, disables automatic AuthFetch payments, checks authenticated
challenge/result binding, and never constructs or persists a wallet action.
OutputPaidLookupServiceError preserves a validated service error packet.
Existing AuthFetch defaults are unchanged. See
paid lookup clients for response bounds,
recovery, private custody and the separate durable buyer responsibilities.
Locally authorized outputs in completed actions
completeBoundAction continues to reject an unrequested output funded by a
caller-supplied input by default. A caller may install
authorizeAdditionalOutputs(result) to return independently approved outputs,
each bound to an exact outputIndex, lockingScript, and satoshis. This is a
local policy decision: do not approve outputs merely because an untrusted wallet
labels them as change or a fee. Input-value conservation, requested-output
binding, input signing, and signed-template verification still apply.
For example, a local signer can retain its independently verified storage-policy
decision in a private WeakMap keyed by the exact createAction result:
await completeBoundAction(wallet, args, {
inputSigners,
authorizeAdditionalOutputs: result => verifiedLocalOutputs.get(result) ?? []
})
The new BOUND_ACTION_OUTPUT_AUTHORIZATION_VERSION export is 1. The existing function also exposes completeBoundAction.outputAuthorizationVersion=1.
Consumers supporting older SDK peers should detect that function property before supplying the new
option; older SDKs retain their existing strict behavior. This additive API is
included in the unpublished SDK 3.3 source candidate. The separate SDK3 identity migration
still applies; SDK2 applications need an additive backport or a coordinated SDK3
upgrade. No BRC-100 wire or wallet-data changes are introduced by this option.
The bounded parser owns a fresh private cursor frame for each input. Complete syntax, duplicate, Unicode, integer and resource checks precede exposure. Proven ASCII text has one UTF-8 byte per code unit; non-ASCII text retains native encoding. Byte-view inspection counts decoded bytes independently of an overridable byteLength property. These per-call calculations retain no input or validation result between operations.
ownOutputJSONWithInlineStrings(value, limits) is the explicit native ownership
companion to canonicalOutputJSONWithInlineStrings. It returns bounded canonical
text and an independent value, with null-prototype records and ordinary arrays.
Each call freshly checks descriptors, cycles, Unicode, safe integers, canonical
order and resource limits while assembling a private graph beside its canonical
text. Both results are exposed only after every check succeeds. Neither the
caller graph nor a normalized value, shape or verdict is retained between calls.
A string input remains a string value; incoming JSON text must use a parser to
preserve duplicate-key evidence. Ordinary ownOutputJSON is unchanged. Schemas,
authorization and currentness checks remain the responsibility of each operation.
parseOutputPurchasePrepareWithInlineStrings, parseOutputPurchaseTermsWithInlineStrings and parseOutputPurchaseSubmitWithInlineStrings explicitly select the existing fresh owned-copy implementation for object inputs. Terms retain the intrinsic recovery-deadline check; authentication and domain validation remain separate. Text and bytes retain the general parser. Ordinary purchase parsers, general normalization and digests keep their existing paths. The internal schema companion is also an additive deep-module export. Existing signatures, encodings and limits remain unchanged; no input, normalized value or verdict is cached. Native contract and alias bindings opt in; browser callers retain ordinary parsing by default.
Native purchase contracts explicitly select additive inline companions for historical capability restoration, packet digests and verification, and signed purchase terms. Capability parsing, selection and retention companions are available separately in the SDK; the native initiation method retains its existing binding. Each invocation owns and validates its complete input afresh. Historical capability restoration still checks the recorded selection time, original signature, selected endpoint, identity, chain, selector, installed rules and digest. Current caller authorization and actual operation deadlines remain separate checks. Ordinary SDK entry points, wire text and bytes, canonical encodings, resource limits, error identities and custody formats retain their existing behavior. No input, parsed packet, shape, secret, currentness or authority verdict is cached; only the existing bounded mathematical signature facts and fixed grammar are shared. This is an implementation choice with identical protocol semantics, not a new advertised protocol profile. Hosted property and full mutation qualification remain required.
The additive parseOutputJSONWithOwnedRecords and inspectOutputJSONEncodingWithOwnedRecords preserve the existing shallow string/scalar paths and construct independently owned records during complete lexical traversal of complex JSON. Duplicate decoded names, escaped Unicode, safe integers, framing, depth, item limits and refusal order retain the ordinary parser's rules. Each complete input is captured once. Arrays have ordinary own data fields and records have null prototypes. No partial graph escapes if a later syntax or resource check fails. Parsing preserves lexical negative zero; canonical ownership normalizes it exactly as the ordinary owner does. Encoding inspection describes this input only and supplies no schema, trust or operation authorization.
canonicalOutputJSONWithInlineRecords and ownOutputJSONWithInlineRecords extend fresh inline key/string emission through nested records and arrays. They preserve canonical bytes, descriptor observation order, prototype/symbol/cycle checks, Unicode, integers and exact resource bounds. The owner returns { text, value }; repeated input references become independent owned nodes. Frames are private to one complete call and failures expose no partial state. The earlier ordinary and opt-in entry points remain available. Current native bindings select counted value-only ownership where they consume only .value; callers requiring canonical text retain the full owner and serializer. Explicit schema companions use internal value-only ownership with the same byte bounds; verification still requests canonical bytes independently. Existing default entry points retain their paths. This changes neither a protocol profile nor a wire, custody or public interface contract. No input, parsed graph, shape, secret, authorization or currentness verdict is cached. Hosted qualification remains required; no performance improvement is claimed from source checks.
The explicit parseOutputPurchaseEnvelopeWithInlineStrings,
verifyOutputPurchaseEnvelopeWithInlineStrings and
verifyOutputPurchaseCommitmentEnvelopeWithInlineStrings companions extend fresh
owned-copy normalization through response and original-contract checking.
parseOutputPotatoesWithInlineStrings and
parseOutputPurchaseCommitmentBindingWithInlineStrings provide the corresponding
bounded representation boundaries. Release representations and caller-selected
bindings have parseOutputReleaseEvidenceWithInlineStrings and
bindOutputReleaseEvidenceWithInlineStrings. Each call checks the entire current
input, original signatures, policy and transaction association as applicable.
These functions retain no parsed graph, secret, authorization, currentness or
validation result between calls. They confer neither Bitcoin validity nor domain
eligibility. Ordinary entry points, encodings, error identities and resource
limits remain unchanged. Current private-purchase bindings select these companions
explicitly; historical recovery still verifies and returns the original signed
result. Source checks do not establish a performance improvement.
Explicit schema ownership now counts the complete canonical encoding without constructing composite text that the schema path discards. This internal traversal still checks every current descriptor, prototype, symbol, cycle, Unicode sequence, integer, depth, item count and byte boundary in the same order, and constructs independent ordinary-data arrays and null-prototype records. The full text/value owner and ordinary normalization remain available for their callers. It retains no input, normalized graph or verdict. This internal selection changes no wire, stored format, public root export or authority rule; hosted qualification remains required.
ownOutputJSONWithCountedRecords is an opt-in fresh owner returning { value }. It counts every canonical byte and preserves the full inline-record owner's descriptor/prototype/symbol/cycle/Unicode/integer checks, limits and refusal order, without constructing composite text. Arrays have ordinary own data fields and records have null prototypes; repeated nodes and later calls remain independent. Native private-state modules that consume only .value select this companion through imports. The protected-record codec and other callers that need canonical text retain the full owner and serializer. No input, graph, shape, secret, authorization or currentness verdict is cached. Existing APIs and defaults remain available; this changes no wire, persistence or authority rule. Hosted qualification remains required and no performance improvement is claimed.
The explicit purchase and release companions select fixed nested companion grammars for release policies, STEAK results and release evidence. They preserve nested JSON-text representations, duplicate-name refusals, complete fresh ownership and byte/depth limits, and every signature and original-request binding. The ordinary schemas and default entry points remain intact. Internal policy and STEAK helpers are deep-module exports only; no SDK root export is added. Fixed grammar reuse retains no supplied input, secret, authorization or validation result. Hosted qualification remains required; source checks establish no performance improvement.
Fixed nested companion grammars are instantiated lazily and retained as immutable validator configuration. Unused companion paths can be removed from browser bundles. This retains neither supplied input nor normalized data, secret or verdict; every call still owns and validates the complete current representation independently.
The explicit purchase/release parser owns and bounds the complete enclosing packet on every call. Fixed child grammars then validate that newly owned graph without repeating ownership of object subtrees. Embedded JSON text keeps its complete parser, including duplicate-name and resource checks. Intrinsic release arithmetic, signatures, digests, original-request bindings, custody and current authority remain separate fresh checks. Internal child validators require an already owned and bounded parent and are not standalone public packet parsers or SDK root exports. No input, partial graph, secret or validation/authority result is retained between calls. Existing default and standalone parsers retain their paths. Hosted property/mutation qualification remains required and no speedup is claimed from source checks.
Portable WithInlineStrings schema companions retain the general text/byte parser. Server callers can explicitly choose parseOutputPurchasePrepareWithOwnedRecords, parseOutputPurchaseSubmitWithOwnedRecords, parseOutputPurchaseTermsWithOwnedRecords, parseOutputPurchaseEnvelopeWithOwnedRecords, parseOutputPotatoesWithOwnedRecords, parseOutputPurchaseCommitmentBindingWithOwnedRecords and parseOutputReleaseEvidenceWithOwnedRecords. These additive parsers construct independently owned records during complete lexical traversal of text or UTF-8 bytes and use the same fixed packet grammars and intrinsic checks. Object inputs retain fresh counted ownership. Native server bindings select them through imports; the portable buyer and wallet entries retain their existing dependency paths. This selection adds no wire profile, persisted format, signature verdict or authority rule. Complete fresh syntax, decoded-name duplicates, Unicode, safe integers, depth and input-byte fences remain mandatory; ordinary parser entry points are unchanged. Canonical U64, Hex32, compressed identities, standard base64 and request IDs use strict end-of-input assertions so line terminators cannot be accepted as part of a canonical primitive. Valid canonical representations, defaults, wire bytes and signature/authority checks remain unchanged. No input, graph or verdict is cached. Hosted qualification is still required; source checks establish no speedup.
The additive canonicalOutputJSONWithDirectRecords emits canonical text directly from freshly inspected records and arrays. It validates the complete input on every call, observes each descriptor in canonical key order, and preserves ordinary canonical bytes, safe integers, Unicode rules, prototype and symbol refusals, cycle detection, and exact resource limits. It returns text only and retains no input graph, encoding, shape, secret or authority verdict. Native private-state serializers explicitly select it through import aliases; portable browser and wallet entry points retain their existing selections. Representation validation supplies no schema, signature, custody, authorization or currentness decision. Existing serializers remain available with their previous behavior. The new SDK property and refusal tests compare the selected emitter with those existing paths; hosted runtime and complete mutation qualification remain required before acceptance.
The explicit server purchase companions build their fixed grammar lazily with
createOwnedRecordSchema, an internal deep-module helper. Its complete normalizer
freshly owns and bounds the entire input before selecting private grammar
callbacks. Required and unknown fields and every scalar/domain predicate are
checked on every call. Fresh private data-only records need no second caller
prototype, symbol or descriptor inspection. Returned schema callbacks remain
ordinary standalone validators; custom callbacks retain their ordinary behavior.
Grammar metadata contains callbacks only. It holds no supplied input, graph,
shape, key material, authorization, currentness or validation result. Portable
parsers and buyer/wallet imports retain their existing paths. This adds no wire
profile, stored format, root SDK export or authority rule. Hosted behavior and
complete mutation qualification are required; static checks establish no speedup.
validateOutputByteEncoding(value, maximumBytes) returns the current canonical
standard Base64 string after validating its alphabet, framing, padding bits and
exact decoded-size bound. It avoids constructing a decoded array when a caller
only needs the encoded representation. Defaults, limit predicates and refusal
order match decodeOutputBytes; decoding retains its existing implementation.
The private fixed owned-record schema selects this validator only after fresh
complete parent ownership. Ordinary byte callbacks and portable parser paths
remain unchanged. This establishes representation only; endpoint schema,
transaction validity, signature, custody and current authorization still need
independent checks. No input or validation verdict is retained. The helper is an
additive SDK export and requires no wire or stored-data migration. Hosted
runtime and mutation qualification remain required; static checks establish no
performance improvement.
Pre-construction wallet reviews
The SDK accepts a storage pre-construction double-spend review through
HTTPWalletJSON only for createAction with explicit inputs. It requires one
empty attempted-TXID result, no constructed-action fields, and complete competing
transactions that spend those requested outpoints. Malformed, unrelated and
ID-only evidence remains invalid. The existing bounded retry helper synchronizes
the winning transactions before re-invoking the operation to read fresh state.
Use a wallet with the matching Toolbox parser fix. The binary wire format is
unchanged and cannot carry structured review evidence; choose a compatible
transport before financial operations rather than retrying an ambiguous failure.
No BRC-100 call or storage-schema migration is required.
Existing certificate compatibility
The 4.0.0 source candidate restores bounded historical certificate types through
existing listing, proof, discovery, relinquishment and authentication APIs. New
signing and acquisition still require exactly 32 type bytes. Legacy binary
operations require upgraded adapters at both endpoints, including registration
of the internal HTTP transport endpoint when using HTTPWalletWire; ordinary
encodings are unchanged. See the protocol and rollout contract.
HMAC key encoding
createHmac and verifyHmac use the ECDH shared point's X coordinate as a
minimal-length unsigned big-endian byte array, matching published SDK2/3.
Leading zero octets are omitted; zero is encoded as one zero octet. No
additional hash is applied. HMAC-SHA256's own block padding is unchanged.
There is one encoding for generation and verification. Existing tags and
persisted HMAC-derived identifiers remain reproducible. The fixed-width
encoding change from #1370 is backed out; no alternate mode or relaxed verifier
is provided. BRC-2 AES-GCM encryption retains its existing 32-byte key encoding.