Metadata-Version: 2.4
Name: rarebl
Version: 0.2.1
Summary: Rarebl signing SDK: build, verify and sign BTC, LTC, BCH, DASH, ETH and TRON transactions locally. Private keys never leave your machine.
Author: Rarebl
License: MIT
Project-URL: Homepage, https://docs.rarebl.com
Keywords: rarebl,bitcoin,litecoin,ethereum,tron,signing,sdk
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: fast
Requires-Dist: coincurve; extra == "fast"
Dynamic: license-file

# Rarebl Python SDK

One file, Python 3.9+, **standard library only** (the optional `coincurve` package is used automatically for constant-time signing when installed). Builds, verifies and signs transactions **on your machine**, so private keys never go to Rarebl or anyone else.

## Download

```bash
curl -fsSLO https://docs.rarebl.com/sdk/python/rarebl.py
echo "22af552c39d8f58fec4e46cb1065530f28fce743e31abd0c09e189e1aec40eac  rarebl.py" | sha256sum -c -
```

The checksum for every SDK file is in `https://docs.rarebl.com/sdk/SHA256SUMS`. Put `rarebl.py` next to your script (or on `PYTHONPATH`) and `import rarebl`. Or install it from PyPI: `pip install rarebl` (`pip install "rarebl[fast]"` adds `coincurve`). The PyPI package also installs the CLI as the command `rarebl-py` (the same as `python3 rarebl.py`).

## Send BTC

```python
import os, rarebl

c = rarebl.Rarebl()                                  # https://api.rarebl.com
key = open("btc.key").read().strip()                 # hex or WIF; never hard-code it
txid = c.transfer(chain="btc", from_="bc1q...sender", to="bc1q...recipient",
                  amount="0.001", key=key, priority="standard")
print(txid)
```

`transfer` asks the API to build the transaction, **recomputes every digest locally and checks that it pays exactly what you asked**, signs on your machine, then assembles and broadcasts. For BTC/LTC/BCH the sender address is watched automatically the first time.

## Send USDT on TRON

```python
txid = c.transfer(chain="tron", from_="T...sender", to="T...recipient", amount="25",
                  token="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", key=os.environ["TRON_KEY"],
                  max_fee=100_000_000)               # feeLimit cap in sun
```

USDT/USDC decimals are built in; for any other token pass `decimals=`. ETH works the same way (`chain="eth"`, `token="0xdac17f95..."`).

## Keys, addresses, signing

```python
k = rarebl.keys.generate("btc", "p2tr")              # {privateKey, wif, publicKey, address, outputKey, type}
rarebl.keys.fromPrivate("eth", "<64-hex>")           # also from_private
rarebl.address.derive("ltc", pubkey_hex, "p2wpkh")
rarebl.address.validate("bch", "bitcoincash:q...")   # {valid, type, normalized}

build = c.build({"chain": "btc", "from": [addr], "to": [{"address": to, "amount": "0.001"}], "priority": "fast"})
rarebl.verify_build(build, expect={"to": {"address": to, "amount": "0.001"}})   # raises VerifyError
sigs = rarebl.sign_build(build, key, expect={"to": {"address": to, "amount": "0.001"}})   # expect is required
c.assemble(build["unsigned"], sigs, broadcast=True)
rarebl.sign_digest(digest_hex, key, "ecdsa-secp256k1", 1)     # DER+sighash | schnorr-bip340 | ecdsa-secp256k1-recoverable
```

Chains and types: BTC/LTC `p2pkh`, `p2sh-p2wpkh`, `p2wpkh`, `p2tr`; BCH `p2pkh` (CashAddr, no prefix); DASH `p2pkh`; ETH; TRON. Errors are typed: `ApiError` (`.code`, `.reason`, `.detail`), `VerifyError`, `KeyMismatchError`, `EnvelopeError`.

`sign_build(build, keys, verify=True, expect=None, now=None, unsafe_no_expect=False, deterministic=False, prev_txs=None)` raises `InputError` without `expect` (it must contain `to`): without it nothing pins who is paid. Pass `unsafe_no_expect=True` to sign without pinning the recipients (the default fee caps still apply); `verify=False` also needs it. Legacy p2pkh inputs (btc, ltc, dash) must carry `unsigned.inputs[i].prevTx` (or you pass `prev_txs={txid: raw_hex}`): the SDK checks that it hashes to the outpoint and takes the amount from it.

`expect` (same shape as the JS SDK): `to` (`{address, amount | amountRaw}` or a list), `change` (extra change addresses; the input addresses always qualify), `token`, `decimals`, `opReturn`, `from`, `chain`, and fee caps `maxFee` (whole units), `maxFeeSats`, `maxFeeRaw` (ETH wei), `maxFeeLimit` (TRON sun). `amount: "max"` must leave no change output. Default caps when you give none: UTXO fee rate 1000 sat/vB (btc, ltc) or 50 sat/byte (bch, dash; override with `maxFeeRate` or an absolute `maxFee`); ETH `maxFeePerGas` 500 gwei (`maxFeePerGas`, wei), total fee 0.05 ETH (`maxFee`), tip at most max(5 gwei, maxFeePerGas/2) (`maxPriorityFeePerGas`, wei); TRON `feeLimit` 150 TRX (`maxFeeLimit`). A UTXO transaction with version other than 1 or 2, a non-zero locktime (`allowLocktime: True`) or a repeated outpoint is refused, and sighash `0x41` is accepted on bch only.

## Webhooks

```python
ok = rarebl.webhook.verify(signing_secret, raw_body_bytes, request.headers["X-Rarebl-Signature"], 300)
```

Pass the **raw** body, not re-serialised JSON (`tolerance_sec=0` or `None` turns the age check off; a malformed header returns `False`). It checks `t=<unix>,v1=<hex HMAC-SHA256(secret, t + "." + body)>` in constant time, accepts several `v1` values (secret rotation) and rejects timestamps older than the tolerance.

## Command line

```bash
python3 rarebl.py keygen --chain btc --type p2wpkh
python3 rarebl.py address --chain btc --type p2wpkh --key-file btc.key
python3 rarebl.py sign-build build.json --key-file btc.key --expect-to ADDR --expect-amount 0.001   # or --unsafe-no-expect
python3 rarebl.py transfer --chain btc --from ADDR --to ADDR --amount 0.001 --key-file btc.key --priority standard
python3 rarebl.py verify-webhook --secret-env RAREBL_WEBHOOK_SECRET --header 't=..,v1=..' --body-file body.raw
```

Keys are read from `--key-file`, `--key-env` or `--key-stdin`, never from a command-line argument, and are never printed (except by `keygen`, whose job is to print the new key).

## Security

- **Why local signing.** A private key that has been sent to a server is a key that server (and anything between you and it) can use. Here the API only sees public data and finished signatures. Rarebl cannot spend your funds and a breach of Rarebl cannot leak your keys.
- **`verify` is on by default and `expect` is required.** `sign_build` / `transfer` refuse to sign a digest they cannot recompute from the unsigned transaction (legacy, BIP143, BIP341, BCH FORKID, EIP-1559, TRON txID), and refuse a transaction that pays a different recipient or amount than `expect`/`transfer` say, sends change anywhere but back to you, or has an unreasonable fee. Without this check a compromised or buggy server could trick you into signing a payment to someone else. `verify=False` signs whatever digest it is given and needs `unsafe_no_expect=True`.
- **Hosted signing.** Hosted signing sends your private key to Rarebl over TLS. Signing locally with an SDK keeps keys on your side and is recommended. `rarebl.envelope.encrypt(signer_key, payload)` builds an envelope v2 (X25519 + HKDF-SHA256 + AES-256-GCM) for `tx/sign` / `tx/send`: `payload` is `{"privateKeys": [...], "op": "sign", "chain": "btc", "digests": [...]}` or `{"op": "send", "bind": rarebl.envelope.bind_of("btc", {"address": to, "amount": "0.001"}), ...}`, valid for at most 300 seconds, one use. The request needs the header `X-Rarebl-Accept-Risk: hosted-signing`. `envelope.decrypt` opens address/new replies sealed to your `encryptTo` key. The helper needs the `cryptography` package for AES-GCM and raises a clear error without it; nothing else in the SDK does.
- **Constant-time only with `coincurve`.** Without it the secp256k1, Schnorr and X25519 code is pure Python: correct (RFC 6979, BIP340, RFC 7748 vectors) but **not constant-time**, so it leaks timing information. If `coincurve` is installed (`pip install coincurve`) key derivation and ECDSA/Schnorr signing use libsecp256k1 automatically (`rarebl.backend()` tells which; `RAREBL_PURE_PYTHON=1` forces the pure path). Either way use it on a machine you control, not on shared hosting or where an attacker can run code beside you. The X25519 envelope code is always pure Python.
- ECDSA nonces are RFC 6979 and signatures low-S, and every signature is verified after signing. BIP340 (p2tr) signatures use fresh random aux randomness; pass `deterministic=True` for reproducible output.
- Test keys in the repository are labelled TEST ONLY and are public. Never fund them.

## Tests

`python3 tests/run.py` (no dependencies; installs the `cryptography` package only to exercise the AES-GCM envelope). It runs RFC 6979 and BIP340 vectors, BIP143/BIP341 digests, address vectors for every chain, the shared vectors in `sdk/vectors/`, the envelope vectors and the webhook checks.
