@lemayinc/mtp
v1.0.0
Published
Massachusetts Transaction Protocol — TypeScript SDK. Reference implementation of the four MTP primitives (Offers, Requests, Terms, Receipts), seven protocol layers, deterministic CBOR serialization, MTP-UUID generation, and post-quantum cryptographic sign
Maintainers
Readme
@lemay/mtp
The Massachusetts Transaction Protocol — TypeScript SDK.
Reference implementation of the complete MTP protocol stack: four primitives, seven layers, deterministic CBOR serialization, MTP-UUID generation, and post-quantum cryptographic signing. 4,416 lines of strict TypeScript implementing MTP-SPEC-001 and MTP-BIND-001.
MTP is a universal transaction protocol governing any bounded interaction between two parties that produces a committed outcome. Not merely economic transactions — any exchange of value, data, computation, or obligation that requires structural trust guarantees rather than institutional promises.
Proprietary software. Curtis License™ v1.0. LeMay Inc.
The Four Primitives
Every MTP transaction flows through four primitives. These are the atoms of the protocol — irreducible, composable, and cryptographically sealed.
Offer — A provider's signed declaration of what they can deliver, at what price, under what terms. An Offer carries a validity window, geographic constraints, capacity limits, prerequisites, and non-negotiable provisions. It is the provider's commitment to the market.
Request — A consumer's signed declaration of what they need, subject to what constraints. A Request carries budget ceilings, latency requirements, accuracy thresholds, delivery deadlines, jurisdiction constraints, and an authority attestation proving the requester has the standing to transact. It is the consumer's demand signal.
Terms — The negotiated agreement between parties. Terms reference the originating Offer and Request, lock the price, delivery specification, quality requirements, dispute resolution method, settlement rail, and attribution method. Every participant must sign. Terms are the contract.
Receipt — Cryptographic proof of everything that occurred. The Receipt records the outcome (fulfilled, partially fulfilled, disputed, or failed), the verification method and evidence, partial fulfillment details if applicable, dispute initiation if warranted, failure classification, and attribution shares. The Receipt is the truth. It cannot be amended, redacted, or denied.
The Seven Layers
MTP implements a complete protocol stack. Each layer is independent, composable, and fully implemented in this SDK.
Layer 1 — Identity. Decentralized identifiers (did:mtp) generated from public key material. DID Documents with verification methods, service endpoints, and algorithm support profiles. Delegation certificates with scope and value constraints, chain validation, and revocation checking. Post-quantum algorithm negotiation between parties.
Layer 2 — Discovery. Capability Manifests published by providers declaring what they offer. In-memory and federated discovery indexes. Request-to-Offer matching with compatibility scoring. Offer revocation with cryptographic proof.
Layer 3 — Negotiation. Multi-round negotiation state machine with proposal, counterproposal, acceptance, and rejection. Configurable maximum rounds and timeout. Single-round accept shortcut for commodity transactions where the Offer's terms are accepted without modification.
Layer 4 — Commitment. Transaction Mandates created from agreed Terms. Multi-party signature collection. Conditional preconditions with expiration. State transitions from Pending through Active, Settling, and Completed. Mandate expiration checking.
Layer 5 — Settlement. Pluggable payment rail abstraction. Settlement adapters register with a central registry. Currency support querying. Settlement execution and reversal. The protocol does not prescribe a payment method — it abstracts all of them behind a single interface.
Layer 6 — Verification. Quality evaluation against agreed terms. Inference quality evaluation (accuracy, latency, format, model version). Physical delivery evaluation (condition, dimensions, weight). Automatic Receipt generation from evaluation results with fulfillment ratio computation.
Layer 7 — Attribution. Shapley value computation for multi-party transactions. Exact computation for coalitions of ten or fewer participants. Monte Carlo approximation with configurable sample count and error bounds for larger coalitions. Normalization to percentage shares. Signed attribution records.
Installation
npm install @lemay/mtpRequires Node.js 18 or later.
Quick Start
The following example demonstrates the complete transaction lifecycle: generating identities, creating an Offer, issuing a matching Request, negotiating Terms, and sealing the outcome with a Receipt.
import {
// Crypto
registerCryptoProvider,
CryptoProvider,
SignatureAlgorithm,
KemAlgorithm,
// Identity
generateDid,
// Primitives
buildOffer,
buildRequest,
buildTermsUnsigned,
addTermsSignature,
isTermsFullySigned,
buildReceipt,
// Types
DeliveryMethod,
SettlementTiming,
DisputeMethod,
ReceiptOutcome,
VerificationMethod,
ParticipantRole,
AttributionMethod,
} from "@lemay/mtp";
import { createHash, randomBytes } from "crypto";
// ──────────────────────────────────────────────
// Step 0: Register a CryptoProvider
// ──────────────────────────────────────────────
// MTP requires a pluggable cryptographic provider.
// This example uses a minimal HMAC-based provider
// for demonstration. Production deployments must
// supply a post-quantum provider (ML-DSA-65/87).
const demoCrypto: CryptoProvider = {
async generateSigningKeyPair(algorithm: SignatureAlgorithm) {
const priv = randomBytes(32);
const pub = createHash("sha256").update(priv).digest();
return { publicKey: pub, privateKey: priv, algorithm };
},
async sign(message: Buffer, privateKey: Buffer) {
const hmac = createHash("sha256")
.update(Buffer.concat([privateKey, message]))
.digest();
return hmac.toString("base64url");
},
async verify(message: Buffer, signature: string, publicKey: Buffer) {
// Demo: accept all signatures. Replace with real verification.
return true;
},
async generateKemKeyPair(algorithm: KemAlgorithm) {
const priv = randomBytes(32);
const pub = createHash("sha256").update(priv).digest();
return { publicKey: pub, privateKey: priv, algorithm };
},
async encapsulate(publicKey: Buffer) {
const shared = randomBytes(32);
const ct = randomBytes(64);
return { sharedSecret: shared, ciphertext: ct };
},
async decapsulate(ciphertext: Buffer, privateKey: Buffer) {
return randomBytes(32);
},
hash(data: Buffer) {
return createHash("sha256").update(data).digest();
},
async encrypt(plaintext: Buffer, key: Buffer) {
return { ciphertext: plaintext, iv: randomBytes(12), tag: randomBytes(16) };
},
async decrypt(ciphertext: Buffer) {
return ciphertext;
},
};
registerCryptoProvider(demoCrypto);
async function main() {
// ──────────────────────────────────────────────
// Step 1: Generate Identities
// ──────────────────────────────────────────────
const providerKeys = await demoCrypto.generateSigningKeyPair(
SignatureAlgorithm.ML_DSA_65
);
const consumerKeys = await demoCrypto.generateSigningKeyPair(
SignatureAlgorithm.ML_DSA_65
);
const providerDid = generateDid(providerKeys.publicKey);
const consumerDid = generateDid(consumerKeys.publicKey);
console.log("Provider DID:", providerDid);
console.log("Consumer DID:", consumerDid);
// ──────────────────────────────────────────────
// Step 2: Create an Offer
// ──────────────────────────────────────────────
const offer = await buildOffer(
{
agent_id: providerDid,
value_type: "inference.text_generation",
description: {
human: "High-accuracy text generation inference service",
machine: { model: "sovereign-llm-v1", context_window: 128000 },
},
terms_template: {
price: { amount: 0.002, unit: "USD" },
delivery: {
method: DeliveryMethod.SYNCHRONOUS,
max_latency_ms: 5000,
},
quality: { accuracy: 0.95, format_compliance: 1.0 },
settlement: {
rail: "mercury",
timing: SettlementTiming.IMMEDIATE,
},
},
validity_window: {
not_before: new Date().toISOString(),
not_after: new Date(Date.now() + 86400000).toISOString(),
},
},
providerKeys
);
console.log("Offer ID:", offer.offer_id);
// ──────────────────────────────────────────────
// Step 3: Create a Request
// ──────────────────────────────────────────────
const request = await buildRequest(
{
agent_id: consumerDid,
value_type: "inference.text_generation",
description: {
human: "Need text generation for document analysis",
machine: { task: "summarization", max_tokens: 4096 },
},
constraints: {
max_latency_ms: 5000,
accuracy_threshold: 0.9,
budget_ceiling: { amount: 1.0, unit: "USD" },
},
authority_attestation: {
principal: consumerDid,
scope: "inference.text_generation",
max_transaction_value: { amount: 1.0, unit: "USD" },
},
},
consumerKeys
);
console.log("Request ID:", request.request_id);
// ──────────────────────────────────────────────
// Step 4: Negotiate and Sign Terms
// ──────────────────────────────────────────────
const now = new Date();
const expiration = new Date(now.getTime() + 3600000);
let terms = buildTermsUnsigned(
{
participants: [
{ did: providerDid, role: ParticipantRole.PROVIDER },
{ did: consumerDid, role: ParticipantRole.CONSUMER },
],
offer_ref: offer.offer_id,
request_ref: request.request_id,
price: { amount: 0.002, unit: "USD" },
delivery: {
method: DeliveryMethod.SYNCHRONOUS,
max_latency_ms: 5000,
},
quality: { accuracy: 0.95 },
dispute_resolution: {
method: DisputeMethod.AUTOMATED_ARBITRATION,
},
settlement: {
rail: "mercury",
timing: SettlementTiming.IMMEDIATE,
},
expiration: expiration.toISOString(),
},
providerDid
);
// Both parties sign
terms = await addTermsSignature(terms, providerDid, providerKeys);
terms = await addTermsSignature(terms, consumerDid, consumerKeys);
console.log("Terms fully signed:", isTermsFullySigned(terms));
console.log("Terms ID:", terms.terms_id);
// ──────────────────────────────────────────────
// Step 5: Generate a Receipt
// ──────────────────────────────────────────────
const receipt = await buildReceipt(
{
mandate_id: terms.terms_id, // In full flow, this would be a Mandate ID
participants: terms.participants,
outcome: ReceiptOutcome.FULFILLED,
verification: {
method: VerificationMethod.COMPUTATION,
evidence: ["accuracy_score=0.97", "latency_ms=1200"],
},
timestamp: new Date().toISOString(),
},
providerDid,
providerKeys
);
console.log("Receipt ID:", receipt.receipt_id);
console.log("Outcome:", receipt.outcome);
}
main().catch(console.error);API Reference
Core Types
All type definitions are exported from the package root. The complete type system is derived from MTP-SPEC-001 and MTP-BIND-001.
Foundational Types
| Type | Description |
|------|-------------|
| MtpUuid | 256-bit globally unique identifier in 67-character canonical hex format |
| DidString | Decentralized identifier in did:mtp:* format |
| Timestamp | ISO 8601 RFC 3339 UTC timestamp |
| Duration | ISO 8601 duration string |
| Jurisdiction | ISO 3166-1 alpha-2 country code |
| PriceUnit | ISO 4217 currency code or MTP-defined unit |
| ValueTypeClassifier | Dotted-path from the MTP Value Taxonomy |
Enumerations
| Enum | Values |
|------|--------|
| MtpUuidType | Offer, Request, Terms, Receipt, Mandate, Agent, Principal, Manifest, Error |
| SignatureAlgorithm | ML_DSA_65, ML_DSA_87, SLH_DSA_SHA2_192s |
| KemAlgorithm | ML_KEM_768, ML_KEM_1024 |
| HashAlgorithm | SHA_256, SHA3_256 |
| DeliveryMethod | SYNCHRONOUS, ASYNCHRONOUS, PHYSICAL, STREAMING |
| SettlementTiming | IMMEDIATE, DEFERRED, ESCROW |
| DisputeMethod | AUTOMATED_ARBITRATION, HUMAN_ARBITRATION, LEMAY_DISPUTE_SERVICE, CUSTOM |
| VerificationMethod | ATTESTATION, EVIDENCE, COMPUTATION, THIRD_PARTY |
| ReceiptOutcome | FULFILLED, PARTIALLY_FULFILLED, DISPUTED, FAILED |
| TransactionState | initiated, negotiating, committed, settling, verifying, fulfilled, disputed, resolved, failed, void |
| ParticipantRole | PROVIDER, CONSUMER, INTERMEDIARY, ARBITER, OBSERVER |
| AttributionMethod | SHAPLEY, EQUAL, PROPORTIONAL, CUSTOM |
| ErrorSeverity | Fatal, Recoverable, Warning, Informational |
| ProtocolLayer | CrossLayer (0) through Attribution (7) |
Protocol Objects
| Type | Description |
|------|-------------|
| MtpOffer | Provider's signed offer with value type, terms template, validity window, and constraints |
| MtpRequest | Consumer's signed request with value type, constraints, and authority attestation |
| MtpTerms | Negotiated agreement with locked price, delivery, quality, dispute, settlement, and multi-party signatures |
| MtpReceipt | Cryptographic proof of outcome with verification evidence, attribution, and signature |
| MtpSignature | Algorithm, base64url value, and signer DID |
| AgentSignature | Agent DID, algorithm, and signature value for multi-party signing |
| PriceSpec | Amount and currency unit |
| DeliverySpec | Method, latency, delivery windows, and format |
| QualitySpec | Arbitrary quality dimension map |
| SettlementSpec | Payment rail, timing, and escrow configuration |
| MtpError | Structured error with code, layer, severity, description, and transaction reference |
UUID Generation
MTP-UUIDs are 256-bit identifiers implementing MTP-BIND-001 Section IX. Structure: 4-bit version, 4-bit type nibble, 64-bit nanosecond timestamp, 48-bit source hash, 136-bit CSPRNG random.
import { generateMtpUuid, parseMtpUuid, validateMtpUuidType, mtpUuidToBytes, MtpUuidType } from "@lemay/mtp";
const uuid = generateMtpUuid(MtpUuidType.OFFER, "did:mtp:abc123");
const components = parseMtpUuid(uuid);
// { version, type, timestamp, source, random, raw }
validateMtpUuidType(uuid, MtpUuidType.OFFER); // throws if type mismatch
const bytes = mtpUuidToBytes(uuid); // Buffer (32 bytes) for CBOR embeddingDeterministic CBOR Serialization
Implements MTP-BIND-001 Section IV. Two conforming implementations serializing the same logical object produce byte-identical output. Map keys sorted in bytewise lexicographic order. No indefinite-length encoding. Minimal integer encoding.
import { serializeDeterministic, deserialize, computeSignableBytes, verifyRoundTrip, toDiagnosticNotation } from "@lemay/mtp";
const obj = { agent: "did:mtp:abc", price: 0.002 };
const cbor = serializeDeterministic(obj); // Buffer — deterministic CBOR bytes
const restored = deserialize(cbor); // Original object
const signable = computeSignableBytes(obj); // Bytes to sign (signature fields excluded)
const intact = verifyRoundTrip(obj, cbor); // true if round-trip preserves structure
const diag = toDiagnosticNotation(obj); // Human-readable CBOR notationCryptographic Signing
Abstraction layer for post-quantum cryptography. Register a CryptoProvider implementation before calling any signing or primitive-building function.
import { registerCryptoProvider, getCryptoProvider, signProtocolObject, verifyProtocolSignature, CryptoProvider } from "@lemay/mtp";
// Implement the CryptoProvider interface with your chosen
// post-quantum library (ML-DSA-65, ML-DSA-87, SLH-DSA-SHA2-192s)
const provider: CryptoProvider = { /* ... */ };
registerCryptoProvider(provider);
const signature = await signProtocolObject(messageBytes, privateKey, signerDid, algorithm);
const valid = await verifyProtocolSignature(messageBytes, signature, publicKey);CryptoProvider Interface:
| Method | Description |
|--------|-------------|
| generateSigningKeyPair(algorithm) | Generate ML-DSA or SLH-DSA key pair |
| sign(message, privateKey, algorithm) | Sign message bytes |
| verify(message, signature, publicKey, algorithm) | Verify signature |
| generateKemKeyPair(algorithm) | Generate ML-KEM key pair |
| encapsulate(publicKey, algorithm) | KEM encapsulation |
| decapsulate(ciphertext, privateKey, algorithm) | KEM decapsulation |
| hash(data) | SHA-256 or SHA3-256 hash |
| encrypt(plaintext, key) | Symmetric encryption (returns ciphertext, iv, tag) |
| decrypt(ciphertext, key, iv, tag) | Symmetric decryption |
Primitive Builders
Factory functions for constructing the four MTP primitives with automatic UUID generation, input validation, and cryptographic signing.
import { buildOffer, buildRequest, buildTermsUnsigned, addTermsSignature, isTermsFullySigned, buildReceipt } from "@lemay/mtp";| Function | Signature | Description |
|----------|-----------|-------------|
| buildOffer | (input: OfferInput, keyPair: MtpKeyPair) → Promise<MtpOffer> | Create and sign an Offer |
| buildRequest | (input: RequestInput, keyPair: MtpKeyPair) → Promise<MtpRequest> | Create and sign a Request |
| buildTermsUnsigned | (input: TermsInput, creatingAgentDid: DidString) → MtpTerms | Create unsigned Terms (signatures array empty) |
| addTermsSignature | (terms: MtpTerms, agentDid: DidString, keyPair: MtpKeyPair) → Promise<MtpTerms> | Add a participant's signature to Terms |
| isTermsFullySigned | (terms: MtpTerms) → boolean | Check whether all participants have signed |
| buildReceipt | (input: ReceiptInput, verifyingAgentDid: DidString, keyPair: MtpKeyPair) → Promise<MtpReceipt> | Create and sign a Receipt |
Validation rules enforced by builders: DID format (did:mtp:*), value type taxonomy, RFC 3339 timestamps, human description length (4,096 character limit), minimum two participants on Terms, outcome-specific required fields on Receipts.
Layer 1 — Identity
Decentralized identity generation, DID Documents, delegation certificates, algorithm negotiation.
import {
generateDid,
deriveSourceFromDid,
buildDidDocument,
issueDelegationCertificate,
verifyCertificate,
validateDelegationChain,
checkRevocationStatus,
negotiateAlgorithms,
} from "@lemay/mtp";| Function | Description |
|----------|-------------|
| generateDid(publicKey: Buffer) | Generate did:mtp:* from Base58btc(SHA-256(publicKey)) |
| deriveSourceFromDid(did: DidString) | Extract 48-bit source hash for UUID generation |
| buildDidDocument(input: DidDocumentInput) | Construct JSON-LD DID Document with verification methods, service endpoints, algorithm profile |
| issueDelegationCertificate(input, keyPair) | Issue delegation credential with scope and value constraints |
| verifyCertificate(certificate) | Verify delegation certificate signature |
| validateDelegationChain(chain, principal, scope, value) | Validate authority chain — ensures scope and value are not escalated |
| checkRevocationStatus(did) | Check whether a DID has been revoked |
| negotiateAlgorithms(localProfile, remoteProfile) | Select highest-security common algorithms between two parties |
Layer 2 — Discovery
Capability publication, indexing, and matching.
import {
buildCapabilityManifest,
InMemoryDiscoveryIndex,
FederatedDiscoveryClient,
matchRequestToOffers,
buildOfferRevocation,
} from "@lemay/mtp";| Export | Description |
|--------|-------------|
| buildCapabilityManifest(input, keyPair) | Create signed Capability Manifest declaring what an agent provides |
| InMemoryDiscoveryIndex | In-memory manifest store with query support (for local or testing use) |
| FederatedDiscoveryClient | Queries multiple discovery indexes across network boundaries |
| matchRequestToOffers(request, index) | Find compatible Offers for a Request with compatibility scoring (0.0–1.0) |
| buildOfferRevocation(offerId, agentId, reason, keyPair) | Revoke a published Offer with cryptographic proof |
Layer 3 — Negotiation
Multi-round negotiation state machine.
import { NegotiationSession, NegotiationStatus, singleRoundAccept, ProposalResponse } from "@lemay/mtp";| Export | Description |
|--------|-------------|
| NegotiationSession | State machine managing proposal, counterproposal, acceptance, rejection, timeout |
| NegotiationStatus | Active, Accepted, Rejected, Timeout, Exhausted |
| ProposalResponse | Accept, Counter, Reject |
| singleRoundAccept(offer, request, keyPair) | Shortcut for commodity transactions — accept Offer terms without negotiation |
NegotiationSession methods: submitProposal(terms, proposerDid, keyPair), acceptProposal(), rejectProposal(), counterProposal(counter, keyPair), isTimedOut().
Layer 4 — Commitment
Transaction Mandate lifecycle.
import {
createMandate,
signMandate,
satisfyPrecondition,
checkPreconditionExpiration,
checkMandateExpiration,
initiateSettlement,
confirmSettlement,
MandateStatus,
} from "@lemay/mtp";| Function | Description |
|----------|-------------|
| createMandate(input, creatingAgentDid) | Create TransactionMandate from agreed Terms |
| signMandate(mandate, agentDid, keyPair) | Add participant signature to Mandate |
| satisfyPrecondition(mandate, preconditionId) | Mark precondition satisfied; transitions to Active if all met |
| checkPreconditionExpiration(mandate) | Check whether any precondition has expired |
| checkMandateExpiration(mandate) | Check whether the Mandate itself has expired |
| initiateSettlement(mandate) | Transition Mandate to Settling state |
| confirmSettlement(mandate) | Transition Mandate to Completed state |
MandateStatus: Pending, Active, Settling, Completed, Superseded, Void.
Layer 5 — Settlement
Pluggable payment rail abstraction.
import { SettlementRegistry, executeSettlement, executeReversal, SettlementStatus } from "@lemay/mtp";| Export | Description |
|--------|-------------|
| SettlementRegistry | Registry for payment rail adapters — register(adapter), getAdapter(railId), findAdaptersForCurrency(unit), listRails() |
| executeSettlement(mandate, params) | Execute payment through the appropriate rail adapter |
| executeReversal(settlementId, reason) | Reverse a completed settlement |
| SettlementStatus | Initiated, Processing, Confirmed, Reversed, Failed |
Implement SettlementAdapter to add new payment rails: initiateSettlement(params), queryStatus(id), reverseSettlement(id, reason), supportsCurrency(unit).
Layer 6 — Verification
Quality evaluation and delivery confirmation.
import { evaluateInferenceQuality, evaluatePhysicalDelivery, generateReceipt } from "@lemay/mtp";| Function | Description |
|----------|-------------|
| evaluateInferenceQuality(terms, measured) | Evaluate inference delivery against agreed terms (accuracy, latency, format, model version) |
| evaluatePhysicalDelivery(terms, measured) | Evaluate physical delivery against agreed terms (condition, dimensions, weight) |
| generateReceipt(evaluation, mandate, agentDid, keyPair) | Generate signed Receipt from evaluation results with automatic fulfillment ratio computation |
Layer 7 — Attribution
Shapley value computation for multi-party value distribution.
import { exactShapley, approximateShapley, normalizeToShares, buildAttributionRecord } from "@lemay/mtp";| Function | Description |
|----------|-------------|
| exactShapley(agents, valueFn) | Exact Shapley values for coalitions of 10 or fewer participants. O(2^n * n) complexity. |
| approximateShapley(agents, valueFn, sampleCount?) | Monte Carlo approximation for larger coalitions. Default 10,000 samples. Returns values and error bound. |
| normalizeToShares(shapleyMap) | Convert Shapley values to percentage shares summing to 1.0 |
| buildAttributionRecord(mandate, method, entries, keyPair) | Create signed attribution record for inclusion in Receipts |
The ValueFunction type is (coalition: Set<DidString>) => number — a characteristic function mapping any subset of participants to the value that coalition generates.
Specifications
This SDK implements two specifications:
MTP-SPEC-001 — Massachusetts Transaction Protocol Specification, Parts 1–3. Defines the four primitives, seven layers, transaction state machine, error model, and governance framework.
MTP-BIND-001 — MTP Technical Binding Specification. Defines the wire format (deterministic CBOR per RFC 8949), MTP-UUID structure (256-bit with type nibble, nanosecond timestamp, source hash, and CSPRNG random), cryptographic algorithms (ML-DSA-65, ML-DSA-87, SLH-DSA-SHA2-192s for signing; ML-KEM-768, ML-KEM-1024 for key encapsulation), and serialization rules.
License
Curtis License™ v1.0 — LeMay American Innovation Protection License.
Copyright © 2026 LeMay Inc. All rights reserved. Proprietary and confidential. No rights are granted without a prior written and fully executed license agreement with LeMay Inc.
For licensing inquiries: [email protected]
LeMay Inc. — Pro Republica Aedificamus Invented in USA. Made in the Commonwealth of Massachusetts.
