Source code for fleetmesh_node.planes.services.settle.compartment

"""The Settlement compartment: the operator verbs over the engine and the
rails. Built from the operator's `settlement` config block."""
from __future__ import annotations

import json
from typing import Any, Mapping, Optional, Union

from fleetmesh_node import channels as ch_mod
from fleetmesh_node import metrics as mx_mod
from fleetmesh_core.accounting.cashu import create_nutzap_event
from fleetmesh_node import compartment as compartment_mod
from fleetmesh_node.compartment import stores as st
from fleetmesh_node.compartment import Command, Need
from fleetmesh_node.config.parameter import Parameter
from fleetmesh_node.config import SettlementConfig
from .engine import SettlementEngine
from .store import SettlementStore


from .types import SettleShowDict


[docs]class Settlement(compartment_mod.Compartment): """The settlement compartment of meshnode (NIP-61 Nutzap & Lightning hold-invoices).""" name = 'settle' attr: Optional[str] = 'settlement' DB: str = 'settlements.sqlite' reads = ('settlement', 'compute') # grants is a node attribute it reaches, not a config key config_cls = SettlementConfig SCHEMA = SettlementStore.SCHEMA STORES = ( st.Store(key='escrows', description='settlement escrows held in sqlite database', kind=st.RING, shape=dict, bound=256), ) NEEDS = ( Need('db_path', path='DB'), Need('node_pk', 'pubkey'), Need('settings', block=SettlementConfig), Need('ks', 'ks'), Need('grants', 'stores.grants'), ) CHANNELS = ( ch_mod.Channel('escrow_created', 'A settlement escrow was created for a compute ask', level=ch_mod.INFO, say='created escrow {ask} for {amount_msat} msat (rail: {rail})', tags=('settle', 'escrow')), ch_mod.Channel('escrow_held', 'A settlement escrow was locked in held state', level=ch_mod.INFO, say='escrow {ask} held', tags=('settle', 'escrow')), ch_mod.Channel('escrow_settled', 'A settlement escrow was settled upon preimage disclosure', level=ch_mod.INFO, say='escrow {ask} settled', tags=('settle', 'escrow')), ch_mod.Channel('escrow_cancelled', 'A settlement escrow was cancelled and released', level=ch_mod.NOTE, say='escrow {ask} cancelled (reason: {reason})', tags=('settle', 'escrow')), ch_mod.Channel('grant_expanded', 'Peer rate-bucket grant limits expanded with Nutzap', level=ch_mod.INFO, say='grant expanded for peer {peer} via nutzap', tags=('settle', 'nutzap')), ) METRICS = ( mx_mod.Metric(name='settlement_escrows_created', description='Escrows created for compute tasks.', kind=mx_mod.COUNTER, counts='escrow_created', tags=('settle', 'escrow')), mx_mod.Metric(name='settlement_escrows_held', description='Escrows locked into held state.', kind=mx_mod.COUNTER, counts='escrow_held', tags=('settle', 'escrow')), mx_mod.Metric(name='settlement_escrows_settled', description='Escrows settled with preimage.', kind=mx_mod.COUNTER, counts='escrow_settled', tags=('settle', 'escrow')), mx_mod.Metric(name='settlement_escrows_cancelled', description='Escrows cancelled.', kind=mx_mod.COUNTER, counts='escrow_cancelled', tags=('settle', 'escrow')), mx_mod.Metric(name='settlement_grants_expanded', description='Grants expanded via ecash Nutzap.', kind=mx_mod.COUNTER, counts='grant_expanded', tags=('settle', 'nutzap')), ) COMMANDS = ( Command( key='show', name='Settlement Status', description='display active settlement rails and escrows', tags=('settle', 'status'), permission='settle/show', run='show_cmd', reply='dict', ), Command( key='create', name='Create Escrow', description='create conditional hold escrow for a compute ask', tags=('settle', 'escrow'), parameters=( Parameter(key='ask', name='ask', description='ask identifier', type=str, default='', required=True), Parameter(key='buyer', name='buyer', description='buyer public key', type=str, default='', required=True), Parameter(key='seller', name='seller', description='seller public key', type=str, default='', required=True), Parameter(key='amount_msat', name='amount_msat', description='escrow amount in millisatoshis', type=int, default=0, required=True), Parameter(key='hash', name='hash', description='payment hash', type=str, default='', required=True), Parameter(key='rail', name='rail', description='settlement rail name', type=str, default='lightning', required=False), ), permission='settle/create', run='create_cmd', reply='dict', ), Command( key='hold', name='Hold Escrow', description='transition escrow to HELD state upon locked payment', tags=('settle', 'hold'), parameters=( Parameter(key='ask', name='ask', description='ask identifier', type=str, default='', required=True), Parameter(key='proof', name='proof', description='proof or token payload', type=object, default=None, required=False), ), permission='settle/hold', run='hold_cmd', reply='bool', ), Command( key='settle', name='Settle Escrow', description='settle escrow upon disclosed preimage', tags=('settle', 'settle'), parameters=( Parameter(key='ask', name='ask', description='ask identifier', type=str, default='', required=True), Parameter(key='preimage', name='preimage', description='payment preimage hex', type=str, default='', required=True), ), permission='settle/settle', run='settle_cmd', reply='bool', ), Command( key='reconcile', name='Reconcile Escrow', description='reconcile variable token escrow with delta refund', tags=('settle', 'reconcile'), parameters=( Parameter(key='ask', name='ask', description='ask identifier', type=str, default='', required=True), Parameter(key='cost_msat', name='cost_msat', description='actual cost in millisatoshis', type=int, default=0, required=True), Parameter(key='preimage', name='preimage', description='payment preimage hex', type=str, default='', required=True), ), permission='settle/reconcile', run='reconcile_cmd', reply='dict', ), Command( key='stream_pay', name='Stream Payment', description='record pay-as-you-stream Nutzap token milestone', tags=('settle', 'stream'), parameters=( Parameter(key='ask', name='ask', description='ask identifier', type=str, default='', required=True), Parameter(key='tokens', name='tokens', description='delta tokens', type=int, default=0, required=True), Parameter(key='rate', name='rate', description='millisatoshis per token', type=int, default=0, required=True), Parameter(key='proof', name='proof', description='cashu token proof', type=object, default=None, required=False), ), permission='settle/stream_pay', run='stream_pay_cmd', reply='dict', ), Command( key='cancel', name='Cancel Escrow', description='cancel escrow and refund locked funds', tags=('settle', 'cancel'), parameters=( Parameter(key='ask', name='ask', description='ask identifier', type=str, default='', required=True), Parameter(key='reason', name='reason', description='cancellation reason', type=str, default='', required=False), ), permission='settle/cancel', run='cancel_cmd', reply='bool', ), Command( key='nutzap', name='Create Nutzap', description='create signed NIP-61 Kind 9321 Nutzap event', tags=('settle', 'nutzap'), parameters=( Parameter(key='recipient', name='recipient', description='recipient public key', type=str, default='', required=True), Parameter(key='amount_msat', name='amount_msat', description='payment amount in millisatoshis', type=int, default=0, required=True), Parameter(key='proofs', name='proofs', description='Cashu proofs list or json', type=object, default=list, required=True), Parameter(key='mint', name='mint', description='mint url', type=str, default=None, required=False), Parameter(key='target_event', name='target_event', description='target event id', type=str, default=None, required=False), ), permission='settle/nutzap', run='nutzap_cmd', reply='dict', ), Command( key='expand_grant', name='Expand Grant', description='expand peer rate-bucket limits with verified Nutzap proofs', tags=('settle', 'grants'), parameters=( Parameter(key='peer', name='peer', description='peer public key', type=str, default='', required=True), Parameter(key='nutzap', name='nutzap', description='nutzap event dict or json', type=object, default=dict, required=True), ), permission='settle/expand_grant', run='expand_grant_cmd', reply='dict', ), Command( key='nwc_pay', name='Pay NWC Invoice', description='pay a Lightning invoice via NWC to unlock escrow', tags=('settle', 'nwc'), parameters=( Parameter(key='hash', name='hash', description='payment hash hex', type=str, default='', required=True), Parameter(key='bolt11', name='bolt11', description='bolt11 payment invoice', type=str, default='', required=True), ), permission='settle/nwc_pay', run='nwc_pay_cmd', reply='dict', ), Command( key='cashu_swap', name='Swap Cashu Proofs', description='swap held Cashu proofs for fresh blinded tokens at the live mint', tags=('settle', 'cashu'), parameters=( Parameter(key='hash', name='hash', description='payment hash hex', type=str, default='', required=True), Parameter(key='outputs', name='outputs', description='blinded outputs list or json', type=object, default=list, required=True), ), permission='settle/cashu_swap', run='cashu_swap_cmd', reply='dict', ), Command( key='cashu_melt', name='Melt Cashu Proofs', description='melt held Cashu proofs to pay an external Lightning invoice', tags=('settle', 'cashu'), parameters=( Parameter(key='hash', name='hash', description='payment hash hex', type=str, default='', required=True), Parameter(key='bolt11', name='bolt11', description='bolt11 payment invoice', type=str, default='', required=True), ), permission='settle/cashu_melt', run='cashu_melt_cmd', reply='dict', ), )
[docs] def __init__(self, node: Any = None, db_path: Optional[str] = None, node_pk: Optional[str] = None, settings: Optional[Union[SettlementConfig, Mapping[str, Any]]] = None, clock: Optional[Any] = None, ks: Optional[Any] = None, grants: Optional[Any] = None, db: Optional[Any] = None) -> None: """Built by `from_context` in a node. `Settlement()` and `Settlement(node=fake)` still work: what is not passed is read off `node` (dir, ks, cfg['settlement']) when it has it, else defaulted. `settings` is the operator's `settlement` config block: `nwc_uri`, `live_cashu`, `mint_url`.""" if db is None and db_path is not None: from fleetmesh_node.storage.adapter import SqliteAdapter db = SqliteAdapter(db_path, schema=self.SCHEMA, clock=clock) super().__init__(node, clock, db=db) # The keystore that signs a Nutzap and the grant store a Nutzap # expands: named from ctx in a node; read off `node` for the suites # that hand a fake node and nothing else. self.ks: Optional[Any] = ks if ks is not None else getattr(node, 'ks', None) self.grants: Optional[Any] = grants if grants is not None else getattr(node, 'grants', None) if node_pk is None and self.ks is not None: node_pk = self.ks.node_pk if settings is None: cfg = (getattr(node, 'cfg', None) or {}) if node is not None else {} settings = cfg.get('settlement', {}) if isinstance(cfg, dict) else {} block = settings if isinstance(settings, SettlementConfig) else SettlementConfig.from_dict(settings or {}) if db_path is not None: self.engine: SettlementEngine = SettlementEngine( db_path=db_path, clock=clock, nwc_uri=block.nwc_uri, use_live_cashu=block.live_cashu, mint_url=block.mint_url, node_pk=node_pk, db=self.db, ) else: self.engine = SettlementEngine( clock=clock, nwc_uri=block.nwc_uri, use_live_cashu=block.live_cashu, mint_url=block.mint_url, node_pk=node_pk, db=self.db, )
[docs] def show_cmd(self) -> SettleShowDict: return { 'rails': list(self.engine.rails.keys()), 'escrows': self.engine.list_escrows(limit=20), }
[docs] def create_cmd(self, args: Mapping[str, Any]) -> Mapping[str, Any]: res = self.engine.create_escrow( ask_id=args['ask'], buyer_pk=args['buyer'], seller_pk=args['seller'], amount_msat=int(args['amount_msat']), payment_hash=args['hash'], rail_id=args.get('rail') or 'lightning', ) self.say('escrow_created', ask=args['ask'], amount_msat=int(args['amount_msat']), rail=args.get('rail') or 'lightning') return res
[docs] def hold_cmd(self, args: Mapping[str, Any]) -> bool: ok_hold = self.engine.hold_escrow(args['ask'], token_or_proof=args.get('proof')) if not ok_hold: self.refusals.refuse('settlement', 'hold failed', detail={'ask': args['ask']}) else: self.say('escrow_held', ask=args['ask']) return ok_hold
[docs] def settle_cmd(self, args: Mapping[str, Any]) -> bool: ok_settle = self.engine.settle_escrow(args['ask'], args['preimage']) if not ok_settle: self.refusals.refuse('settlement', 'settle failed', detail={'ask': args['ask']}) else: self.say('escrow_settled', ask=args['ask']) return ok_settle
[docs] def reconcile_cmd(self, args: Mapping[str, Any]) -> Mapping[str, Any]: return self.engine.reconcile_escrow( ask_id=args['ask'], actual_cost_msat=int(args['cost_msat']), preimage=args['preimage'], )
[docs] def stream_pay_cmd(self, args: Mapping[str, Any]) -> Mapping[str, Any]: return self.engine.stream_micropayment( ask_id=args['ask'], delta_tokens=int(args['tokens']), rate_msat_per_token=int(args['rate']), cashu_token=args.get('proof'), )
[docs] def cancel_cmd(self, args: Mapping[str, Any]) -> bool: ok_cancel = self.engine.cancel_escrow(args['ask'], reason=args.get('reason') or '') if ok_cancel: self.say('escrow_cancelled', ask=args['ask'], reason=args.get('reason') or '') return ok_cancel
[docs] def nutzap_cmd(self, args: Mapping[str, Any]) -> Any: if self.ks is None: raise ValueError("no node keystore available to sign Nutzap") proofs = args['proofs'] if isinstance(args['proofs'], list) else json.loads(args['proofs']) rail = self.engine.rails.get('cashu') mint = args.get('mint') or (getattr(rail, 'mint_url', None) if rail is not None else None) if not mint: raise ValueError('no mint: pass mint=... or set settlement.mint_url') return create_nutzap_event( sender_sk=self.ks.node_sk, recipient_pk=args['recipient'], proofs=proofs, mint_url=mint, amount_msat=int(args['amount_msat']), target_event_id=args.get('target_event'), )
[docs] def expand_grant_cmd(self, args: Mapping[str, Any]) -> Mapping[str, Any]: if self.grants is None: raise ValueError("no node grant store available") nutzap_raw = args['nutzap'] nutzap: Mapping[str, Any] = ( nutzap_raw if isinstance(nutzap_raw, dict) else json.loads(nutzap_raw) ) res = self.engine.expand_grant_with_nutzap(self.grants, args['peer'], nutzap) self.say('grant_expanded', peer=args['peer']) return res
[docs] def nwc_pay_cmd(self, args: Mapping[str, Any]) -> Mapping[str, Any]: r = self.engine.get_rail('nwc') if not hasattr(r, 'pay_and_settle'): raise ValueError("configured nwc rail does not support pay_and_settle") return r.pay_and_settle(args['hash'], args['bolt11'])
[docs] def cashu_swap_cmd(self, args: Mapping[str, Any]) -> Mapping[str, Any]: r = self.engine.get_rail('cashu') if not hasattr(r, 'swap_and_settle'): raise ValueError("configured cashu rail does not support live swap_and_settle") outputs = args['outputs'] if isinstance(args['outputs'], list) else json.loads(args['outputs']) return r.swap_and_settle(args['hash'], outputs)
[docs] def cashu_melt_cmd(self, args: Mapping[str, Any]) -> Mapping[str, Any]: r = self.engine.get_rail('cashu') if not hasattr(r, 'melt_to_lightning'): raise ValueError("configured cashu rail does not support live melt_to_lightning") return r.melt_to_lightning(args['hash'], args['bolt11'])
[docs] def stop(self) -> Any: self.engine.close() super().stop() return None