Metadata-Version: 2.4
Name: flux-node-signer
Version: 0.4.0
Summary: Signs for fluxnodes from a workstation: a delegate key, bindings and starts
Keywords: flux,fluxnode,blockchain,cryptocurrency,delegates,transaction,secp256k1
Author: David White
Author-email: David White <david@runonflux.io>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Requires-Dist: aiohttp>=3.14.3
Requires-Dist: base58>=2.1.1
Requires-Dist: certifi>=2026.10.18
Requires-Dist: coincurve>=21.0.0
Requires-Dist: pydantic>=2.12.5
Requires-Dist: pydantic-settings>=2.14.2
Requires-Dist: pyrage>=1.3.0
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: rich>=14.2.0
Requires-Dist: typer>=0.21.1
Requires-Python: >=3.13
Project-URL: Homepage, https://github.com/RunOnFlux/flux-node-signer
Project-URL: Repository, https://github.com/RunOnFlux/flux-node-signer
Project-URL: Issues, https://github.com/RunOnFlux/flux-node-signer/issues
Description-Content-Type: text/markdown

# flux-node-signer

Signs for fluxnodes from a workstation. It holds a delegate key an owner has named for
their nodes, reads the chain, and builds, signs and sends fluxnode transactions. It
reaches no node: what it needs from a node is handed to it.

## What it does

An owner names a key for a node (an outpoint) as a delegate, with one of two
permissions:

| Permission | May |
|---|---|
| start | start the node when it has left the list |
| bind | that, and set the node's keys |

Setting a node's keys starts nothing. A node whose keys are bound and which is not on
the list is started by its own machine when that is ready. A node that has been on the
list and left it is started by its owner or a delegate: `start` below.

| Command | What it does |
|---|---|
| `generate-delegate-key` | makes a key and writes it encrypted (age, by passphrase) |
| `delegate-link` | makes the link a provider gives an owner, whose wallet gives the key the bind permission from it |
| `view` | reports where each outpoint stands for a delegate key: not named, unbound, pending or bound, and what the key may do there |
| `bind` | binds nodes' keys from their links, with a version 7 keys transaction a bind delegate's key signs |
| `start` | starts nodes that are off the list, with a start any delegate's key signs: version 7 for a node with keys set, and version 6 for one with none until the identity enforcement height |
| `derive-pubkey`, `check-delegates`, `find-start-tx`, `test-connection` | helpers |

`delegate-link`, `view`, `bind` and `start` print one JSON document on standard
output and their errors on standard error, so a program can call them. The same
operations are a library: `flux_node_signer.signer` (`delegate_link`, `view`, `bind`,
`start`) over the formats in `flux_node_signer.identity`.

## A provider's work, end to end

The chain is reached through the public Flux API, or with `--transport rpc` through a
fluxd's JSON-RPC: `FLUX_RPC_HOST`, `FLUX_RPC_PORT`, `FLUX_RPC_USERNAME`,
`FLUX_RPC_PASSWORD`, or the `--rpc-*` options.

1. **Make the delegate key**, once:

   ```bash
   flux-node-signer generate-delegate-key --name delegate
   ```

2. **Give each owner a delegate link** for their nodes. The owner's wallet reads it,
   shows the key's fingerprint, and gives the key the bind permission for those
   outpoints. The owner compares the fingerprint with the one you show them.

   ```bash
   flux-node-signer delegate-link --key-file delegate.key.age <txid>:<n> [<txid>:<n> ...]
   ```

   ```json
   {
    "line": "FLUXBND1 <delegatekey> <proof> <txid>:<n>",
    "delegatekey": "<66 hex>",
    "fingerprint": "9c34 af45 edef 87cd e432 209c 54cd 5d05",
    "proof": "<128 hex>",
    "outpoints": ["<txid>:<n>"]
   }
   ```

3. **See which outpoints name the key**, and the state of each node's keys:

   ```bash
   flux-node-signer view --delegate-key <66 hex> <txid>:<n> [<txid>:<n> ...]
   ```

   Each entry's `standing` is `not-named`, `unbound`, `pending` (a keys transaction
   has set keys the node's machine has not confirmed with yet) or `bound`, and its
   `permission` is `start`, `bind` or null.

4. **Bind each node's keys.** A node's link is the line fluxd gives in
   `getfluxnodestatus` (`identity_link_text`, or by field in `identity_link`). The
   input is a JSON list:

   ```json
   [
    {"link": "FLUXID1 <txid>:<n> <identitykey> <proof> <drawkey> <nodekey> [<vouch>]",
     "collateral_pubkey": "<66 hex>"},
    {"link": {"outpoint": "<txid>:<n>", "identitykey": "...", "proof": "...",
              "drawkey": "...", "nodekey": "..."},
     "redeem_script": "<hex>"}
   ]
   ```

   ```bash
   flux-node-signer bind nodes.json --key-file delegate.key.age [--dry-run]
   ```

   For each entry the tool checks the link's proof, reads the outpoint's state, and
   states the basis the chain will hold it to: `new` (the outpoint is off the list
   and has never had keys), `vouched` (the link is vouched by the key the chain shows
   for the node) or `replaces` (another machine takes the node over). It signs
   nothing for a link whose proof fails, for an outpoint the key has no bind
   permission for, or for keys the chain already has. A `replaces` binding is refused
   unless `--allow-replace` is given. Each result carries the `outcome`, the `basis`,
   the keys transaction's `txid` and its hex. The command exits 2 when any entry was
   refused.

   Nothing more is sent for a new node: its machine starts it and confirms with the
   keys. The chain takes a signed transaction for 100 blocks from the height it was
   signed at, so one that is not mined in that time is built again.

5. **Start a node that has left the list**, by any delegate's key:

   ```json
   [{"outpoint": "<txid>:<n>", "node_key": "<hex>", "collateral_pubkey": "<66 hex>"}]
   ```

   ```bash
   flux-node-signer start nodes.json --key-file delegate.key.age [--dry-run]
   ```

   The start carries no keys. `node_key` is the node key the node's keys were set
   with (the `nodekey` of the link they were bound from); for keys in force the tool
   checks it against the proof on record. A node with no keys set is started by a
   version 6 start until the identity enforcement height, and from it not at all:
   bind its keys first.

A multisig collateral is named by its `redeem_script` in place of `collateral_pubkey`.

## Installation

### Prerequisites

- Python 3.13+
- [uv](https://github.com/astral-sh/uv) package manager
- Access to a Flux RPC node

### Install uv

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

### Install flux-node-signer

```bash
# From PyPI
pip install flux-node-signer
```

Or install from source:

```bash
# Clone the repository
git clone https://github.com/RunOnFlux/flux-node-signer.git
cd flux-node-signer

# Install with uv
uv sync

# Or install in development mode
uv sync --dev
```

### Verify Installation

```bash
# Activate the virtual environment
source .venv/bin/activate

# Test the CLI
flux-node-signer --help
```

## Quick Start

```bash
flux-node-signer test-connection --rpc-user <username> --rpc-password <password>
flux-node-signer start nodes.json --key-file delegate.key.age --dry-run
flux-node-signer start nodes.json --key-file delegate.key.age
```

`nodes.json` is the list of step 5 above. `--dry-run` builds and signs and sends
nothing: each result carries the transaction's hex and id.

## CLI Commands

### `start`

```bash
flux-node-signer start [OPTIONS] INPUT_FILE
```

Starts each node of a JSON list that is off the list, signed by a delegate's key.
Each entry has `outpoint` (`<txid>:<n>`), `node_key` (hex), and `collateral_pubkey`
or, for a multisig collateral, `redeem_script`.

The tool reads each outpoint from the chain and builds the start the chain takes for
it:

| The chain shows for the outpoint | The start |
|---|---|
| keys in force or pending | version 7, with no keys in it |
| no keys, below the identity enforcement height | version 6 |
| no keys, from the enforcement height | none: bind the node's keys first |
| the node is on the list | none: nothing to do |

Options: `--key-file`/`-k` (required), `--passphrase`/`-p`, `--dry-run`, and the
`--rpc-*` options. Each result carries the `outcome`, the transaction's `version`,
`txid` and hex. The command exits 2 when any entry was refused.

The chain is reached through the public Flux API by default (`--transport api`,
`--api-url`), or through a fluxd's JSON-RPC (`--transport rpc` and the `--rpc-*`
options). `view`, `bind` and `delegate-link` take the same options.

A node's keys and delegates are read with `getidentitykey` and
`listfluxnodedelegates`. Where the chain reached offers neither (a fluxd from before
node identity, or an API that does not pass them through), `start` takes the node to
have no keys set and builds the version 6 start without checking the delegate, and the
chain judges it; `bind` and `view` say that they need a chain that answers.

### `derive-pubkey`

Derive public key from a WIF private key.

```bash
flux-node-signer derive-pubkey WIF_PRIVATE_KEY
```

This utility helps you convert your private keys to public keys. Very useful when you have:
- Collateral private key → need collateral public key
- Fluxnode private key → need fluxnode public key

**Example:**
```bash
$ flux-node-signer derive-pubkey KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn
✓ Derived public key:
0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
```

### `test-connection`

Test RPC connection to Flux daemon.

```bash
flux-node-signer test-connection [OPTIONS]
```

## Getting Your Keys

This section explains how to get all the required parameters for the `start` command.

### 1. Collateral Transaction Hash & Index

From your wallet that sent the collateral:

```bash
# Find your collateral transaction
flux-cli listtransactions

# Get details
flux-cli gettransaction <txid>
```

Or from Zelcore: Check your transaction history for the 1000/12500/40000 FLUX send.

- **collateral_txhash**: The transaction ID (64 hex characters)
- **collateral_index**: Usually `0` or `1` (which output in the transaction)

### 2. Collateral Public Key

You need the **public key** for the address that holds the collateral.

**Option A: From Zelcore**
Zelcore doesn't easily show public keys, so you'll need the private key:
1. Export the private key from Zelcore for your collateral address
2. Use our utility:
```bash
flux-node-signer derive-pubkey <your_collateral_private_key_WIF>
```

**Option B: From flux-cli**
If you have the collateral address in flux-cli wallet:
```bash
# Get the address that holds collateral
flux-cli getaddressesbyaccount ""

# Get the private key (KEEP THIS SECURE!)
flux-cli dumpprivkey <your_collateral_address>

# Derive public key
flux-node-signer derive-pubkey <WIF_from_above>
```

### 3. Delegate Private Key

This is a **new key** you generate just for signing START transactions. You can:

**Option A: Generate with flux-cli**
```bash
# Generate a new key pair
flux-cli getnewaddress

# Export the private key
flux-cli dumpprivkey <new_address>
```

**Option B: Use your collateral private key** (simpler but less secure)
You can use the same WIF as your collateral private key. This is fine for testing.

The `delegate_key` parameter expects WIF format directly (e.g., `KwDi...`)

### 4. Fluxnode Public Key

Each fluxnode needs its own identity key.

**Option A: From your fluxnode**
If you're running a fluxnode:
```bash
# On the fluxnode server
flux-cli getfluxnodestatus | grep pubkey
```

**Option B: Generate new keys**
```bash
# Generate a new address
flux-cli getnewaddress

# Dump the private key
flux-cli dumpprivkey <address>

# Derive the public key
flux-node-signer derive-pubkey <WIF_private_key>
```

For multi-node benchmarks, generate one key pair per node.

### Summary: What You Actually Need

```bash
# 1. Find your collateral transaction
collateral_txhash="abc123..."  # From wallet/blockchain

# 2. Get your RPC credentials
rpc_user=$(grep rpcuser ~/.flux/flux.conf | cut -d= -f2)
rpc_password=$(grep rpcpassword ~/.flux/flux.conf | cut -d= -f2)

# 3. Delegate key (can be same as collateral for simplicity)
delegate_key="L..."  # Export from Zelcore or flux-cli

# 4. Fluxnode privkey (generate new for each node)
fluxnode_privkey="K..."  # Generate with flux-cli getnewaddress

# 5. Build the start (the node key is the fluxnode key's public half)
node_key=$(flux-node-signer derive-pubkey $fluxnode_privkey)
echo "[{\"outpoint\": \"$collateral_txhash:0\", \"node_key\": \"$node_key\", \"collateral_pubkey\": \"<66 hex>\"}]" > nodes.json
flux-node-signer start nodes.json \
  --key-file delegate.key.age \
  --rpc-user $rpc_user \
  --rpc-password $rpc_password \
  --dry-run
```

## Configuration

### Environment Variables

Create a `.env` file:

```bash
FLUX_RPC_HOST=127.0.0.1
FLUX_RPC_PORT=16124
FLUX_RPC_TIMEOUT=30
FLUX_OUTPUT_FORMAT=rich
```

See `examples/.env.example` for all options.

### RPC Authentication

The tool requires username/password authentication for all RPC connections.

**Get credentials from your flux.conf:**
```bash
grep rpcuser ~/.flux/flux.conf
grep rpcpassword ~/.flux/flux.conf
```

**Pass via CLI:**
```bash
flux-node-signer start nodes.json --key-file delegate.key.age --rpc-user <user> --rpc-password <pass>
```

**Or use environment variables:**
```bash
export FLUX_RPC_USERNAME=myuser
export FLUX_RPC_PASSWORD=mypassword
flux-node-signer start nodes.json --key-file delegate.key.age  # reads FLUX_RPC_USERNAME and FLUX_RPC_PASSWORD
```

## Transaction Format (version 6)

The version 7 keys, start and delegate transactions, a node's link and the delegate link are
built in `flux_node_signer.identity`.

### Structure

```
Header (4 bytes)              # nVersion | (fOverwintered << 31)
├─ nType: int8_t (0x02)       # FLUXNODE_START_TX_TYPE
├─ nFluxTxVersion: int32_t    # 0x0101 (NORMAL | DELEGATES)
├─ collateralIn: COutPoint    # 36 bytes (hash + index)
│  ├─ hash: uint256           # 32 bytes, little-endian
│  └─ n: uint32_t             # 4 bytes, little-endian
├─ collateralPubkey: CPubKey  # Compact size + 33 bytes
├─ pubKey: CPubKey            # Fluxnode key, compact size + 33 bytes
├─ sigTime: uint32_t          # 4 bytes, little-endian
├─ fUsingDelegates: bool      # 1 byte (0x01)
├─ delegateData:              # CFluxnodeDelegates
│  ├─ nDelegateVersion: int8_t (0x01)
│  ├─ nType: int8_t (0x02)    # SIGNING type
│  └─ (no keys for SIGNING)
└─ sig: vector<unsigned char> # Compact size + 65 bytes
```

### Byte Order

- **All integers**: Little-endian
- **Transaction hash**: Reversed (little-endian)
- **Public keys**: No reversal

### Signing Process

1. Serialize transaction without signature
2. Compute transaction hash (double SHA256)
3. Build message: `"Zelcash Signed Message:\n" + tx_hash_hex`
4. Hash message with SHA256
5. Sign with secp256k1 recoverable signature (65 bytes)

## Development

### Running Tests

```bash
# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov

# Run specific test file
uv run pytest tests/test_transaction.py

# Run specific test
uv run pytest tests/test_crypto.py::TestWIFDecoding::test_decode_mainnet_compressed
```

### Linting and Formatting

```bash
# Format code
uv run ruff format

# Lint code
uv run ruff check

# Type checking
uv run ty check
uv run pyright
```

### Project Structure

```
flux-node-signer/
├── src/
│   └── flux_node_signer/
│       ├── __init__.py          # Package exports
│       ├── __main__.py          # CLI: the version 6 commands and the helpers
│       ├── delegate_cli.py      # CLI: delegate-link, view, bind, start
│       ├── signer.py            # A delegate's work: view, bind, start, delegate link
│       ├── identity.py          # Version 7 formats: links, delegates, transactions
│       ├── chain.py             # What is read from the chain, and sending to it
│       ├── transaction.py       # Version 6 start transaction
│       ├── crypto.py            # Signatures, hashes, key encoding
│       ├── key_manager.py       # Encrypted key files
│       ├── rpc_client.py        # fluxd JSON-RPC client
│       ├── api_client.py        # Flux API client
│       ├── models.py            # Pydantic models
│       ├── config.py            # Configuration
│       └── exceptions.py        # Custom exceptions
├── tests/
│   ├── test_identity.py        # Version 7 formats against the specification's vectors
│   ├── test_signer.py          # Bindings and starts against a table of chain states
│   ├── test_delegate_cli.py    # The JSON commands
│   ├── test_transaction.py     # Version 6 transaction tests
│   ├── test_crypto.py          # Crypto tests
│   └── test_rpc_client.py      # RPC tests
├── examples/
│   ├── .env.example            # Environment config
│   ├── config.example.toml     # TOML config
├── pyproject.toml              # Project config
└── README.md                   # This file
```

## Library Usage

Binding nodes' keys as a bind delegate:

```python
import asyncio
from pathlib import Path

from flux_node_signer.chain import RpcChain
from flux_node_signer.crypto import decode_wif
from flux_node_signer.identity import NodeLink
from flux_node_signer.key_manager import DelegateKeyManager
from flux_node_signer.rpc_client import FluxRPCClient
from flux_node_signer.signer import Collateral, bind


async def main():
    delegate_key, _ = decode_wif(DelegateKeyManager.load_key(Path("delegate.key.age")))
    chain = RpcChain(
        FluxRPCClient(host="127.0.0.1", port=16124, username="user", password="pass")
    )
    # The line fluxd gives in getfluxnodestatus as identity_link_text
    link = NodeLink.parse(
        "FLUXID1 <txid>:<n> <identitykey> <proof> <drawkey> <nodekey>"
    )
    collateral = Collateral(pubkey=bytes.fromhex("<the collateral's public key>"))

    done = await bind(chain, delegate_key, link, collateral, send=False)
    print(done.json())  # outcome, basis, txid and the signed transaction


asyncio.run(main())
```

`view`, `start` and `delegate_link` are in the same module and return the documents
the commands print.

A version 6 delegated start:

```python
import asyncio
from flux_node_signer import (
    FluxnodeStartTransaction,
    FluxRPCClient,
    FluxAPIClient,
    decode_wif,
)


async def main():
    # Decode delegate key
    delegate_privkey, _ = decode_wif(
        "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"
    )

    # Build transaction
    tx = FluxnodeStartTransaction(
        collateral_txhash="1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d0",
        collateral_index=0,
        fluxnode_pubkey=bytes.fromhex(
            "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
        ),
    )

    # Sign transaction
    tx.sign(delegate_privkey)

    # Option 1: Send via public API (default, no credentials needed)
    api_client = FluxAPIClient()
    txid = await api_client.send_raw_transaction(tx.to_hex())
    print(f"Transaction sent via API: {txid}")

    # Option 2: Send via direct RPC (requires credentials)
    rpc_client = FluxRPCClient(
        host="127.0.0.1", port=16124, username="myuser", password="mypassword"
    )
    txid = await rpc_client.send_raw_transaction(tx.to_hex())
    print(f"Transaction sent via RPC: {txid}")


if __name__ == "__main__":
    asyncio.run(main())
```

## Troubleshooting

### "RPC authentication required"

You must provide RPC credentials. Get them from your flux.conf:

```bash
grep rpcuser ~/.flux/flux.conf
grep rpcpassword ~/.flux/flux.conf
```

Then use:
```bash
flux-node-signer start nodes.json --key-file delegate.key.age --rpc-user <user> --rpc-password <pass>
```

### "TX decode failed"

This usually means:
- Incorrect byte order (transaction hash must be reversed)
- Invalid public key format (must be compressed, 33 bytes)
- Incorrect serialization

Use `--dry-run` to see the transaction without sending it, and fluxd's
`decoderawtransaction` to read it:

```bash
flux-node-signer start nodes.json --key-file delegate.key.age --dry-run
```

### "bad-txns-in-belowout"

The collateral transaction output doesn't exist or is already spent.

Verify with:

```bash
flux-cli getrawtransaction <txhash> 1
```

### "Invalid signature"

Check:
- Delegate key is correct WIF format
- Public keys match the delegate key
- Transaction is signed before sending

## Security Considerations

### Private Key Handling

- Never commit private keys to version control
- Use `.env` files (add to `.gitignore`)
- Consider using encrypted storage
- Rotate keys periodically

### RPC Security

- Use RPC over localhost when possible
- Enable RPC authentication
- Use TLS for remote connections
- Firewall RPC port

### Transaction Validation

- Always verify transaction details before signing
- Use `--dry-run` and `--decode` for testing
- Double-check collateral amounts
- Verify fluxnode public keys

## Examples

See the `examples/` directory for:
- `.env.example` - Environment configuration
- `config.example.toml` - TOML configuration

## License

MIT License - see [LICENSE](LICENSE) file for details

## Contributing

Contributions welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Add tests for new features
4. Ensure all tests pass
5. Submit a pull request

## Support

- GitHub Issues: https://github.com/RunOnFlux/flux-node-signer/issues
- PyPI: https://pypi.org/project/flux-node-signer/

## Acknowledgments

- Built for the Flux ecosystem
- Uses secp256k1 cryptography via coincurve
- Transaction format follows Bitcoin-style serialization
- Inspired by fluxd's activefluxnode implementation
