Bases: ISigning
        ECDSA (secp256k1) detached signer for bytes and canonicalized envelopes.
  Algorithms
  
- ES256K (ECDSA over secp256k1 with SHA-256)
- 'ECDSA-SHA256' accepted as a synonym
 
  Private KeyRef accepted
  
- {"kind":"pem_priv","data": }
- {"kind":"pem_priv_path","path": }
- {"kind":"jwk_priv","jwk": {"kty":"EC","crv":"secp256k1","x","y","d"}}
- {"kind":"cryptography_obj","obj": EllipticCurvePrivateKey}
         Verification keys (opts["pubkeys"]) accepted as:
  - {"kind":"pem_pub","data": }
  - {"kind":"pem_pub_path","path": }
  - {"kind":"jwk_pub","jwk": {"kty":"EC","crv":"secp256k1","x","y"}}
  - {"kind":"cryptography_obj","obj": EllipticCurvePublicKey}
  - direct PEM (bytes/str)
  - direct JWK mapping (dict with kty='EC', crv='secp256k1', x, y)
  Signature format
  
- DER (ASN.1) by default; include {"fmt":"DER"} in the signature map.
- JOSE raw r||s: pass opts={"format":"RAW"} to sign/verify.
 
  
    
            
              Source code in swarmauri_signing_secp256k1/Secp256k1EnvelopeSigner.py
              | 296
297
298
299
300
301
302
303
304
305
306 | def supports(self) -> Mapping[str, Iterable[str]]:
    algs = ("ES256K", "ECDSA-SHA256")
    canons = ("json", "cbor") if _CBOR_OK else ("json",)
    return {
        "algs": algs,
        "canons": canons,
        "signs": ("bytes", "digest", "envelope", "stream"),
        "verifies": ("bytes", "digest", "envelope", "stream"),
        "envelopes": ("mapping",),
        "features": ("multi", "detached_only"),
    }
 | 
 
     
 
async
  
sign_bytes(key, payload, *, alg=None, opts=None)
            
              Source code in swarmauri_signing_secp256k1/Secp256k1EnvelopeSigner.py
              | 310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348 | async def sign_bytes(
    self,
    key: KeyRef,
    payload: bytes,
    *,
    alg: Optional[Alg] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> Sequence[Signature]:
    _ensure_crypto()
    if alg not in (None, "ES256K", "ECDSA-SHA256"):
        raise ValueError(
            "Unsupported alg for Secp256k1EnvelopeSigner. Use 'ES256K'."
        )
    sk = _keyref_to_private(key, passphrase=(opts or {}).get("passphrase"))
    if not isinstance(sk.curve, ec.SECP256K1):
        raise TypeError("Private key curve must be secp256k1.")
    der_sig = sk.sign(payload, ec.ECDSA(hashes.SHA256()))
    fmt = (opts or {}).get("format", "DER")
    sig_bytes = der_sig
    if isinstance(fmt, str) and fmt.upper() == "RAW":
        r, s = decode_dss_signature(der_sig)
        size_bytes = (sk.curve.key_size + 7) // 8
        sig_bytes = r.to_bytes(size_bytes, "big") + s.to_bytes(size_bytes, "big")
    kid = _kid_from_public(
        sk.public_key(),
        (opts or {}).get("kid_jwk_hint") if isinstance(opts, Mapping) else None,
    )
    return [
        _Sig(
            {
                "alg": "ES256K",
                "kid": kid,
                "sig": sig_bytes,
                "fmt": "RAW" if fmt == "RAW" else "DER",
            }
        )
    ]
 | 
 
     
 
async
  
verify_bytes(
    payload, signatures, *, require=None, opts=None
)
            
              Source code in swarmauri_signing_secp256k1/Secp256k1EnvelopeSigner.py
              | 350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411 | async def verify_bytes(
    self,
    payload: bytes,
    signatures: Sequence[Signature],
    *,
    require: Optional[Mapping[str, object]] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> bool:
    _ensure_crypto()
    min_signers = int((require or {}).get("min_signers", 1))
    allowed_algs = set((require or {}).get("algs", ("ES256K", "ECDSA-SHA256")))
    fmt_pref = (opts or {}).get("format", "DER")
    if not (opts and "pubkeys" in opts):
        raise ValueError(
            "verify_bytes requires opts['pubkeys'] with one or more secp256k1 public keys."
        )
    pubs: list[ec.EllipticCurvePublicKey] = []
    for entry in opts["pubkeys"]:  # type: ignore[index]
        pk = _keyref_to_public(entry)
        if not isinstance(pk.curve, ec.SECP256K1):
            raise TypeError("All verification public keys must be secp256k1.")
        pubs.append(pk)
    accepted = 0
    for sig in signatures:
        alg = sig.get("alg")
        if not isinstance(alg, str) or alg not in allowed_algs:
            continue
        sig_bytes = sig.get("sig")
        if not isinstance(sig_bytes, (bytes, bytearray)):
            continue
        any_verified = False
        for pk in pubs:
            try:
                if (isinstance(fmt_pref, str) and fmt_pref.upper() == "RAW") or (
                    isinstance(sig.get("fmt"), str)
                    and sig.get("fmt").upper() == "RAW"
                ):
                    size_bytes = (pk.curve.key_size + 7) // 8
                    if len(sig_bytes) != 2 * size_bytes:
                        raise InvalidSignature(
                            "Invalid RAW ECDSA signature length for secp256k1."
                        )
                    r = int.from_bytes(sig_bytes[:size_bytes], "big")
                    s = int.from_bytes(sig_bytes[size_bytes:], "big")
                    der = encode_dss_signature(r, s)
                    pk.verify(der, payload, ec.ECDSA(hashes.SHA256()))
                else:
                    pk.verify(bytes(sig_bytes), payload, ec.ECDSA(hashes.SHA256()))
                any_verified = True
                break
            except InvalidSignature:
                continue
        if any_verified:
            accepted += 1
            if accepted >= min_signers:
                return True
    return False
 | 
 
     
 
async
  
canonicalize_envelope(env, *, canon=None, opts=None)
            
              Source code in swarmauri_signing_secp256k1/Secp256k1EnvelopeSigner.py
              | 415
416
417
418
419
420
421
422
423
424
425
426 | async def canonicalize_envelope(
    self,
    env: Envelope,
    *,
    canon: Optional[Canon] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> bytes:
    if canon in (None, "json"):
        return _canon_json(env)  # type: ignore[arg-type]
    if canon == "cbor":
        return _canon_cbor(env)  # type: ignore[arg-type]
    raise ValueError(f"Unsupported canon: {canon}")
 | 
 
     
 
async
  
sign_envelope(key, env, *, alg=None, canon=None, opts=None)
            
              Source code in swarmauri_signing_secp256k1/Secp256k1EnvelopeSigner.py
              | 430
431
432
433
434
435
436
437
438
439
440 | async def sign_envelope(
    self,
    key: KeyRef,
    env: Envelope,
    *,
    alg: Optional[Alg] = None,
    canon: Optional[Canon] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> Sequence[Signature]:
    payload = await self.canonicalize_envelope(env, canon=canon, opts=opts)
    return await self.sign_bytes(key, payload, alg="ES256K", opts=opts)
 | 
 
     
 
async
  
verify_envelope(
    env, signatures, *, canon=None, require=None, opts=None
)
            
              Source code in swarmauri_signing_secp256k1/Secp256k1EnvelopeSigner.py
              | 442
443
444
445
446
447
448
449
450
451
452 | async def verify_envelope(
    self,
    env: Envelope,
    signatures: Sequence[Signature],
    *,
    canon: Optional[Canon] = None,
    require: Optional[Mapping[str, object]] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> bool:
    payload = await self.canonicalize_envelope(env, canon=canon, opts=opts)
    return await self.verify_bytes(payload, signatures, require=require, opts=opts)
 | 
 
     
 
abstractmethod
      async
  
sign_digest(key, digest, *, alg=None, opts=None)
        Produce detached signatures over a pre-computed message digest.
            
              Source code in swarmauri_core/signing/ISigning.py
              | 114
115
116
117
118
119
120
121
122
123
124 | @abstractmethod
async def sign_digest(
    self,
    key: KeyRef,
    digest: bytes,
    *,
    alg: Optional[Alg] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> Sequence[Signature]:
    """Produce detached signatures over a pre-computed message digest."""
    ...
 | 
 
     
 
abstractmethod
      async
  
sign_stream(key, payload, *, alg=None, opts=None)
        Produce detached signatures over streaming byte payloads.
Implementations MAY buffer the stream to reuse :meth:sign_bytes.
            
              Source code in swarmauri_core/signing/ISigning.py
              | 149
150
151
152
153
154
155
156
157
158
159
160
161
162
163 | @abstractmethod
async def sign_stream(
    self,
    key: KeyRef,
    payload: ByteStream,
    *,
    alg: Optional[Alg] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> Sequence[Signature]:
    """
    Produce detached signatures over streaming byte payloads.
    Implementations MAY buffer the stream to reuse :meth:`sign_bytes`.
    """
    ...
 | 
 
     
 
abstractmethod
      async
  
verify_stream(
    payload, signatures, *, require=None, opts=None
)
            
              Source code in swarmauri_core/signing/ISigning.py
              | 165
166
167
168
169
170
171
172
173 | @abstractmethod
async def verify_stream(
    self,
    payload: ByteStream,
    signatures: Sequence[Signature],
    *,
    require: Optional[Mapping[str, object]] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> bool: ...
 | 
 
     
 
abstractmethod
      async
  
verify_digest(
    digest, signatures, *, require=None, opts=None
)
        Verify detached signatures produced over a pre-computed digest.
            
              Source code in swarmauri_core/signing/ISigning.py
              | 228
229
230
231
232
233
234
235
236
237
238 | @abstractmethod
async def verify_digest(
    self,
    digest: bytes,
    signatures: Sequence[Signature],
    *,
    require: Optional[Mapping[str, object]] = None,
    opts: Optional[Mapping[str, object]] = None,
) -> bool:
    """Verify detached signatures produced over a pre-computed digest."""
    ...
 |