Source code for fleetmesh_core.textile.quilt

"""Fabric & Quilt root calculation and validation (`fleetmesh_core.textile.quilt`)."""
from __future__ import annotations

import os
from typing import Any, List, Mapping, MutableMapping, Optional

from .bao import bao_root_1024
from .canonical import canonical_json
from .principal import Principal, norm_key, principal_keys

AUDIENCES = ('self', 'circle', 'public')
AUDIENCE_RANK = {'self': 0, 'circle': 1, 'public': 2}
MAX_VIEW_JSON_BYTES = int(os.environ.get('FLEETMESH_MAX_QUILT_VIEW_BYTES', str(2 * 1024 * 1024)))


[docs]def compute_fabric_root(fabric: Mapping[str, Any], snapshot: Mapping[str, Any]) -> str: owner = fabric.get('owner') or {} payload: MutableMapping[str, Any] = { 'v': 1, 'fabric_id': fabric.get('fabric_id'), 'kind': fabric.get('kind'), 'owner': {'identity_id': owner.get('identity_id'), 'did': owner.get('did')}, 'strand_ids': list(snapshot.get('strand_ids') or []), 'strand_roots': list(snapshot.get('strand_roots') or []), } if snapshot.get('structure') == 'key': payload['structure'] = 'key' if snapshot.get('delimiters'): payload['delimiters'] = [ {'at': d.get('at'), 'mark': d.get('mark'), 'strand_id': d.get('strand_id') or ''} for d in snapshot['delimiters'] if isinstance(d, Mapping) ] if isinstance(fabric.get('interactions'), list): payload['interactions'] = [ {'kind': e.get('kind'), 'target': e.get('target_strand_id'), 'at': e.get('at'), 'fiber_root': e.get('fiber_root') or ''} for e in fabric['interactions'] ] return bao_root_1024(canonical_json(payload).encode('utf-8'))[0]
[docs]def compute_quilt_root(quilt: Mapping[str, Any]) -> str: owner = quilt.get('owner') or {} fabrics = sorted(quilt.get('fabrics') or [], key=lambda f: str(f.get('fabric_id') or '')) return bao_root_1024(canonical_json({ 'v': 1, 'quilt_id': quilt.get('quilt_id'), 'audience': quilt.get('audience') or 'self', 'owner': {'identity_id': owner.get('identity_id'), 'did': owner.get('did')}, 'identity_fibers': [{'role': f.get('role'), 'kind': f.get('kind'), 'fiber_root': f.get('fiber_root')} for f in quilt.get('identity_fibers') or []], 'fabrics': [{'fabric_id': f.get('fabric_id'), 'fabric_root': f.get('fabric_root'), 'audience': f.get('audience')} for f in fabrics], **({'shard_fibers': [ {'shard_type': f.get('shard_type'), 'fiber_root': f.get('fiber_root'), 'byte_length': f.get('byte_length'), **({'sealed_root': f['sealed_root']} if f.get('sealed_root') else {})} for f in sorted(quilt.get('shard_fibers') or [], key=lambda f: str(f.get('shard_type') or '')) ]} if quilt.get('shard_fibers') else {}), **({'spindle': [{'stream_id': sid} for sid in sorted(str(s.get('stream_id') or '') for s in quilt['spindle'])]} if quilt.get('spindle') else {}), }).encode('utf-8'))[0]
def _fabric_audience(fabric: Mapping[str, Any]) -> str: if fabric.get('kind') in ('activity', 'vault') or fabric.get('visibility') == 'vault_only': return 'self' return 'circle' if fabric.get('kind') == 'circle_feed' else 'public'
[docs]def validate_quilt_view(view: Mapping[str, Any], principal: Principal, *, owner_ref: Optional[Mapping[str, Any]] = None) -> List[str]: """Problems with a published view (empty when it may be stored).""" errors: List[str] = [] audience = view.get('audience') raw_quilt = view.get('quilt') quilt: Mapping[str, Any] = raw_quilt if isinstance(raw_quilt, Mapping) else {} raw_fabrics = view.get('fabrics') fabrics: Optional[List[Any]] = raw_fabrics if isinstance(raw_fabrics, list) else None if audience not in AUDIENCES or quilt.get('audience') != audience: errors.append('invalid_audience') owner = quilt.get('owner') or {} p = owner_ref if owner_ref is not None else (principal or {}) if not principal_keys(principal) or any(norm_key(owner.get(f)) != norm_key(p.get(f)) for f in ('identity_id', 'did')): errors.append('not_quilt_owner') if quilt.get('shard_fibers') and audience != 'self': errors.append('shard_fibers_not_allowed') spindle = quilt.get('spindle') if spindle is not None and (not isinstance(spindle, list) or any( not isinstance(s, Mapping) or set(s) != {'stream_id'} or not isinstance(s.get('stream_id'), str) or not s['stream_id'] for s in spindle)): errors.append('invalid_spindle') if fabrics is None: return errors + ['fabrics_required'] refs = {str(r.get('fabric_id')): r for r in quilt.get('fabrics') or [] if isinstance(r, Mapping)} if set(refs) != {str(f.get('fabric_id')) for f in fabrics if isinstance(f, Mapping)} or len(refs) != len(fabrics): errors.append('fabric_refs_mismatch') for f in fabrics: if not isinstance(f, Mapping): errors.append('invalid_fabric') continue fid = str(f.get('fabric_id') or '') raw_snap = f.get('snapshot') snap: Mapping[str, Any] = raw_snap if isinstance(raw_snap, Mapping) else {} if f.get('owner', {}).get('identity_id') != owner.get('identity_id') or f.get('owner', {}).get('did') != owner.get('did'): errors.append(f'fabric_owner_mismatch:{fid}') if snap.get('fabric_root') != compute_fabric_root(f, snap): errors.append(f'fabric_root_mismatch:{fid}') if any(not isinstance(d, Mapping) or d.get('mark') not in ('tombstone', 'hidden') or not isinstance(d.get('at'), int) for d in snap.get('delimiters') or []): errors.append(f'invalid_delimiter:{fid}') ref = refs.get(fid) or {} fab_aud = _fabric_audience(f) if ref.get('fabric_root') != snap.get('fabric_root') or ref.get('audience') != fab_aud: errors.append(f'fabric_ref_mismatch:{fid}') if audience in AUDIENCE_RANK and AUDIENCE_RANK[fab_aud] < AUDIENCE_RANK[audience]: errors.append(f'fabric_not_allowed_in_view:{fid}') if not errors and quilt.get('quilt_root') != compute_quilt_root(quilt): errors.append('quilt_root_mismatch') return errors
[docs]def group_owner_id(circle_id: str) -> str: """A circle's identity as a quilt owner: its own namespace, apart from user identity ids.""" return f'group:{norm_key(circle_id)}'
FIBER_PACK_MAGIC = 'MTFP1\n' def compute_suit_root( suit_id: str, owner: Mapping[str, Any], quilt_roots: List[str], fiber_entries: List[Mapping[str, Any]], sealed_shards: Optional[List[Mapping[str, Any]]] = None, ) -> str: """Computes the canonical 1,024-byte Bao Merkle root of a Layer 5 TextileSuit.""" sorted_q = sorted(set(str(q) for q in (quilt_roots or []) if q)) sorted_f = sorted( ( { 'root': str(f.get('root') or ''), 'byte_length': int(f.get('byte_length') or 0), 'mime_type': str(f.get('mime_type') or 'application/octet-stream'), } for f in (fiber_entries or []) ), key=lambda x: str(x['root']), ) sorted_s = sorted( ( { 'shard_type': str(s.get('shard_type') or ''), 'plaintext_root': str(s.get('plain_root') or s.get('plaintext_root') or ''), 'sealed_root': str(s.get('sealed_root') or ''), } for s in (sealed_shards or []) ), key=lambda x: x['shard_type'], ) payload = canonical_json({ 'v': 2, 'magic': FIBER_PACK_MAGIC, 'suit_id': suit_id, 'owner': {'identity_id': owner.get('identity_id'), 'did': owner.get('did')}, 'quilt_roots': sorted_q, 'fibers': sorted_f, 'sealed_shards': sorted_s, }).encode('utf-8') return bao_root_1024(payload)[0] def compute_fit_root(policy: Mapping[str, Any]) -> str: """Computes the canonical 1,024-byte Bao Merkle root of a Layer 6 TextileFit policy.""" langs = sorted(str(x) for x in (policy.get('preferred_subtitle_langs') or policy.get('preferredSubtitleLangs') or ['en'])) payload = canonical_json({ 'v': 1, 'policy_id': policy.get('policy_id') or policy.get('policyId') or 'fit-sovereign-default-v1', 'contributed_quota_mb': int(policy.get('contributed_quota_mb') or policy.get('contributedQuotaMB') or 2048), 'pinned_reserve_pct': int(policy.get('pinned_reserve_pct') or policy.get('pinnedReservePct') or 75), 'auto_pin_self_quilt_shards': bool(policy.get('auto_pin_self_quilt_shards', policy.get('autoPinSelfQuiltShards', True))), 'auto_pin_circle_strands': bool(policy.get('auto_pin_circle_strands', policy.get('autoPinCircleStrands', True))), 'max_auto_pin_fiber_bytes': int(policy.get('max_auto_pin_fiber_bytes') or policy.get('maxAutoPinFiberBytes') or 16 * 1024 * 1024), 'preferred_subtitle_langs': langs, 'enforce_bao_on_ingress': bool(policy.get('enforce_bao_on_ingress', policy.get('enforceBaoOnIngress', True))), 'enforce_local_tombstones': bool(policy.get('enforce_local_tombstones', policy.get('enforceLocalTombstones', True))), 'enforce_sealed_shard_boundary': bool(policy.get('enforce_sealed_shard_boundary', policy.get('enforceSealedShardBoundary', True))), 'serve_local_vault_first': bool(policy.get('serve_local_vault_first', policy.get('serveLocalVaultFirst', True))), }).encode('utf-8') return bao_root_1024(payload)[0] def compute_preemptive_lock_tag(tree_root_hex: str) -> str: import hashlib clean = str(tree_root_hex or '').strip().lower() if len(clean) == 64 and all(c in '0123456789abcdef' for c in clean): root_bytes = bytes.fromhex(clean) else: root_bytes = hashlib.sha256(f'fleetmesh-kdf:tree-root:{clean}'.encode('utf-8')).digest() prefix = b'fleetmesh-preemptive-tag-v1:' return hashlib.sha256(b'\x05' + prefix + root_bytes).hexdigest() def build_tombstone_strand_manifest(params: Mapping[str, Any]) -> MutableMapping[str, Any]: """Computes a Layer 7 Tombstone Strand manifest and its 1,024B Bao `strand_root`.""" from .canonical import get_strand_public_url_path, sanitize_strand_url_slug from .strand import compute_strand_root created_at = int(params.get('created_at') or params.get('createdAt') or 0) updated_at = int(params.get('updated_at') or params.get('updatedAt') or created_at) target_strand_id = str(params.get('target_strand_id') or params.get('targetStrandId') or '') target_strand_kind = str(params.get('target_strand_kind') or params.get('targetStrandKind') or 'document') raw_root = str(params.get('target_tree_root') or params.get('targetTreeRoot') or '').strip().lower() if len(raw_root) == 64 and all(c in '0123456789abcdef' for c in raw_root): target_tree_root = raw_root else: target_tree_root = bao_root_1024(f'fleetmesh-tombstone-target:{target_strand_id}'.encode('utf-8'))[0] raw_lock = str(params.get('lock_tag') or params.get('lockTag') or '').strip().lower() lock_tag = raw_lock if (len(raw_lock) == 64 and all(c in '0123456789abcdef' for c in raw_lock)) else compute_preemptive_lock_tag(target_tree_root) mode = str(params.get('mode') or 'retroactive') default_policies = { 'preemptive': 'preemptive_ceiling', 'retroactive': 'local_suppress', 'local_cache': 'local_cache_block', 'ephemeral_ttl': 'ttl_auto_expire', 'federated_quarantine': 'peer_ingest_reject', 'superseded_revision': 'revision_compaction', 'key_revocation': 'ucan_key_revoke', } hard_purged = bool(params.get('hard_purged') or params.get('hardPurged') or params.get('policy') == 'hard_purge') policy = 'hard_purge' if hard_purged else str(params.get('policy') or default_policies.get(mode, 'local_suppress')) instance_local = bool( params.get('instance_local') or params.get('instanceLocal') or mode in ('local_cache', 'federated_quarantine') or policy == 'local_cache_block' ) reversible = not hard_purged and ( mode in ('preemptive', 'local_cache', 'federated_quarantine') or policy in ('local_suppress', 'local_cache_block', 'preemptive_ceiling') ) visibility = 'vault_only' if instance_local else str(params.get('visibility') or 'public') is_blinded = bool(params.get('is_blinded') or params.get('isBlinded')) claim_bytes = canonical_json({ 'schema': 'fleetmesh.tombstone.claim/v1', 'lock_tag': lock_tag, 'target_strand_id': f'blinded:{lock_tag[:16]}' if (is_blinded and visibility == 'public') else target_strand_id, 'target_strand_kind': target_strand_kind, 'target_tree_root': '' if (is_blinded and visibility == 'public') else target_tree_root, 'mode': mode, 'policy': policy, 'ceiling_rung': params.get('ceiling_rung') or params.get('ceilingRung') or None, 'is_blinded': is_blinded, 'blinded_origin_commitment': params.get('blinded_origin_commitment') or params.get('blindedOriginCommitment') or None, 'hard_purged': hard_purged, 'created_at': created_at, }).encode('utf-8') claim_fiber_root = bao_root_1024(claim_bytes)[0] title = str(params.get('title') or '') note = str(params.get('note') or '') meta_bytes = canonical_json({ 'schema': 'fleetmesh.tombstone.meta/v1', 'title': title, 'target_strand_kind': target_strand_kind, 'mode': mode, 'policy': policy, 'reversible': reversible, 'hard_purged': hard_purged, 'note': note, 'updated_at': updated_at, }).encode('utf-8') meta_fiber_root = bao_root_1024(meta_bytes)[0] fibers = [ {'fiber_root': claim_fiber_root, 'role': 'primary_asset', 'kind': 'hide', 'mime_type': 'application/json', 'byte_length': len(claim_bytes)}, {'fiber_root': meta_fiber_root, 'role': 'metadata', 'kind': 'metadata', 'mime_type': 'application/json', 'byte_length': len(meta_bytes)}, {'fiber_root': target_tree_root, 'role': 'source', 'kind': 'metadata', 'mime_type': 'application/octet-stream', 'byte_length': 0}, ] strand_id = f'tombstone-{sanitize_strand_url_slug(target_strand_id or lock_tag[:16])}' author = dict(params.get('author') or {'identity_id': 'local-owner', 'did': 'did:nostr:local-owner'}) manifest: MutableMapping[str, Any] = { 'strand_id': strand_id, 'kind': 'tombstone', 'schema_id': 'fleetmesh.strand.tombstone/v1', 'author': author, 'visibility': visibility, 'version_number': 2 if hard_purged else 1, 'version_tag': '2.0.0-purged' if hard_purged else '1.0.0', 'fibers': fibers, 'public_url': get_strand_public_url_path(strand_id, visibility), 'parent_strand_id': target_strand_id, 'created_at': created_at, 'updated_at': updated_at, } manifest['strand_root'] = compute_strand_root(manifest) return manifest __all__ = [ 'AUDIENCES', 'AUDIENCE_RANK', 'MAX_VIEW_JSON_BYTES', 'FIBER_PACK_MAGIC', 'compute_fabric_root', 'compute_quilt_root', 'validate_quilt_view', 'group_owner_id', 'compute_suit_root', 'compute_fit_root', 'compute_preemptive_lock_tag', 'build_tombstone_strand_manifest', ]