Compare commits

..
11 Commits
Author SHA1 Message Date
plebandClaude Opus 5.5 aedda5bc86 docs: describe the fork vs upstream, add CLAUDE.md
- README: table of differences from upstream (master), pin a release
  tag in the usage example, drop references to personal hosts
- docs/fork-maintenance.md -> docs/maintenance.md: rewritten from a
  tracking note into a record of what was removed and an ongoing
  maintenance guide (mempool signers, per-release checklist)
- CLAUDE.md: branch layout, tag a release after consumer-facing
  changes (v0.MINOR.PATCH), how to check changes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:40:23 -08:00
plebandClaude Opus 5.5 230e5c539b mempool: 3.3.2
- Node 26, en-US-only frontend build
- Set NG_FORCE_TTY=false: under Nix's pty the Angular CLI spinner
  redraws forever and the frontend build never finishes
- generate.sh: verify release tags against pinned wiz or mononaut
  fingerprints (mononaut signs since v3.3.0; key fetched from GitHub)
- Newer mining-pool logos
- nginx: serve the English site at / instead of redirecting
- docs/fork-maintenance.md: reflect 3.3.2, Node 26 and the signer change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:30:23 -08:00
plebandClaude Opus 5.5 e1af5b794e Remove upstream tests, docs, examples, dev env and release tooling
Replace upstream's README with a short one for this fork, and add
docs/fork-maintenance.md describing what was removed and how to
maintain the rest. Keeps helper/update-fixed-output-derivation.sh for
pkgs/mempool/generate.sh. There is no test suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:49:32 -08:00
plebandClaude Opus 5.5 5d7289532b Drop pinned nixpkgs inputs and the local lndinit
Take every package from the consumer's pkgs: bitcoind, lnd, electrs and
lndinit (0.1.3 -> nixpkgs' version; gen-seed and init-wallet flags are
unchanged). The flake now has a single nixpkgs input. Removes
useVersionLockedPkgs, pinned.nix, nixpkgs-pinned.nix, shell.nix and the
update-flake helper that generated pinned.nix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:45:22 -08:00
plebandClaude Opus 5.5 0b8304395b Remove presets
Squirtle's settings from secure-node.nix and enable-tor.nix now live in
nix-pleb's squirtle config. The other presets had no users.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:44:25 -08:00
plebandClaude Opus 5.5 6e13a8b7ad Remove unused services and support features
Squirtle runs bitcoind, lnd, electrs and mempool. Remove every other
service module and its packages (clightning and plugins, joinmarket,
btcpayserver/nbxplorer, rtl, liquid, lndconnect, loop, pool, charge-lnd,
fulcrum, hardware-wallets, python-packages, bitcoind_29), plus the
support features squirtle doesn't use: netns-isolation, i2p support in
bitcoind, backups, versioning, obsolete-options and the krops/nixops
deployment modules.

mempool loses its electrumServer option and always uses electrs.

Squirtle's system is unchanged on 26.05 apart from two blank lines in
bitcoin.conf, and it now evaluates on 26.11 without the i2pd patch on
branch nixos-26.11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:43:16 -08:00
Jonas Nick da27f27026 fetch-release: fix signature verification!
`gpg --verify nar-hash.txt.asc` with a single argument lets gpg pick the
verification mode from the file's packet structure. For a real detached
signature it hashes the sibling nar-hash.txt, but for an inline signed
message it verifies the payload embedded in the .asc itself, never reads
nar-hash.txt, prints "not a detached signature; file was NOT verified!"
and still exits 0. The `&> /dev/null` hid that warning.
2026-08-31 08:12:01 +00:00
Jonas Nick 4e418e56be SECURITY: add haoxucu to wall of fame 2026-08-31 07:07:23 +00:00
Jonas Nick c4f172441d README: add archival notice 2026-08-15 16:09:51 +00:00
Jonas Nick 37931e5288 Merge fort-nix/nix-bitcoin#848: lnd: don't pass the admin macaroon in curl argv
df184b6e06 lnd: don't pass the admin macaroon in `curl` argv (Jonas Nick)

Pull request description:

Top commit has no ACKs.

Tree-SHA512: d18fa7176c59f33a38222a2d3d44320769ac83e091104594a9572e44ce38205d341767ea598da1b5500208c1e9f6645ed5c3b9390438d95912e44d1c5f3a4752
2026-08-13 10:44:26 +00:00
Jonas Nick df184b6e06 lnd: don't pass the admin macaroon in curl argv
`lnd-create-macaroons` interpolated the hex-encoded admin macaroon into
`curl`'s argv, where any local user could read it from world-readable
`/proc/<pid>/cmdline`. The unit's `ProtectProc=invisible` doesn't apply,
because `nbLib.rootScript`'s `+` prefix disables sandboxing for the
process. Pass the header on a file descriptor instead, so the credential
never enters any argv (`printf` is a bash builtin); the request sent to
lnd is unchanged. Only configurations with a non-empty
`services.lnd.macaroons` were affected, which `services.charge-lnd` and
`services.btcpayserver` with `lightningBackend = "lnd"` set automatically.
2026-08-12 18:02:07 +00:00
175 changed files with 306 additions and 13818 deletions
-55
View File
@@ -1,55 +0,0 @@
name: nix-bitcoin tests
on: [push, pull_request]
env:
CACHIX_SIGNING_KEY: ${{ secrets.CACHIX_SIGNING_KEY }}
# Strategy:
# Job `build_test_drivers` evals all VM tests and builds all test drivers in a single Nix build.
# Compared to launching a separate build job for each VM test, this avoids duplicated
# builds of derivations that the test drivers have in common.
#
# The job matrix `test_scenario` runs the VM tests.
# When job `build_test_drivers` determines that all tests have already been built successfully,
# job `test_scenario` is skipped via output variable `run_scenario_tests`.
jobs:
build_test_drivers:
runs-on: ubuntu-latest
outputs:
run_scenario_tests: ${{ steps.main.outputs.run_scenario_tests }}
steps:
- uses: actions/checkout@v4
- uses: cachix/install-nix-action@v31
- id: main
name: Build test drivers
run: |
echo "::group::Setup Nix env"
nix shell --inputs-from . nixpkgs#{bash,coreutils,cachix} -c ./test/ci/build_test_drivers.sh
test_scenario:
runs-on: ubuntu-latest
strategy:
matrix:
scenario:
- default
- netns
- netnsRegtest
- joinmarket-bitcoind-29
needs: build_test_drivers
if: needs.build_test_drivers.outputs.run_scenario_tests == 'true'
steps:
- uses: actions/checkout@v4
- uses: cachix/install-nix-action@v31
- run: nix shell --inputs-from . nixpkgs#{bash,coreutils,cachix} -c ./test/ci/build.sh ${{ matrix.scenario }}
check_flake:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: cachix/install-nix-action@v31
- run: nix flake check --all-systems
# FIXME: Re-enable when the nixos-search input is usable again.
# This is also disabled in ./test/run-tests.sh.
# - run: ./test/nixos-search/ci-test.sh
- run: ./test/shellcheck.sh
+43
View File
@@ -0,0 +1,43 @@
# CLAUDE.md
This is a trimmed fork of fort-nix/nix-bitcoin, which is archived. It has NixOS modules for bitcoind, lnd, electrs and mempool only. Read README.md for an overview and docs/maintenance.md for what was removed and what needs upkeep.
## Branches
- `main` is where development happens, and releases are tagged from it. Commit here.
- `master` holds upstream's archived tree for reference. Don't commit to it or move it.
- On gitea, the default branch is `master`, so consumers must pin a tag.
## Tag a release after every change
Consumers pin `?ref=refs/tags/vX.Y.Z`, so a change on `main` doesn't reach anyone until it's tagged. After committing a change that affects what consumers evaluate or build (modules, `pkgs/`, `flake.nix`, `flake.lock`), propose a new tag. Changes that only touch docs don't need one.
Versioning is `v0.MINOR.PATCH`. Ignore upstream's `v0.0.x` tags, which exist only in older local clones.
| Bump | When | Examples |
|---|---|---|
| MINOR | Package version bumps, new options, anything a consumer may have to change config for (removed or renamed options, changed defaults) | `v0.1.0` → `v0.2.0` |
| PATCH | Fixes and hash refreshes with no config impact | `v0.1.0` → `v0.1.1` |
Steps:
1. Find the latest fork tag with `git tag --list 'v0.[1-9]*' --sort=-v:refname | head -1`.
2. Create an annotated, unsigned tag: `git tag -a vX.Y.Z -m "<summary>"`. In the message, summarize the changes since the last tag and say whether the release has been deployed yet.
3. Push the branch and the tag with `git push origin main` and `git push origin vX.Y.Z`. Pushing is outward-facing, so confirm with the user first.
4. Remind the user to bump the tag in the consuming flake.
## Checking changes
There is no test suite.
- Run `nix flake check` for evaluation.
- After touching `pkgs/mempool/`, run `nix build .#mempool-backend .#mempool-frontend .#mempool-rust-gbt .#mempool-nginx-conf`.
- Runtime behaviour is only verified by deploying to a node. Say so when something hasn't been deployed.
## mempool updates
Use `pkgs/mempool/generate.sh`. It checks the release tag's signature against pinned fingerprints for wiz and mononaut. Never add a new signer fingerprint without the user's sign-off. See the "Updating mempool" section of docs/maintenance.md.
## Writing style
The README and docs describe a generic node. Don't name personal hosts or private configs.
+61 -115
View File
@@ -1,131 +1,77 @@
<p align="center"> # nix-bitcoin (satstack fork)
<img
width="320"
src="docs/img/nix-bitcoin-logo.png"
alt="nix-bitcoin logo">
</p>
<br/>
<p align="center">
<a href="https://github.com/fort-nix/nix-bitcoin/actions" target="_blank">
<img src="https://github.com/fort-nix/nix-bitcoin/actions/workflows/test.yml/badge.svg?branch=master"
alt="Github Actions status">
</a>
<a href="https://github.com/fort-nix/nix-bitcoin/releases/latest" target="_blank">
<img src="https://img.shields.io/github/v/release/fort-nix/nix-bitcoin" alt="GitHub tag (latest SemVer)">
</a>
<a href="https://github.com/fort-nix/nix-bitcoin/commits/master" target="_blank">
<img src="https://img.shields.io/github/commit-activity/y/fort-nix/nix-bitcoin" alt="GitHub commit activity">
</a>
<a href="https://github.com/fort-nix/nix-bitcoin/graphs/contributors" target="_blank">
<img src="https://img.shields.io/github/contributors-anon/fort-nix/nix-bitcoin" alt="GitHub contributors">
</a>
<a href="https://github.com/fort-nix/nix-bitcoin/releases" target="_blank">
<img src="https://img.shields.io/github/downloads/fort-nix/nix-bitcoin/total" alt="GitHub downloads">
</a>
</p>
<br/>
nix-bitcoin is a collection of Nix packages and NixOS modules for easily installing **full-featured Bitcoin nodes** with an emphasis on **security**. NixOS modules for a Bitcoin node running **bitcoind, lnd, electrs and
mempool**, with Tor onion services and host-generated secrets.
Overview This is a trimmed fork of [fort-nix/nix-bitcoin](https://github.com/fort-nix/nix-bitcoin),
--- which was archived in August 2026. Upstream's tree is preserved on the
nix-bitcoin can be used for personal or merchant wallets, public infrastructure or `master` branch. Development happens on `main`, and releases are tagged
for Bitcoin application backends. In all cases, the aim is to provide security and from `main`, starting at `v0.1.0`.
privacy by default. However, while nix-bitcoin is used in production today, it is
still considered experimental.
nix-bitcoin nodes can be deployed on dedicated hardware, virtual machines or containers. ## How it differs from upstream
The Nix packages and NixOS modules can be used independently and combined freely.
nix-bitcoin is built on top of Nix and [NixOS](https://nixos.org/) which provide powerful abstractions to keep it highly customizable and | | Upstream (`master`) | This fork (`main`) |
maintainable. Testament to this are nix-bitcoin's robust security features and its potent test framework. However, |---|---|---|
running nix-bitcoin does not require any previous experience with the Nix ecosystem. | Services | ~20: bitcoind, lnd, clightning (+ plugins, REST, replication), electrs, fulcrum, mempool, btcpayserver, rtl, joinmarket, liquid, loop, pool, charge-lnd, lndconnect, hardware wallets… | bitcoind, lnd, electrs, mempool |
| Support features | netns-isolation, i2p, backups, config versioning and obsolete-option migrations, krops/nixops deployment | Tor onion services, generated secrets, operator user, systemd hardening, nodeinfo |
| Presets | `secure-node`, `enable-tor`, `hardened`, `wireguard`, … | None: set the options you want in your own config |
| Flake inputs | nixpkgs, nixpkgs-unstable, nixpkgs-25_05, flake-utils, extra-container | nixpkgs only |
| Packages | Pinned set: lnd and others from unstable, clightning plugins, python packages, an old bitcoind, its own lndinit… | Everything from your nixpkgs, except mempool, which is built here |
| Flake outputs | `nixosModules`, `overlays`, `packages`, `legacyPackages`, `lib`, `templates`, tests | `nixosModules.default`, `overlays.default`, `packages.mempool-*` |
| Tests, docs, examples, dev shell, release signing | Yes | Removed |
Get started The code that's left is about 2,300 lines, down from about 16,500. The modules that remain keep upstream's option names, so a config that only uses those four services should carry over once it stops importing presets and stops setting removed options. See [docs/maintenance.md](docs/maintenance.md) for the full list of what was removed and how the fork is maintained.
---
- See the [examples](examples/README.md) for an overview of all features.
- To setup a new node from scratch, see the [installation instructions](docs/install.md).
- To add nix-bitcoin to an existing NixOS configuration, see [importable-configuration.nix](examples/importable-configuration.nix)
and the [Flake example](examples/flakes/flake.nix).
Docs ## Usage
---
Hint: To show a table of contents, click the button (![Github TOC button](docs/img/github-table-of-contents.svg)) in the
top left corner of the documents.
<!-- TODO-EXTERNAL: --> Pin a release tag. The repo's default branch is still upstream's `master`.
<!-- Change query to `nix-bitcoin` when upstream search has been fixed -->
* [NixOS options search](https://search.nixos.org/flakes?channel=unstable&sort=relevance&type=options&query=bitcoin)
* [Hardware requirements](docs/hardware.md)
* [Installation](docs/install.md)
* [Configuration and maintenance](docs/configuration.md)
* [Using services](docs/services.md)
* [FAQ](docs/faq.md)
Features ```nix
--- # flake.nix
A [configuration preset](modules/presets/secure-node.nix) for setting up a secure node inputs.nix-bitcoin = {
* All applications use Tor for outbound connections and support accepting inbound connections via onion services. url = "git+ssh://gitea@gitea.satstack.dev/pleb/nix-bitcoin.git?ref=refs/tags/v0.1.0";
inputs.nixpkgs.follows = "nixpkgs";
};
NixOS modules ([src](modules/modules.nix)) # in a nixosSystem's modules
* Application services inputs.nix-bitcoin.nixosModules.default
* [bitcoind](https://github.com/bitcoin/bitcoin) ```
* [clightning](https://github.com/ElementsProject/lightning) with support for announcing an onion service
and [database replication](docs/services.md#setup-clightning-database-replication).\
Available plugins:
* [clboss](https://github.com/ZmnSCPxj/clboss): automated C-Lightning Node Manager
* [currencyrate](https://github.com/lightningd/plugins/tree/master/currencyrate): currency converter
* [monitor](https://github.com/lightningd/plugins/tree/master/monitor): helps you analyze the health of your peers and channels
* [rebalance](https://github.com/lightningd/plugins/tree/master/rebalance): keeps your channels balanced
* [trustedcoin](https://github.com/nbd-wtf/trustedcoin) ([experimental](docs/services.md#trustedcoin)): replaces bitcoind with trusted public explorers
* [zmq](https://github.com/lightningd/plugins/tree/master/zmq): publishes notifications via ZeroMQ to configured endpoints
* [lnd](https://github.com/lightningnetwork/lnd) with support for announcing an onion service and [static channel backups](https://github.com/lightningnetwork/lnd/blob/master/docs/recovery.md)
* [Lightning Loop](https://github.com/lightninglabs/loop)
* [Lightning Pool](https://github.com/lightninglabs/pool)
* [charge-lnd](https://github.com/accumulator/charge-lnd): policy-based channel fee manager
* [lndconnect](https://github.com/LN-Zap/lndconnect): connect your wallet to lnd or
clightning [via WireGuard](./docs/services.md#use-zeus-mobile-lightning-wallet-via-wireguard) or
[Tor](./docs/services.md#use-zeus-mobile-lightning-wallet-via-tor)
* [Ride The Lightning](https://github.com/Ride-The-Lightning/RTL): web interface for `lnd` and `clightning`
* [mempool](https://github.com/mempool/mempool): Bitcoin visualizer, explorer, and API service
* [electrs](https://github.com/romanz/electrs): Electrum server
* [fulcrum](https://github.com/cculianu/Fulcrum): Electrum server (see [the module](modules/fulcrum.nix) for a comparison with electrs)
* [btcpayserver](https://github.com/btcpayserver/btcpayserver)
* [liquid](https://github.com/elementsproject/elements): federated sidechain
* [JoinMarket](https://github.com/joinmarket-org/joinmarket-clientserver)
* [JoinMarket Orderbook Watcher](https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/master/docs/orderbook.md)
* [bitcoin-core-hwi](https://github.com/bitcoin-core/HWI)
* Helper
* [netns-isolation](modules/netns-isolation.nix): isolates applications on the network-level via network namespaces
* [nodeinfo](modules/nodeinfo.nix): script which prints info about the node's services
* [backups](modules/backups.nix): duplicity backups of all your node's important files
* [operator](modules/operator.nix): configures a non-root user who has access to client tools (e.g. `bitcoin-cli`, `lightning-cli`)
Security ```nix
--- {
See [SECURITY.md](SECURITY.md) for the security policy and how to report a vulnerability. nix-bitcoin = {
generateSecrets = true; # writes /etc/nix-bitcoin-secrets on the host
operator = { enable = true; name = "alice"; };
nodeinfo.enable = true;
onionServices.bitcoind.public = true;
};
nix-bitcoin aims to achieve a high degree of security by building on the following principles: services.tor = { enable = true; client.enable = true; };
* **Simplicity:** Only services enabled in `configuration.nix` and their dependencies are installed, support for [doas](https://github.com/Duncaen/OpenDoas) ([sudo alternative](https://lobste.rs/s/efsvqu/heap_based_buffer_overflow_sudo_cve_2021#c_c6fcfa)), code is continuously reviewed and refined. services.bitcoind = { enable = true; tor.proxy = true; };
* **Integrity:** The Nix package manager guarantees that all dependencies are exactly specified, packages can be built from source to reduce reliance on binary caches, nix-bitcoin merge commits are signed, all commits are approved by multiple nix-bitcoin developers, upstream packages are cryptographically verified where possible, we use this software ourselves. services.lnd.enable = true;
* **Principle of Least Privilege:** Services operate with least privileges; they each have their own user and are restricted further with [systemd features](pkgs/lib.nix), [RPC whitelisting](modules/bitcoind-rpc-public-whitelist.nix) and [netns-isolation](modules/netns-isolation.nix). There's a non-root user *operator* to interact with the various services. services.electrs.enable = true;
* **Defense-in-depth:** nix-bitcoin supports a [hardened kernel](https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/profiles/hardened.nix), services are confined through discretionary access control, Linux namespaces, [dbus firewall](modules/security.nix) and seccomp-bpf with continuous improvements. services.mempool.enable = true; # also enables electrs
}
```
Note that if the machine you're deploying *from* is insecure, there is nothing nix-bitcoin can do to protect itself. Packages come from the consumer's nixpkgs (`pkgs.bitcoind`, `pkgs.lnd`,
`pkgs.electrs`, `pkgs.lndinit`). The only package built here is mempool
(`pkgs/mempool/`).
Security fund ## What's in the repo
---
The nix-bitcoin security fund is a 2 of 3 bitcoin multisig address open for donations, used to reward
security researchers who discover vulnerabilities in nix-bitcoin or its upstream dependencies.\
See [Security Fund](./SECURITY.md#nix-bitcoin-security-fund) for details.
Developing | Path | Contents |
--- |---|---|
See [dev/README](./dev/README.md). | `modules/` | `bitcoind`, `lnd`, `electrs`, `mempool`, plus `secrets/`, `operator`, `security`, `onion-services`, `onion-addresses`, `nodeinfo` |
| `pkgs/mempool/` | mempool backend, frontend, rust-gbt and nginx config. `generate.sh` bumps the version, verifies the release signature and refreshes hashes |
| `pkgs/lib.nix` | systemd hardening and Tor helpers shared by the modules |
| `helper/update-fixed-output-derivation.sh` | Used by `generate.sh` to recompute hashes |
Troubleshooting There is no test suite. Build your host's system before switching to a
--- new release, and roll back (`nixos-rebuild switch --rollback`) if a
If you are having problems with nix-bitcoin check the [FAQ](docs/faq.md) or submit an issue.\ service fails at runtime.
There's also a Matrix room at [#general:nixbitcoin.org](https://matrix.to/#/#general:nixbitcoin.org).\
We are always happy to help. ## License
MIT, see [LICENSE](LICENSE).
-104
View File
@@ -1,104 +0,0 @@
# Security Policy
## Reporting a Vulnerability
To report security issues send an encrypted email to the following nix-bitcoin developers or contact them via [matrix](https://matrix.org/).
| Name | GPG Fingerprint | Email | Matrix |
|---------------|----------------------------------------------------|-------------------------|------------------------------------------------------------------------------------|
| Jonas Nick | 36C7 1A37 C9D9 88BD E825 08D9 B1A7 0E4F 8DCD 0366 | jonasd.nick@gmail.com | [@nickler:nixbitcoin.org](https://matrix.to/#/@nickler:nixbitcoin.org) |
| Erik Arvstedt | 4E28 0A8C 1B33 4C86 C26B C134 3331 2B94 4DD9 7846 | erik.arvstedt@gmail.com | [@erikarvstedt:matrix.org](https://matrix.to/#/@erikarvstedt:matrix.org) |
| nixbitcoindev | 577A 3452 7F3E 2A85 E80F E164 DD11 F9AD 5308 B3BA | nixbitcoin@i2pmail.org | [@nixbitcoindev:nixbitcoin.org](https://matrix.to/#/@nixbitcoindev:nixbitcoin.org) |
You can import a GPG key by running the following command with that individual’s fingerprint: `gpg --keyserver hkps://keys.openpgp.org --recv-keys "<fingerprint>"`. Ensure that you put quotes around fingerprints containing spaces.
[Responsible disclosures](https://en.wikipedia.org/wiki/Coordinated_vulnerability_disclosure) may qualify for a reward from the nix-bitcoin security fund (see [below](#nix-bitcoin-security-fund)).
## Wall of Fame
*empty*
## nix-bitcoin security fund
The nix-bitcoin security fund rewards security researchers who discover and
report vulnerabilities in nix-bitcoin or its upstream dependencies.\
It is held on a 2 of 3 bitcoin multisig address and is open for donations:
```
bc1qrpnz05n0yznaj6yw82wy8dhwuqz86s87vdlhq4cu92fus9qal25s555wsy
```
([View balance](https://mempool.nixbitcoin.org/address/bc1qrpnz05n0yznaj6yw82wy8dhwuqz86s87vdlhq4cu92fus9qal25s555wsy))
Rewards are paid out as percentages of the total fund, rather than as fixed
amounts.
The nix-bitcoin developers [listed above](#reporting-a-vulnerability) each hold
one key to the multisig address and collectively form the nix-bitcoin developer
quorum.
### Eligible Vulnerabilities
The following types of vulnerabilities qualify for rewards, to the exclusion of
all other security vulnerabilities.
| Type | Description | Examples |
| :-: | :-: | :-: |
| Outright Vulnerabilities | Vulnerabilities in nix-bitcoin specific tooling (except CI tooling) | privilege escalation in SUID binary `netns-exec`, improper release signature verification through `fetch-release` |
| Violations of [PoLP](https://en.wikipedia.org/wiki/Principle_of_least_privilege) | nix-bitcoin services are given too much privilege over the system or unnecessary access to other nix-bitcoin services, or one of the nix-bitcoin isolation measures is incorrectly implemented | `netns-isolation` doesn't work, RTL has access to bitcoin RPC interface or files |
| Vulnerabilities in Dependencies | A vulnerability in any dependency of a nix-bitcoin installation with a configuration consisting of any combination of the following services: bitcoind, clightning, lnd, electrs, joinmarket, btcpayserver, liquidd.<br />**Note:** The vulnerability must first be reported to and handled by the maintainers of the dependency before it qualifies for a reward| Compromised NixOS expression pulls in malicious package, JoinMarket pulls in a python dependency with a known severe vulnerability |
| Bad Documentation | Our documentation suggests blatantly insecure things | `install.md` tells you to add our SSH keys to your root user |
| Compromise of Signing Key | Compromise of the nix-bitcoin signing key, i.e., `0xB1A70E4F8DCD0366` | Leaking the key, managing to sign something with it |
### Reward
Researchers qualify for a maximum reward[^1] of 10% of the total fund holdings for
reporting any vulnerability that matches the above eligibility requirements. If
a vulnerability or any combination of a number of vulnerabilities that meet the
above-described eligibility requirements can lead to a realistic attack on
nix-bitcoin users, researchers qualify for a higher maximum reward[^1] depending
the final outcome of the attack scenario:
| Outcome | Description | Maximum Reward of Total Fund[^1] |
| :-: | :-: | :-: |
| Loss of Funds | Attack allows stealing or destroying user's funds | 50 % |
| Loss of Privacy | Attack allows exfiltrating sensitive information or otherwise attributing a user's real world identity to his nix-bitcoin node or funds held/managed thereon without the user specifically opting-in to this (e.g., by disabling the `secure-node` preset) | 25 % |
| Denial of Service | Attack allows crashing a service or otherwise denying a user service from his node | 25 % |
All other reported vulnerabilities which meet the above requirements without a
clear and plausible attack scenario receive a maximum reward[^1] of 10% of the
fund.
[^1]: Rewards are subject to a discount at the discretion of the nix-bitcoin
developer quorum for reasons such as insignificance of the vulnerability or
obscurity of the victim's required configuration, as well as simple mitigation
(i.e. the attack should have been mitigated anyway by common-sense security
measures) or complex/unlikely attack execution.
### Policy
* Vulnerabilities must be [responsibly
disclosed](https://en.wikipedia.org/wiki/Coordinated_vulnerability_disclosure).
* E2EE: Vulnerabilities must be disclosed via end-to-end encrypted communication
methods, such as PGP E-Mail or Matrix.
* Wall of Fame: In addition to the above rewards, security researchers will also
be added to the Wall of Fame, unless, of course, they wish to remain
anonymous.
* First come, first serve: Rewards are awarded strictly on a first come, first
serve basis from the date they were responsibly disclosed in their entirety.
Multiple reports from the same researcher can either be bundled for a higher
likelihood of receiving the full maximum reward or rewarded individually,
proportional to the remaining amount.
* Exclusion of dependencies with existing bug bounty programms: Software which
is covered by an existing bug bounty program is not eligible for rewards under
the "Vulnerabilities in Dependencies" category.
* Exclusion of dependencies with known vulnerabilities that are in the process
of being patched: Software with a known vulnerability where there is reason to
believe that the patch is still under development or simply has not yet been
ported to NixOS, due to the relative recency of the patch, is not eligible for
rewards under the "Vulnerabilities in Dependencies" category.
* Termination: The fund can be terminated at any time by the quorum of key
holders in which case the holdings are donated to non-profit organizations.
* This document may be updated over time to ensure smooth and purposeful
operation of the fund as an incentive for security researchers to investigate
and report vulnerabilities in the nix-bitcoin ecosystem.
-101
View File
@@ -1,101 +0,0 @@
This directory contains docs and helper scripts for developing and debugging:
- [`dev.sh`](./dev.sh): misc dev helpers
- [`dev-features.sh`](./dev-features.sh): helpers for developing specific
nix-bitcoin features, like services
- [`topics`](./topics) features specific topics
- [`dev-scenarios.nix`](./dev-scenarios.nix): extra test scenarios used in the above scripts
See also: [test/README.md](../test/README.md)
## Run a dev shell
There are two ways to run a dev shell:
### 1. Run command `nix develop`
This starts a shell with [`test/run-tests.sh`](../test/run-tests.sh) and
the scripts in dir [`helper`](../helper) added to `PATH`.
### 2. Setup and start the `direnv` dev env
This is an opinionated, [direnv](https://direnv.net/)-based dev env, optimized for developer experience.
[`dev-env/create.sh`](./dev-env/create.sh) creates a git repo with the following contents:
- Dir `src` which contains the nix-bitcoin repo
- Dir `bin` for helper scripts
- File `scenarios.nix` for custom test scenarios
- File `.envrc` that defines a [direnv](https://direnv.net/) environment,
mainly for adding nix-bitcoin and helper scripts to `PATH`
#### Installation
1. [Install direnv](https://direnv.net/docs/installation.html).\
If you use NixOS (and Bash as the default shell), just add the following to your system config:
```nix
environment.systemPackages = [ pkgs.direnv ];
programs.bash.interactiveShellInit = ''
eval "$(direnv hook bash)"
'';
```
2. Create the dev env:
```bash
# Set up a dev environment in dir ~/dev/nix-bitcoin.
# The dir is created automatically.
./dev-env/create.sh ~/dev/nix-bitcoin
cd ~/dev/nix-bitcoin
# Enable direnv
direnv allow
```
3. Optional: Editor integration
- Add envrc support to your editor
- Setup your editor so you can easily execute lines or paragraphs from a shell script
file in a shell.\
This simplifies using dev helper scripts like [`./dev.sh`](./dev.sh).
#### Explore the dev env
```bash
# The direnv is automatically activated when visiting any subdir of ~/dev/nix-bitcoin
cd ~/dev/nix-bitcoin
ls -al . bin lib
# The direnv config file
cat .envrc
# You can use this file to define extra scenarios
cat scenarios.nix
# Binary `dev-run-tests` runs nix-bitcoin's `run-tests.sh` with extra scenarios from ./scenarios.nix
# Example:
# Run command `nodeinfo` in `myscenario` (defined in ./scenarios.nix) via a container
dev-run-tests -s myscenario container --run c nodeinfo
# Equivalent (shorthand)
te -s myscenario container --run c nodeinfo
# Run the tests for `myscenario` in a VM
te -s myscenario
# Start an interactive shell inside a VM
te -s myscenario vm
```
See also: [test/README.md](../test/README.md)
## Adding a new service
It's easiest to use an existing service as a template:
- [electrs.nix](../modules/electrs.nix): a basic service
- [clightning.nix](../modules/clightning.nix): simple, but covers a few more features.\
(A `cli` binary and a runtime-composed config to include secrets.)
- [rtl.nix](../modules/rtl.nix): includes a custom package, defined in [pkgs/rtl](../pkgs/rtl).\
Most other services use packages that are already included in nixpkgs.
## Switching to a new NixOS release
- Run command `update-flake.sh 26.05`
- Treewide: check if any `TODO-EXTERNAL` comments can be resolved
-65
View File
@@ -1,65 +0,0 @@
#!/usr/bin/env bash
# shellcheck disable=SC2016
set -euo pipefail
destDir=${1:-nix-bitcoin}
scriptDir=$(cd "${BASH_SOURCE[0]%/*}" && pwd)
mkdir -p "$destDir/"{bin,lib}
cd "$destDir"
if [[ ! -e src ]]; then
echo "Cloning fort-nix/nix-bitcoin"
git clone https://github.com/fort-nix/nix-bitcoin src
fi
echo 'export root=$PWD
export src=$root/src
PATH_add bin
PATH_add src/helper' > .envrc
if [[ ! -e scenarios.nix ]]; then
cp "$scriptDir/template-scenarios.nix" scenarios.nix
fi
install -m 755 <(
echo '#!/usr/bin/env bash'
echo 'exec run-tests.sh --extra-scenarios "$root/scenarios.nix" "$@"'
) bin/dev-run-tests
install -m 755 <(
echo '#!/usr/bin/env bash'
echo 'exec $root/src/test/run-tests.sh --out-link-prefix /tmp/nix-bitcoin/test "$@"'
) bin/run-tests.sh
ln -sfn dev-run-tests bin/te
## nix-bitcoin-firejail
echo '# Add your shell config files here that should be accessible in the sandbox
whitelist ${HOME}/.bashrc
read-only ${HOME}/.bashrc' > lib/nix-bitcoin-firejail.conf
install -m 755 <(
echo '#!/usr/bin/env bash'
echo '# A sandbox for running shells/binaries in an isolated environment:'
echo '# - The sandbox user is the calling user, with all capabilities dropped'
echo '# and with no way to gain new privileges (e.g. via `sudo`).'
echo '# - $HOME is bind-mounted to a dir that only contains shell config files and files required by direnv.'
echo '#'
echo '# You can modify the firejail env by editing `lib/nix-bitcoin-firejail.conf` in your dev env dir.'
echo 'exec firejail --profile="$root/lib/nix-bitcoin-firejail.conf" --profile="$root/src/dev/dev-env/nix-bitcoin-firejail.conf" "$@"'
) bin/nix-bitcoin-firejail
echo "1" > lib/dev-env-version
## git
echo '/src' > .gitignore
if [[ ! -e .git ]]; then
git init
git add .
git commit -a -m init
fi
-16
View File
@@ -1,16 +0,0 @@
pkgs:
pkgs.mkShell {
shellHook = ''
# A known rev from the master branch to test whether `nix develop`
# is called inside the nix-bitcoin repo
rev=5cafafd02777919c10e559b5686237fdefe920c2
if git cat-file -e $rev &>/dev/null; then
root=$(git rev-parse --show-toplevel)
export PATH=$root/test:$root/helper:$PATH
else
echo 'Error: `nix develop` must be called inside the nix-bitcoin repo.'
exit 1
fi
'';
}
-25
View File
@@ -1,25 +0,0 @@
include default.local
include globals.local
include disable-common.inc
include disable-programs.inc
caps.drop all
netfilter
noinput
nonewprivs
noroot
notv
novideo
protocol unix,inet,inet6
seccomp
## Enable features
allow-debuggers
# Enable direnv configs
whitelist ${HOME}/.config/direnv
read-only ${HOME}/.config/direnv
whitelist ${HOME}/.local/share/direnv
read-only ${HOME}/.local/share/direnv
-20
View File
@@ -1,20 +0,0 @@
{ pkgs, lib, scenarios, nix-bitcoin }:
with lib;
rec {
# For more examples, see `scenarios` and `exampleScenarios` in ./src/test/tests.nix
template = { config, pkgs, lib, ... }: {
imports = [
(nix-bitcoin + "/modules/presets/secure-node.nix")
scenarios.netnsBase
scenarios.regtestBase
];
test.container.enableWAN = true;
test.container.exposeLocalhost = true;
};
myscenario = { config, pkgs, lib, ... }: {
services.clightning.enable = true;
nix-bitcoin.nodeinfo.enable = true;
};
}
-320
View File
@@ -1,320 +0,0 @@
# shellcheck disable=SC2086,SC2154
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Run tests
# See ../test/README.md for a tutorial
# and ../test/run-tests.sh for a complete documentation
# Start a shell in a container
run-tests.sh -s electrs container
# Run a command in a container.
# The container is deleted afterwards.
run-tests.sh -s electrs container --run c journalctl -u electrs
# Run a bash command
run-tests.sh -s bitcoind container --run c bash -c "sleep 1; journalctl -u bitcoind"
run-tests.sh -s '{
imports = [ scenarios.regtestBase ];
services.electrs.enable = true;
}' container --run c journalctl -u electrs
run-tests.sh -s "{
services.electrs.enable = true;
nix-bitcoin.nodeinfo.enable = true;
}" container --run c nodeinfo
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Get generic node infos
# Start container shell
run-tests.sh -s bitcoind container
# Run commands inside the shell:
# The node's services
c systemctl status
# Failed units
c systemctl list-units --failed
# Analyze container boot performance
c systemd-analyze critical-chain
# Listening TCP sockets
c netstat -nltp
# Listening sockets
c netstat -nlp
# The container root filesystem
ls -al /var/lib/nixos-containers/nb-test
# The container root filesystem on NixOS systems with stateVersion < 22.05
ls -al /var/lib/containers/nb-test
# Start a shell in the context of a service process.
# Must be run inside the container (enter with cmd `c`).
enter_service() {
name=$1
pid=$(systemctl show -p MainPID --value "$name")
IFS=- read -r uid gid < <(stat -c "%u-%g" "/proc/$pid")
nsenter --all -t "$pid" --setuid "$uid" --setgid "$gid" bash
}
enter_service clightning
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# bitcoind
run-tests.sh -s bitcoind container
c systemctl status bitcoind
c systemctl cat bitcoind
c journalctl --output=short-precise -u bitcoind
ls -al /var/lib/nixos-containers/nb-test/var/lib/bitcoind
c bitcoin-cli getpeerinfo
c bitcoin-cli getnetworkinfo
c bitcoin-cli getblockchaininfo
run-tests.sh -s '{
imports = [ scenarios.regtestBase ];
services.bitcoind.enable = true;
}' container
address=$(c bitcoin-cli getnewaddress)
echo $address
c bitcoin-cli generatetoaddress 10 $address
# Run bitcoind with network access
run-tests.sh -s "{
test.container.enableWAN = true;
services.bitcoind.enable = true;
}" container --run c journalctl -u bitcoind -f
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# clightning
run-tests.sh -s clightning container
c systemctl status clightning
c journalctl --output=short-precise -u clightning
c lightning-cli getinfo
# Plugins
run-tests.sh -s "{
services.clightning.enable = true;
test.features.clightningPlugins = true;
}" container
c lightning-cli plugin list
# Show plugin config
nix eval --raw .#makeTest --apply '
makeTest: let
config = (makeTest {
config = {
services.clightning.enable = true;
test.features.clightningPlugins = true;
};
}).nodes.machine;
in
config.services.clightning.extraConfig
'
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# clightning-rest
run-tests.sh -s clightning-rest container
c systemctl status clightning-rest
c journalctl -u clightning-rest
c systemctl status clightning-rest-migrate-datadir
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# electrs
run-tests.sh -s "{
imports = [ scenarios.regtestBase ];
services.electrs.enable = true;
}" container
c systemctl status electrs
c systemctl cat electrs
c journalctl --output=short-precise -u electrs
electrs_rpc() {
echo "$1" | c nc 127.0.0.1 50001 | head -1 | jq
}
electrs_rpc '{"method": "server.version", "id": 0, "params": ["electrum/3.3.8", "1.4"]}'
electrs_rpc '{"method": "blockchain.headers.subscribe", "id": 0}'
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# fulcrum
run-tests.sh -s "{
imports = [ scenarios.regtestBase ];
services.fulcrum.enable = true;
}" container
c systemctl status fulcrum
c systemctl cat fulcrum
c journalctl --output=short-precise -u fulcrum
fulcrum_rpc() {
echo "$1" | c nc 127.0.0.1 50002 | head -1 | jq
}
fulcrum_rpc '{"method": "server.version", "id": 0, "params": ["electrum/3.3.8", "1.4"]}'
fulcrum_rpc '{"method": "blockchain.headers.subscribe", "id": 0}'
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# lnd
run-tests.sh -s lnd container
c systemctl status lnd
c journalctl -u lnd
c lncli getinfo
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# lightning-loop
run-tests.sh -s lightning-loop container
c systemctl status lightning-loop
c journalctl -u lightning-loop
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# btcpayserver
# https://docs.btcpayserver.org/Development/GreenFieldExample/
run-tests.sh -s btcpayserver-regtest container
c systemctl status btcpayserver
c journalctl -u btcpayserver
c systemctl cat btcpayserver
c systemctl status nbxplorer
c journalctl -u nbxplorer
## Access the API
request() {
local type=$1
local method=$2
local body=$3
shift; shift; shift
curl -sSL -H "Content-Type: application/json" -X $type --user "a@a.a:aaaaaa" \
-d "$body" "$@" "$ip:23000/api/v1/$method" | jq
}
post() {
local method=$1
local body=$2
shift; shift
request post "$method" "$body" "$@"
}
get() {
local method=$1
request get "$method"
}
# Create new user
post users '{"email": "a@a.a", "password": "aaaaaa", "isAdministrator": true}'
# Login with:
# user: a@a.a
# password: aaaaaa
runuser -u "$(logname)" -- xdg-open http://$ip:23000
# create store
post stores '{"name": "a", "defaultPaymentMethod": "BTC_LightningNetwork"}'
post stores '{"name": "a", "defaultPaymentMethod": "BTC"}'
store=$(get stores | jq -r .[].id)
echo $store
get stores/$store
get stores/$store/payment-methods
get stores/$store/payment-methods/LightningNetwork
# Connect to internal lightning node (internal API, doesn't work)
# Lightning must be manually setup via the webinterface.
post stores/$store/lightning/BTC/setup "" --data-raw 'LightningNodeType=Internal&ConnectionString=&command=save'
nix run --inputs-from . nixpkgs#lynx -- --dump http://$ip:23000/embed/$store/BTC/ln
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# liquid
run-tests.sh -s liquid container
c systemctl status liquidd
c elements-cli getpeerinfo
c elements-cli getnetworkinfo
c liquidswap-cli --help
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# tor
run-tests.sh container
c cat /var/lib/tor/state
c ls -al /var/lib/tor/onion/
c ls -al /var/lib/tor/onion/bitcoind
c ls -al /var/lib/tor/onion/clightning-rest
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# joinmarket
run-tests.sh -s joinmarket container
c systemctl status joinmarket
c journalctl -u joinmarket
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# joinmarket-ob-watcher
# This starts a container with WAN access, so that jm-ob-watcher
# can connect to the joinmarket IRC servers over Tor
run-tests.sh -s jm-ob-watcher container
c systemctl status joinmarket-ob-watcher
c journalctl -u joinmarket-ob-watcher
# Manually wait for string 'started http server, visit http://127.0.0.1:62601/'
# This can take >10 minutes when the Tor network is under heavy load.
# While connecting, errors like `We failed to connect and handshake with ANY directories...`
# may be shown.
c journalctl -f -u joinmarket-ob-watcher
# Check webinterface
c curl 127.0.0.1:62601
nix run --inputs-from . nixpkgs#lynx -- --dump $ip:62601
c curl -s 127.0.0.1:62601 | grep -i "orders found"
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# trustedcoin
run-tests.sh -s trustedcoin-online container
c systemctl start clightning
c journalctl -u clightning -f
# This should show log msgs like
# plugin-trustedcoin returning block 801409, 0000000000000000000482ddc4…, 1483968 bytes
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# mempool
run-tests.sh -s mempool-regtest container
c systemctl status mempool
c journalctl -u mempool
c systemctl status mysql
c nodeinfo
# Check backend
c curl -fsS localhost:8999/api/v1/blocks/1 | jq
c curl -fsS localhost:8999/api/v1/blocks/tip/height | jq
c curl -fsS localhost:8999/api/v1/address/1CGG9qVq2P6F7fo6sZExvNq99Jv2GDpaLE | jq
# Check frontend
c systemctl status nginx
c journalctl -u nginx
c curl -fsS localhost:60845
c curl -fsS localhost:60845/api/mempool | jq
c curl -fsS localhost:60845/api/blocks/1 | jq
c curl -fsS localhost:60845/api/v1/blocks/1 | jq
c curl -fsS localhost:60845/api/blocks/tip/height | jq
# Open frontend
# shellcheck disable=SC2154
runuser -u "$(logname)" -- xdg-open "http://$ip:60845/"
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# rtl
# see ./topics/rtl.sh
-121
View File
@@ -1,121 +0,0 @@
# Extra scenarios for developing and debugging
{ lib, scenarios }:
with lib;
{
btcpayserver-regtest = {
imports = [ scenarios.regtestBase ];
services.btcpayserver.enable = true;
test.container.exposeLocalhost = true;
# services.btcpayserver.lbtc = false;
# Required for testing interactive plugin installation
test.container.enableWAN = true;
};
# A node with internet access to test joinmarket-ob-watcher
jm-ob-watcher = {
services.joinmarket-ob-watcher.enable = true;
# Don't download blocks
services.bitcoind.extraConfig = ''
connect = 0;
'';
test.container.exposeLocalhost = true;
test.container.enableWAN = true;
};
rtl-dev = { config, pkgs, lib, ... }: {
imports = [
# scenarios.netnsBase
# scenarios.regtestBase
];
services.rtl = {
enable = true;
nodes.clightning = {
enable = true;
extraConfig.Settings.themeColor = "INDIGO";
};
# nodes.lnd.enable = false;
# nodes.reverseOrder = true;
nightTheme = true;
extraCurrency = "CHF";
};
test.container.exposeLocalhost = true;
nix-bitcoin.nodeinfo.enable = true;
# test.container.enableWAN = true;
};
wireguard-lndconnect-online = { config, pkgs, lib, ... }: {
imports = [
../modules/presets/wireguard.nix
scenarios.regtestBase
];
# 51820 (default wg port) + 1
networking.wireguard.interfaces.wg-nb.listenPort = 51821;
test.container.enableWAN = true;
# test.container.exposeLocalhost = true;
services.clightning.extraConfig = "disable-dns";
services.lnd = {
enable = true;
lndconnect = {
enable = true;
onion = true;
};
};
services.clightning = {
enable = true;
plugins.clnrest = {
enable = true;
lnconnect = {
enable = true;
onion = true;
};
};
};
services.clightning-rest = {
enable = true;
lndconnect = {
enable = true;
onion = true;
};
};
nix-bitcoin.nodeinfo.enable = true;
};
trustedcoin-online = {
services.clightning = {
enable = true;
tor.proxy = true;
plugins.trustedcoin.enable = true;
plugins.trustedcoin.tor.proxy = false;
};
# Don't run clightning on startup.
# This breaks the follwing dependency cycle:
# clightning
# -> network (trustedcoin fails and exits clightning without network access)
# -> multi-user.target (NixOS containers only gain network access after multi-user.target has completed)
# -> clightning
systemd.services.clightning.wantedBy = mkForce [];
test.container.enableWAN = true;
};
mempool-regtest = {
imports = [
scenarios.regtestBase
];
services.mempool = {
enable = true;
frontend = {
address = "0.0.0.0";
settings.LIQUID_ENABLED = true;
};
};
nix-bitcoin.nodeinfo.enable = true;
};
}
-129
View File
@@ -1,129 +0,0 @@
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Access nix-bitcoin flake packages
function nb() {
nix build --no-link --print-out-paths --print-build-logs "$@"
}
# A package defined by nix-bitcoin
nb .#joinmarket
# Equivalent
nb .#modulesPkgs.joinmarket
# A nix-bitcoin python package
nb .#nbPython3Packages.pyln-client
# A pinned package from nixpkgs(-unstable)
nb .#pinned.electrs
# Equivalent
nb .#modulesPkgs.electrs
## Eval packages
# Check version
nix eval .#joinmarket.version
# Eval derivation. --raw is needed due to a Nix bug (https://github.com/NixOS/nix/issues/5731)
nix eval --raw .#joinmarket; echo
# Check the version of a package in the nixpkgs(-unstable) inputs of the nix-bitcoin flake
nix eval --inputs-from . nixpkgs#electrs.version
nix eval --inputs-from . nixpkgs-unstable#electrs.version
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Inspect test systems
# Build a test system
nix build -o /tmp/system --print-build-logs "$(nix eval --raw .#tests.default --apply '
test: test.nodes.machine.system.build.toplevel.drvPath
')"
readlink /tmp/system
# Inspect system files
cat /tmp/system/activate
cat /tmp/system/etc/system/bitcoind.service
# Evaluate a config value
nix eval .#tests.default --apply '
test: test.nodes.machine.services.bitcoind.rpc.port
'
# Evaluate a config value in a custom test
nix eval .#makeTest --apply '
makeTest: let
config = (makeTest {
config = {
services.electrs.port = 10000;
};
}).nodes.machine;
in
config.services.electrs.port
'
# Evaluate a config value in a scenario defined in a file
nix eval --impure .#getTest --apply '
getTest: let
config = (getTest {
name = "default";
extraScenariosFile = builtins.getEnv("root") + "/scenarios.nix";
}).nodes.machine;
in
config.services.bitcoind.port
'
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Manually run a nix-bitcoin container, without the test framework.
# This allows sharing directories with the container host via option `bindMounts.`
read -rd '' src <<'EOF' || :
let
nix-bitcoin = builtins.getFlake "git+file://${toString ../.}";
in
nix-bitcoin.inputs.extra-container.lib.buildContainers {
system = "x86_64-linux";
inherit (nix-bitcoin.inputs) nixpkgs;
# legacyInstallDirs = true;
config = {
imports = [ ../test/lib/extra-container-workaround.nix ];
containers.nb-adhoc = {
# bindMounts."/shared" = { hostPath = "/my/hostpath"; isReadOnly = false; };
extra.addressPrefix = "10.200.255";
config = {
imports = [ nix-bitcoin.nixosModules.default ];
services.bitcoind.enable = true;
nix-bitcoin.generateSecrets = true;
nix-bitcoin.nodeinfo.enable = true;
};
};
};
}
EOF
nix run --impure --expr "$src"
# Run command in container
nix shell --impure --expr "$src" -c container --run c nodeinfo
# TODO-EXTERNAL: Use this instead when https://github.com/NixOS/nix/issues/7444 is fixed
# nix run --impure --expr "$src" -- --run c nodeinfo
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Show build logs from a CI test run
#
# If a specific test derivation was already built successfully, the test is not rerun
# and the CI logs don't show the test output.
# To view the test output:
# 1. Get the test store path at the end of the CI logs
# 2.
fetch_build_log() {
local log=$1
nix cat-store --store https://nix-bitcoin.cachix.org "$log/output.xml" |
nix shell --inputs-from . nixpkgs#html-tidy -c tidy -xml -i - > /tmp/build-output.xml
echo
echo "Fetched log to /tmp/build-output.xml"
}
# Set this to your store path
fetch_build_log /nix/store/0cdjhvg84jsp47f3357812zjmj2wmz94-vm-test-run-nix-bitcoin-default
# Show runtime
grep "script finished in" /tmp/build-output.xml
# View XML with node folding
firefox /tmp/build-output.xml
-70
View File
@@ -1,70 +0,0 @@
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Test Tor and WireGuard connections on a mobile device
# 1. Run container
run-tests.sh -s wireguard-lndconnect-online container
# 2. Test connecting via Tor
# Print QR codes for lnd, clightning-rest connections via Tor
c lndconnect
c lnconnect-clnrest
c lndconnect-clightning
# Add these to Zeus >= 0.9.0.
# To explicitly check if the connection is successful, press the node logo in the top
# left corner, and then "Node Info".
# Debug
c lndconnect --url
c lnconnect-clnrest --url
c lndconnect-clightning --url
# 3. Test connecting via WireGuard
# 3.1 Forward WireGuard port from the container host to the container
iptables -t nat -A PREROUTING -p udp --dport 51821 -j DNAT --to-destination 10.225.255.2
# 3.2. Optional: When your container host has an external firewall,
# forward the WireGuard port to the container host:
# - Port: 51821
# - Protocol: UDP
# - Destination: IPv4 of the container host
# 3.2 Print QR code and setup wireguard on the mobile device
c nix-bitcoin-wg-connect
c nix-bitcoin-wg-connect --text
# Print QR codes for lnd, clightning-rest connections via WireGuard
c lndconnect-wg
c lnconnect-clnrest-wg
c lndconnect-clightning-wg
# Add these to Zeus >= 0.9.0.
# To explicitly check if the connection is successful, press the menu button in the top
# left corner, and then "Node Info".
# Debug
c lndconnect-wg --url
c lnconnect-clnrest-wg --url
c lndconnect-clightning-wg --url
# 3.3.remove external firewall port forward, remove local port forward:
iptables -t nat -D PREROUTING -p udp --dport 51821 -j DNAT --to-destination 10.225.255.2
# Now exit the container shell
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Debug lndconnect
run-tests.sh -s wireguard-lndconnect-online container
c nodeinfo
c lndconnect --url
c lndconnect-wg --url
c lndconnect-clnrest --url
c lndconnect-clnrest-wg --url
c lndconnect-clightning --url
c lndconnect-clightning-wg --url
c lndconnect
c lndconnect-wg
c lndconnect-clightning
c lndconnect-clightning-wg
-45
View File
@@ -1,45 +0,0 @@
# shellcheck disable=SC2154
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Docs
# https://github.com/Ride-The-Lightning/RTL
# config options: https://github.com/Ride-The-Lightning/RTL/blob/master/.github/docs/Application_configurations.md
# https://github.com/Ride-The-Lightning/c-lightning-REST
# local src: ~/s/RTL/
# Browse API docs (in container shell)
runuser -u "$(logname)" -- xdg-open "http://$ip:4001/api-docs/"
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Debug the service
run-tests.sh -s rtl-dev container
c systemctl status rtl
c journalctl -u rtl
c cat /var/lib/rtl/RTL-Config.json
# Open webinterface. Password: a
runuser -u "$(logname)" -- xdg-open "http://$ip:3000"
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Build RTL manually
# [[~/s/RTL/dockerfiles/Dockerfile][dockerfile]]
# [[~/s/RTL/package.json][package.json]]
rtl_src=~/s/RTL
git clone https://github.com/Ride-The-Lightning/RTL "$rtl_src"
nix build -o /tmp/nix-bitcoin-dev/nodejs --inputs-from . nixpkgs#nodejs_22
# Start a shell in a sandbox
env --chdir "$rtl_src" nix-bitcoin-firejail --whitelist="$rtl_src" --whitelist=/tmp/nix-bitcoin-dev/nodejs
PATH=/tmp/nix-bitcoin-dev/nodejs/bin:"$PATH"
# Install
npm ci --omit=dev --omit=optional --no-update-notifier --ignore-scripts
# If the above fails, try: (details: https://github.com/Ride-The-Lightning/RTL/issues/1182)
npm ci --omit=dev --omit=optional --no-update-notifier --ignore-scripts --legacy-peer-deps
# Run
node rtl --help
git clean -xdf # Cleanup repo
-264
View File
@@ -1,264 +0,0 @@
# Managing your deployment
This section applies to users of the deployment method described in the [installation guide](./install.md).
## Deployment shell
Run command `nix-shell` in your deployment directory.\
You now have access to deployment commands:
- `deploy`\
Deploy the current configuration to your node.
- `eval-config`\
Locally evaluate the configuration. This is useful to check for configuration errors.
- `h`, `help`\
Show help
## Updating nix-bitcoin
Run `update-nix-bitcoin` from the deployment shell.\
This fetches the latest release, verifies its signatures and updates `nix-bitcoin-release.nix`.
# Customizing your configuration
## Get started with Nix
See [Nix - A One Pager](https://github.com/tazjin/nix-1p) for a short guide
to Nix, the language used in `configuration.nix`.\
You can follow along this guide by running command `nix repl` which allows you to interactively
evaluate Nix expressions.
For a general introduction to the Nix and NixOS ecosystem, see [nix.dev](https://nix.dev/).
## Set options
All features and services are configurable through options. You can find a list of
supported options at the top of each nix-bitcoin [module](../modules/modules.nix)
(Examples: [bitcoind.nix](../modules/bitcoind.nix), [btcpayserver.nix](../modules/btcpayserver.nix)).
Example: Set some `bitcoind` options by adding these lines to your `configuration.nix`:
```nix
# Use a custom data dir
services.bitcoind.dataDir = "/my/datadir";
# Enable txindex
services.bitcoind.txindex = true;
```
You can also use regular [NixOS options](https://search.nixos.org/options)
for configuring your system:
```nix
networking.hostName = "myhost";
time.timeZone = "UTC";
```
## Debug your configuration
To print the values of specific options of your config, add the following to your `configuration.nix`:
```nix
system.extraDependencies = let
debugVal = config.networking.firewall.allowedTCPPorts;
# More example options:
# debugVal = config.environment.systemPackages;
# debugVal = config.services.bitcoind.dataDir;
in lib.traceSeqN 3 debugVal [];
```
and run command `eval-config` from the deployment shell.
# Allowing external connections to services
## Allow peer connections to bitcoind
```nix
services.bitcoind = {
# Accept incoming peer connections
listen = true;
# Listen to connections on all interfaces
address = "0.0.0.0";
# Set this to also add IPv6 connectivity.
extraConfig = ''
bind=::
'';
# If you're using the `secure-node.nix` template, set this to allow non-Tor connections
# to bitcoind
tor.enforce = false;
# Also set this if bitcoind should not use Tor for outgoing peer connections
tor.proxy = false;
};
# Open the p2p port in the firewall
networking.firewall.allowedTCPPorts = [ config.services.bitcoind.port ];
```
## Allow bitcoind RPC connections from LAN
```nix
services.bitcoind = {
# Listen to RPC connections on all interfaces
rpc.address = "0.0.0.0";
# Allow RPC connections from external addresses
rpc.allowip = [
"10.10.0.0/24" # Allow a subnet
"10.50.0.3" # Allow a specific address
"0.0.0.0/0" # Allow all addresses
];
# Set this if you're using the `secure-node.nix` template
tor.enforce = false;
};
# Open the RPC port in the firewall
networking.firewall.allowedTCPPorts = [ config.services.bitcoind.rpc.port ];
```
## Allow connections to electrs
```nix
services.electrs = {
# Listen to connections on all interfaces
address = "0.0.0.0";
# Set this if you're using the `secure-node.nix` template
tor.enforce = false;
};
# Open the electrs port in the firewall
networking.firewall.allowedTCPPorts = [ config.services.electrs.port ];
```
You can use the same approach to allow connections to other services.
# Migrate existing services to nix-bitcoin
## Example: bitcoind
```shell
# 1. Stop bitcoind on your node
ssh root@nix-bitcoin-node 'systemctl stop bitcoind'
# Also stop bitcoind on the node that you'll be copying data from
# 2. Copy the data to the nix-bitcoin node
# Important: Add a trailing slash to the source path
rsync /path/to/existing/bitcoind-datadir/ root@nix-bitcoin-node:/var/lib/bitcoind
# 3. Fix data dir permissions on the nix-bitcoin node
ssh root@nix-bitcoin-node 'chown -R bitcoin: /var/lib/bitcoind'
# 4. Start bitcoind
ssh root@nix-bitcoin-node 'systemctl start bitcoind'
```
You can use the same workflow for other services.\
The default data dir path is `/var/lib/<service>` for all services.
Some services require extra steps:
- lnd
Copy your wallet password to `$secretsDir/lnd-wallet-password` (See: [Secrets dir](#secrets-dir)).
- btcpayserver
Copy the postgresql database:
```shell
# Export (on the other node)
sudo -u postgres pg_dump YOUR_BTCPAYSERVER_DB > export.sql
# Restore (on the nix-bitcoin node)
sudo -u postgres psql btcpaydb < export.sql
```
- joinmarket
Copy your wallet to `/var/lib/joinmarket/wallets/wallet.jmdat`.\
Write your wallet password, without a trailing newline, to
`$secretsDir/jm-wallet-password` (See: [Secrets dir](#secrets-dir)).
# Use bitcoind from another node
Here's how to use a bitcoind instance running on another node within a nix-bitcoin config:
```nix
imports = [ <nix-bitcoin/modules/presets/bitcoind-remote.nix> ];
services.bitcoind = {
enable = true;
# Address of the other node
address = "10.10.0.2";
rpc.address = "10.10.0.2";
# Some nix-bitcoin services require whitelisted bitcoind p2p connections
# to work reliably.
# Search for `whitelistedPort` in this repo to see the affected services.
# If you're using one of these services, either add a whitelisted p2p port
# on your remote node via `whitebind` and set it here:
whitelistedPort = <remote whitebind RPC port>;
#
# Or use the default p2p port and add `whitelist=<address of this node>` to
# your remote bitcoind config:
whitelistedPort = config.services.bitcoind.port;
rpc.users = let
# The fully privileged bitcoind RPC username of the other node
name = "myrpcuser";
in {
privileged.name = name;
public.name = name;
## Set this if you use btcpayserver
# btcpayserver.name = name;
## Set this if you use joinmarket-ob-watcher
# joinmarket-ob-watcher.name = name;
};
};
```
For each service that connects to bitcoind and has option
`services.<service>.tor.enforce` enabled (either explicitly or by importing
`secure-node.nix` or `enable-tor.nix`), you need to
allow the remote bitcoind connection:
```nix
systemd.services.<service>.serviceConfig.IPAddressAllow = [ ${services.bitcoind.rpc.address} ];
```
> The above configuration is only required if the remote bitcoind **is
> not** accessed via Tor.
Now save the password of the RPC user to the following files on your nix-bitcoin node:
```shell
$secretsDir/bitcoin-rpcpassword-privileged
$secretsDir/bitcoin-rpcpassword-public
## Only needed when set in the above config snippet
# $secretsDir/bitcoin-rpcpassword-btcpayserver
# $secretsDir/bitcoin-rpcpassword-joinmarket-ob-watcher
```
See: [Secrets dir](#secrets-dir)
Afterwards, restart `bitcoind`: `systemctl restart bitcoind`.
# Temporarily disable a service
Sometimes you might want to disable a service without removing the service user and
integration with other services, as it would happen when setting
`services.<service>.enable = false`.
Use the following approach:
```
systemd.services.<service>.wantedBy = mkForce [];
```
This way, the systemd service still exists, but is not automatically started.\
Note: This only works for services that are not required by other active services.
# Appendix
## Secrets dir
The secrets dir is set by option `nix-bitoin.secretsDir` and has the
following default values:
- If you're using the krops deployment method: `/var/src/secrets`
- Otherwise: `/etc/nix-bitcoin-secrets`
-19
View File
@@ -1,19 +0,0 @@
- **Q:** The clightning service is running but when I try to use it (f.e. by running
`lightning-cli getinfo` as user operator) all I get is `lightning-cli: Connecting
to 'lightning-rpc': Connection refused`.\
**A:** Check your clightning logs with `journalctl -eu clightning`. Do you see
something like `bitcoin-cli getblock ... false` failed? Are you using pruned mode?
That means that clightning hasn't seen all the blocks it needs to and it can't get
that block because your node is pruned. \
If you're just setting up a new node you can `systemctl stop clightning` and wipe
your `/var/lib/clightning` directory. Otherwise you need to reindex the Bitcoin
node.
- **Q:** My disk space is getting low due to nix.\
**A:** run `nix-collect-garbage -d`
- **Q:** Where is `sudo`?\
**A:** After [CVE-2021-3156](https://www.openwall.com/lists/oss-security/2021/01/26/3),
we've replaced `sudo` with OpenBSD's `doas` for users of the `secure-node.nix` template.
It has greatly reduced complexity and is therefore less likely to be a source of
severe vulnerabilities in the future.
-18
View File
@@ -1,18 +0,0 @@
Hardware requirements
---
* RAM: 2GB. ECC memory is better. Additionally, it's recommended to use DDR4 memory with
targeted row refresh (TRR) enabled (https://rambleed.com/).
* Disk space: 1 TB for an unpruned
instance of Bitcoin Core.
* This can be significantly lowered by enabling pruning.
Note: Pruning is not supported by `electrs` and `fulcrum`.
Tested low-end hardware includes:
- [Raspberry Pi 4](https://www.raspberrypi.org/products/raspberry-pi-4-model-b/)
- [PC Engines apu2c4](https://pcengines.ch/apu2c4.htm)
- [Gigabyte GB-BACE-3150](https://www.gigabyte.com/Mini-PcBarebone/GB-BACE-3150-rev-10)
- [Gigabyte GB-BACE-3160](https://www.gigabyte.com/de/Mini-PcBarebone/GB-BACE-3160-rev-10#ov)
Some hardware (including Intel NUCs) may not be compatible with the [hardened kernel preset](../modules/presets/hardened.nix)
(See https://github.com/fort-nix/nix-bitcoin/issues/39#issuecomment-517366093
for a workaround).
-1
View File
@@ -1 +0,0 @@
"nix-bitcoin-logo.png" is a derivative of "nix-snowflake.svg" (https://github.com/NixOS/nixos-artwork/blob/376ed4ba8dc2e611b7e8a62fdc680967ead5bd87/logo/nix-snowflake.svg) by Tim Cuthbertson, used under CC BY. "nix-bitcoin-logo.png" is licensed under CC BY by the nix-bitcoin developers.
-3
View File
@@ -1,3 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="16" height="16" viewBox="0 -2 16 16">
<path fill-rule="evenodd" d="M2 4a1 1 0 100-2 1 1 0 000 2zm3.75-1.5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zm0 5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zm0 5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zM3 8a1 1 0 11-2 0 1 1 0 012 0zm-1 6a1 1 0 100-2 1 1 0 000 2z"></path>
</svg>

Before

Width:  |  Height:  |  Size: 387 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

-342
View File
@@ -1,342 +0,0 @@
# Tutorial: Install and configure NixOS for nix-bitcoin on a dedicated machine
This tutorial describes how to manage your Bitcoin node comfortably from your personal computer with the deployment tool [krops](https://github.com/krebs/krops).
However, nix-bitcoin is agnostic to the deployment method and can be used with different or without such tools (see [examples](../examples/README.md)).
## 0. Preparation
1. Find a machine to deploy nix-bitcoin on (see [hardware.md](hardware.md)).
2. Optional: Make sure you have the latest firmware for your system (BIOS, microcode updates).
3. Optional: Disable Simultaneous Multi-Threading (SMT) in the BIOS
Researchers recommend disabling (SMT), also known as Hyper-Threading Technology in the Intel® world to significantly reduce the impact of speculative execution-based attacks (https://mdsattacks.com/).
## 1. NixOS installation
This is borrowed from the [NixOS manual](https://nixos.org/nixos/manual/index.html#ch-installation). Look there for more information.
1. Obtain latest [NixOS](https://nixos.org/nixos/download.html). For example:
```
wget https://releases.nixos.org/nixos/24.05/nixos-24.05.3164.63d37ccd2d17/nixos-minimal-24.05.3164.63d37ccd2d17-x86_64-linux.iso
# output: 35dd79596f12b159efc533400ba8f730d819eee2d1014683a658020c2b54ae0c
sha256sum nixos-minimal-24.05.3164.63d37ccd2d17-x86_64-linux.iso
```
Alternatively you can build NixOS from source by following the instructions at https://nixos.org/nixos/manual/index.html#sec-building-cd.
2. Write NixOS iso to install media (USB/CD). For example:
```
cp nixos-minimal-23.05.3701.e9b4b56e5a20-x86_64-linux.iso /dev/sdX
```
Replace /dev/sdX with the correct device name. You can find this using `sudo fdisk -l`
3. Boot the system and become root
```
sudo -i
```
You will have to find out if your hardware uses UEFI or Legacy Boot for the next step. You can do that, for example, by executing
```
ls /sys/firmware/efi
```
If the file exists you should continue the installation for UEFI otherwise for Legacy Boot.
4. Option 1: Partition and format for UEFI
```
parted /dev/sda -- mklabel gpt
parted /dev/sda -- mkpart primary 512MiB -8GiB
parted /dev/sda -- mkpart primary linux-swap -8GiB 100%
parted /dev/sda -- mkpart ESP fat32 1MiB 512MiB
parted /dev/sda -- set 3 boot on
mkfs.ext4 -L nixos /dev/sda1
mkswap -L swap /dev/sda2
mkfs.fat -F 32 -n boot /dev/sda3
mount /dev/disk/by-label/nixos /mnt
mkdir -p /mnt/boot
mount /dev/disk/by-label/boot /mnt/boot
swapon /dev/sda2
```
4. Option 2: Partition and format for Legacy Boot (MBR)
```
parted /dev/sda -- mklabel msdos
parted /dev/sda -- mkpart primary 1MiB -8GiB
parted /dev/sda -- mkpart primary linux-swap -8GiB 100%
mkfs.ext4 -L nixos /dev/sda1
mkswap -L swap /dev/sda2
mount /dev/disk/by-label/nixos /mnt
swapon /dev/sda2
```
4. Option 3: Set up encrypted partitions:
Follow the guide at https://gist.github.com/martijnvermaat/76f2e24d0239470dd71050358b4d5134.
5. Generate NixOS config
```
nixos-generate-config --root /mnt
nano /mnt/etc/nixos/configuration.nix
```
We now need to adjust the configuration to make sure that we can ssh into the system and that it boots correctly. We add some lines to set `services.openssh` such that the configuration looks as follows:
```
{ config, pkgs, ... }:
{
imports = [
...
];
# Enable the OpenSSH server.
services.openssh = {
enable = true;
permitRootLogin = "yes";
};
# The rest of the file are default options and hints.
}
```
Now we open `hardware-configuration.nix`
```
nano /mnt/etc/nixos/hardware-configuration.nix
```
which will look similar to
```
{ config, pkgs, ... }:
{
imports = [ ];
# Add line here as explained below
# The rest of the file are generated options.
}
```
Now add one of the following lines to the location mentioned in above example hardware config.
**Option 1**: UEFI
```
boot.loader.systemd-boot.enable = true;
```
**Option 2**: Legacy Boot (MBR)
```
boot.loader.grub.device = "/dev/sda";
```
Lastly, in rare circumstances the hardware configuration does not have a `fileSystems` option. In that case you need to add it with the folllowing line:
```
fileSystems."/".device = "/dev/disk/by-label/nixos";
```
6. Do the installation
```
nixos-install
```
Set root password
```
setting root password...
Enter new UNIX password:
Retype new UNIX password:
```
7. If everything went well
```
reboot
```
## 2. Nix installation
The following steps are meant to be run on the machine you deploy from, not the machine you deploy to.
You can also build Nix from source by following the instructions at https://nixos.org/nix/manual/#ch-installing-source.
1. Install Dependencies (Debian 10 Buster)
```
sudo apt-get install curl git gnupg2 dirmngr
```
2. Install latest Nix in "multi-user mode" with GPG Verification according to https://nixos.org/nix/download.html
```
curl -o install-nix-2.3.10 https://releases.nixos.org/nix/nix-2.3.10/install
curl -o install-nix-2.3.10.asc https://releases.nixos.org/nix/nix-2.3.10/install.asc
gpg2 --recv-keys B541D55301270E0BCF15CA5D8170B4726D7198DE
gpg2 --verify ./install-nix-2.3.10.asc
sh ./install-nix-2.3.10 --daemon
```
Then follow the instructions. Open a new terminal window when you're done.
If you get an error similar to
```
error: cloning builder process: Operation not permitted
error: unable to start build process
/tmp/nix-binary-tarball-unpack.hqawN4uSPr/unpack/nix-2.2.1-x86_64-linux/install: unable to install Nix into your default profile
```
you're likely not installing as multi-user because you forgot to pass the `--daemon` flag to the install script.
3. Optional: Disallow substitutes
You can put `substitute = false` to your `nix.conf` usually found in `/etc/nix/` to build the packages from source.
This eliminates an attack vector where nix's build server or binary cache is compromised.
## 3. Setup deployment directory
1. Clone this project
```
git clone https://github.com/fort-nix/nix-bitcoin
```
2. Create a new directory for your nix-bitcoin node config and copy initial files from nix-bitcoin
```
mkdir nix-bitcoin-node
cd nix-bitcoin-node
cp -r ../nix-bitcoin/examples/{configuration.nix,shell.nix,krops,.gitignore} .
```
3. Obtain the hash of the latest nix-bitcoin release
```
../nix-bitcoin/helper/fetch-release > nix-bitcoin-release.nix
```
#### Optional: Specify the system of your node
This enables evaluating your node config on a machine that has a different system platform
than your node.\
Examples: Deploying from macOS or deploying from a x86 desktop PC to a Raspberry Pi.
```bash
# Run this when your node has a 64-Bit x86 CPU (e.g., an Intel or AMD CPU)
echo "x86_64-linux" > krops/system
# Run this when your node has a 64-Bit ARM CPU (e.g., Raspberry Pi 4 B, Pine64)
echo "aarch64-linux" > krops/system
```
Other available systems:
- `i686-linux` (`x86`)
- `armv7l-linux` (`ARMv7`)\
This platform is untested and has no binary caches.
[See here](https://nixos.wiki/wiki/NixOS_on_ARM) for details.
## 4. Deploy with krops
1. Edit your ssh config
```
nano ~/.ssh/config
```
and add the node with an entry similar to the following (make sure to fix `Hostname` and `IdentityFile`):
```
Host bitcoin-node
# FIXME
Hostname NODE_IP_ADDRESS_OR_HOST_NAME_HERE
User root
PubkeyAuthentication yes
# FIXME
IdentityFile ~/.ssh/id_...
AddKeysToAgent yes
```
2. Make sure you are in the deployment directory and edit `krops/deploy.nix`
```
nano krops/deploy.nix
```
Locate the `FIXME` and set the target to the name of the ssh config entry created earlier, i.e. `bitcoin-node`.
Note that any file imported by your `configuration.nix` must be copied to the target machine by krops.
For example, if there is an import of `networking.nix` you must add it to `extraSources` in `krops/deploy.nix` like this:
```
extraSources = {
"hardware-configuration.nix".file = toString ../hardware-configuration.nix;
"networking.nix".file = toString ../networking.nix;
};
```
3. Optional: Disallow substitutes
If you prefer to build the system from source instead of copying binaries from the Nix cache, add the following line to `configuration.nix`:
```
nix.extraOptions = "substitute = false";
```
If the build process fails for some reason when deploying with `krops-deploy` (see later step), it may be difficult to find the cause due to the missing output.
To see the build output, SSH into the target machine and run
```
nixos-rebuild -I /var/src switch
```
4. Copy `hardware-configuration.nix` from your node to the deployment directory.
```
scp root@bitcoin-node:/etc/nixos/hardware-configuration.nix .
```
5. Adjust configuration by opening the `configuration.nix` file and enable/disable the modules you want by editing this file.
```
nano configuration.nix
```
Pay attention to lines that are preceded by `FIXME` comments. In particular:
1. Make sure to set your SSH pubkey. Otherwise, you loose remote access because the config does not enable `permitRootLogin` (unless you add that manually).
2. Uncomment the line `./hardware-configuration.nix` by removing `#`.
6. Enter the deployment environment
```
nix-shell
```
7. Deploy with krops in nix-shell
```
deploy
```
This will now create a nix-bitcoin node on the target machine.
8. You can now access `bitcoin-node` via ssh
```
ssh operator@bitcoin-node
```
Note that you're able to log in as the unprivileged `operator` user because nix-bitcoin automatically authorizes the ssh key added to `root`.
For security reasons, all normal system management tasks can and should be performed with the `operator` user. Logging in as `root` should be done as rarely as possible.
See also:
- [Migrating existing services to nix-bitcoin](configuration.md#migrate-existing-services-to-nix-bitcoin)
- [Managing your deployment](configuration.md#managing-your-deployment)
- [Using services](services.md)
+116
View File
@@ -0,0 +1,116 @@
# Maintaining the fork
Upstream (fort-nix/nix-bitcoin) was archived in August 2026, so this fork
is now the only source of fixes. This document records what was removed
when the fork was trimmed, and covers the maintenance work that remains.
## What was removed
The trim was done in November 2026, in commits `6e13a8b` through
`e1af5b7` on `main`, and released as `v0.1.0`. Upstream's tree is still
on `master`. The guiding rule was to keep only what a node running
bitcoind, lnd, electrs and mempool actually evaluates, and remove
everything else, since each remaining module has to be ported across
every NixOS release.
| Area | Removed | Why |
|---|---|---|
| Services | clightning (with plugins, REST, replication), joinmarket (with ob-watcher), btcpayserver/nbxplorer, rtl, liquid, lightning-loop, lightning-pool, charge-lnd, lndconnect, fulcrum, hardware-wallets | Not used. Each one broke independently whenever nixpkgs renamed an option or dropped a dependency |
| Packages | `python-packages/` (pyln, joinmarket, hwi and their pinned cython/ecdsa), `clightning-plugins/`, `clightning-rest/`, `clnrest/`, `trustedcoin/`, `rtl/`, `nbxplorer/`, `liquid-swap/`, `joinmarket/`, `bitcoind_29/`, `netns-exec/`, `krops/`, `nixops/`, `generate-secrets-deprecated.nix`, the local `lndinit` (0.1.3) | Only needed by removed services. lndinit now comes from nixpkgs |
| Support features | `netns-isolation.nix`, i2p support in `bitcoind.nix`, `backups.nix`, `versioning.nix`, `obsolete-options.nix`, `modules/deployment/` (krops, nixops) | netns-isolation reached into every service and caused the NixOS 26.11 i2pd breakage. Versioning and obsolete-options exist to migrate other people's configs across upstream releases |
| Presets | `secure-node`, `enable-tor`, `hardened`, `hardened-extended`, `wireguard`, `bitcoind-remote` | Mostly configured removed services. Consumers now set the Tor, onion-service and hardening options directly, which also lets them change values such as `bitcoind.dbCache` that the preset set without `mkDefault` |
| Flake inputs | `nixpkgs-unstable`, `nixpkgs-25_05`, `flake-utils`, `extra-container`, plus `pinned.nix`, `nixpkgs-pinned.nix` and the `useVersionLockedPkgs` option | Consumers following only `nixpkgs` still got packages from the fork's stale pins. Everything now comes from the consumer's nixpkgs |
| Scaffolding | `test/` (VM tests and CI), `examples/`, `dev/`, upstream's `docs/`, `.github/`, `SECURITY.md`, `shell.nix`, `helper/` except `update-fixed-output-derivation.sh` (release signing, `update-flake`) | Upstream's user-facing material and release process. Replaced by a short README |
All told, about 174 files changed and the code went from about 16,500
lines to about 2,300. Option names in the remaining modules are
unchanged from upstream.
## What's left, and what it costs to maintain
Ordered from most to least work:
1. **mempool package (`pkgs/mempool/`).** This is the only package built
here; nixpkgs doesn't package mempool. It has:
- five fixed-output hashes: source, frontend and backend node modules,
the frontend-assets fetch, and the rust-gbt cargo vendor
- a local patch, `0001-allow-disabling-mining-pool-fetching.patch`
- a pinned `nodejs_26` / `nodejs-slim_26`
- an en-US-only frontend build
- `NG_FORCE_TTY=false`, without which the Angular CLI's spinner
redraws forever under Nix's pty and the frontend build never
finishes
Expect every version bump to need the hashes redone (`generate.sh`
does this). When Node 26 reaches end of life, nixpkgs will drop it
and force a Node bump here. If the mempool UI is ever no longer
wanted, removing it is the biggest maintenance cut available.
2. **`mempool.nix` module.** It configures mariadb, nginx (including
`mempool-nginx-conf` from the package) and the backend's JSON config,
so it follows changes to NixOS's mysql and nginx modules and to
mempool's config schema.
3. **`bitcoind.nix`.** It tracks Bitcoin Core config changes across
major versions; nixpkgs moves bitcoind on its own schedule. It
disables NixOS's own `services/networking/bitcoind.nix` through
`disabledModules` in `modules.nix`, so watch for that module being
renamed or split.
4. **`lnd.nix`.** It tracks lnd config changes and uses `pkgs.lndinit`.
Check that the `gen-seed` and `init-wallet` flags still match after
lndinit bumps.
5. **Tor plumbing** (`onion-services.nix`, `onion-addresses.nix`,
`nbLib.tor`). It's built on `services.tor.relay.onionServices` and
`tor.client.socksListenAddress`, which NixOS has kept stable for
years, so expect low churn.
6. **Secrets (`secrets/`).** `setup-secrets` generates RPC passwords,
the lnd cert and similar on the host. It's mostly shell and openssl,
so low churn.
7. **`electrs.nix`, `nodeinfo.nix`, `operator.nix`, `security.nix`,
`nix-bitcoin.nix`.** These are small. The electrs package comes from
nixpkgs.
8. **systemd hardening in `pkgs/lib.nix`** (`defaultHardening`,
`allowedIPAddresses`, `allowNetlink`). Occasionally a systemd or
NixOS change makes a service fail at runtime, not at evaluation.
That only shows up after a deploy.
## Updating mempool
Edit `version` in `pkgs/mempool/generate.sh` and run it. The script
clones the release tag and checks its signature against two pinned
fingerprints:
- **wiz**, `913C5FF1F579B66CA10378DBA394E332255A6173`. He signed every
release through v3.3.0-alpha2. The key is on keyservers and Keybase.
- **mononaut**, `523B596A78BB8495AA2EC45ABFD16BE592A9CD8D`. Mononaut has
signed releases since v3.3.0. The key is fetched from
`github.com/mononaut.gpg`. It was created on 2026-04-14, nobody has
cross-signed it, and it isn't on keyservers or Keybase, so trusting it
means trusting mononaut's GitHub account. wiz published the v3.3.1
GitHub release, which mononaut's key signed.
If a release is signed by any other key, find out why before adding its
fingerprint. After the script refreshes the hashes, build all four
`packages.*.mempool-*` outputs.
## Per-release checklist
On each NixOS release, or each nixpkgs bump in a consuming config:
1. Run `nix flake check` here.
2. Build the consuming host's
`nixosConfigurations.<host>.config.system.build.toplevel`.
Evaluation errors will point into this fork's modules.
3. If mempool or Node changed, build `services.mempool.package` and
`services.mempool.frontend.package` first, and update the hashes.
4. Commit, then tag a new release (see `CLAUDE.md` for the versioning
scheme) and point the consumer at the new tag.
5. Switch the host and check that bitcoind, lnd, electrs, mempool and
nginx are running. Hardening regressions don't show at build time. If
a service fails, run `nixos-rebuild switch --rollback`.
## Testing
There is no test suite. Problems are handled as they show up on a
deployed node, with rollback as the fallback. A regtest VM test was
written during the trim and then dropped as not worth maintaining. If
runtime breakage becomes frequent, upstream's `test/tests.py` on
`master` has per-service checks for all four services to start from.
-130
View File
@@ -1,130 +0,0 @@
# Tutorial: Moving from a NixOps to a Krops deployment
1. Add a new ssh key to your nix-bitcoin node
Krops doesn't automatically generate ssh keys like NixOps, instead you add your own.
If you don't have a ssh key yet
```
ssh-keygen -t ed25519 -f ~/.ssh/bitcoin-node
```
Edit `configuration.nix`
```
users.users.root = {
openssh.authorizedKeys.keys = [
"<contents of ~/.ssh/bitcoin-node.pub or existing .pub key file>"
];
};
```
Deploy new key
```
nixops deploy -d bitcoin-node
```
2. Update your nix-bitcoin, depending on your setup either with `fetch-release` or `git`. Make sure you are at least on `v0.0.41`.
3. Pull the latest nix-bitcoin source
```
cd ~/nix-bitcoin
git pull
```
4. Copy new and updated files into your deployment folder
```
cd <deployment directory, for example `~/nix-bitcoin-node`>
cp -r ~/nix-bitcoin/examples/{krops,shell.nix} .
```
5. Edit your ssh config
```
nano ~/.ssh/config
```
and add the node with an entry similar to the following (make sure to fix `Hostname` and `IdentityFile`):
```
Host bitcoin-node
# FIXME
Hostname NODE_IP_ADDRESS_OR_HOST_NAME_HERE
User root
PubkeyAuthentication yes
# FIXME
IdentityFile <ssh key from step 1 or path to existing key>
AddKeysToAgent yes
```
6. Make sure you are in the deployment directory and edit `krops/deploy.nix`
```
nano krops/deploy.nix
```
Locate the `FIXME` and set the target to the name of the ssh config entry created earlier, i.e. `bitcoin-node`.
Note that any file imported by your `configuration.nix` must be copied to the target machine by krops.
For example, if there is an import of `networking.nix` you must add it to `extraSources` in `krops/deploy.nix` like this:
```
extraSources = {
"hardware-configuration.nix".file = toString ../hardware-configuration.nix;
"networking.nix".file = toString ../networking.nix;
};
```
7. If `lnd` or `joinmarket` is enabled on your node, run the commmand
```
nix-shell --run 'nix-instantiate --eval -E "
(import <nixpkgs/nixos> {
configuration = { lib, ... }: {
imports = [ ./configuration.nix ];
nix-bitcoin.configVersion = lib.mkDefault \"0.0.31\";
nix-bitcoin.secretsSetupMethod = lib.mkForce \"manual\";
};
}).vm.outPath
"'
```
and follow the migration instructions from the error message.
8. Optional: Disallow substitutes
You may have been building nix-bitcoin "without substitutes" to avoid pulling in binaries from the Nix cache. If you want to continue doing so, you have to add the following line to the `configuration.nix`:
```
nix.extraOptions = "substitute = false";
```
If the build process fails for some reason when deploying with `krops-deploy` (see later step), it may be difficult to find the cause due to the missing output.
In that case, it is possible to SSH into the target machine and run
```
nixos-rebuild -I /var/src switch
```
9. Deploy with krops
```
nix-shell --run krops-deploy
```
Remove the old secrets directory. For krops deployments, secrets are always
located at `/var/src/secrets`.
```
ssh bitcoin-node 'rm -rf /secrets'
```
9. You can now access `bitcoin-node` via ssh
```
ssh operator@bitcoin-node
```
10. You can remove the remaining traces of nixops as follows:
```
nix-shell
nix run -f '<nix-bitcoin>' nixops19_09 -c nixops delete -d bitcoin-node --force
git rm -r nixops
```
-598
View File
@@ -1,598 +0,0 @@
# Nodeinfo
Run `nodeinfo` to see onion addresses and local addresses for enabled services.
# Managing services
NixOS uses the [systemd](https://wiki.archlinux.org/title/systemd) service manager.
Usage:
```shell
# Show service status
systemctl status bitcoind
# Show the last 100 log messages
journalctl -u bitcoind -n 100
# Show all log messages since the last system boot
journalctl -b -u bitcoind
# These commands require root permissions
systemctl stop bitcoind
systemctl start bitcoind
systemctl restart bitcoind
# Show the service definition
systemctl cat bitcoind
# Show all service parameters
systemctl show bitcoind
```
# clightning database replication
The clightning database can be replicated to a local path
or to a remote SSH target.\
When remote replication is enabled, nix-bitcoin mounts a SSHFS to a local path.\
Optionally, backups can be encrypted via `gocryptfs`.
Note: You should also backup the static file `hsm_secret` (located at
`/var/lib/clightning/bitcoin/hsm_secret` by default), either manually
or via the `services.backups` module.
## Remote target via SSHFS
1. Add this to your `configuration.nix`:
```nix
services.clightning.replication = {
enable = true;
sshfs.destination = "user@hostname:directory";
# This is optional
encrypt = true;
};
programs.ssh.knownHosts."hostname".publicKey = "<ssh public key from running `ssh-keyscan` on the host>";
```
Leave out the `encrypt` line if you want to store data on your destination
in plaintext.\
Adjust `user`, `hostname` and `directory` as necessary.
2. Deploy
3. To allow SSH access from the nix-bitcoin node to the target node, either
use the remote node config below, or copy the contents of `$secretsDir/clightning-replication-ssh.pub`
to the `authorized_keys` file of `user` (or use `ssh-copy-id`).
4. You can restrict the nix-bitcoin node's capabilities on the SSHFS target
using OpenSSH's builtin features, as detailed
[here](https://serverfault.com/questions/354615/allow-sftp-but-disallow-ssh).
To implement this on NixOS, add the following to the NixOS configuration of
the SSHFS target node:
```nix
systemd.tmpfiles.rules = [
# Because this directory is chrooted by sshd, it must only be writable by user/group root
"d /var/backup/nb-replication 0755 root root - -"
"d /var/backup/nb-replication/writable 0700 nb-replication - - -"
];
services.openssh = {
extraConfig = ''
Match user nb-replication
ChrootDirectory /var/backup/nb-replication
AllowTcpForwarding no
AllowAgentForwarding no
ForceCommand internal-sftp
PasswordAuthentication no
X11Forwarding no
'';
};
users.users.nb-replication = {
isSystemUser = true;
group = "nb-replication";
shell = "${pkgs.coreutils}/bin/false";
openssh.authorizedKeys.keys = [ "<contents of $secretsDir/clightning-replication-ssh.pub>" ];
};
users.groups.nb-replication = {};
```
With this setup, the corresponding `sshfs.destination` on the nix-bitcoin
node is `"nb-replication@hostname:writable"`.
## Local directory target
1. Add this to your `configuration.nix`
```nix
services.clightning.replication = {
enable = true;
local.directory = "/var/backup/clightning";
encrypt = true;
};
```
Leave out the `encrypt` line if you want to store data in
`local.directory` in plaintext.
2. Deploy
clightning will now replicate database files to `local.directory`. This
can be used to replicate to an external HDD by mounting it at path
`local.directory`.
## Custom remote destination
Follow the steps in section "Local directory target" above and mount a custom remote
destination (e.g., a NFS or SMB share) to `local.directory`.\
You might want to disable `local.setupDirectory` in order to create the mount directory
yourself with custom permissions.
# Connect to RTL
Normally you would connect to RTL via SSH tunneling with a command like this
```
ssh -L 3000:127.0.0.1:3000 root@bitcoin-node
```
Or like this, if you are using `netns-isolation`
```
ssh -L 3000:169.254.1.29:3000 root@bitcoin-node
```
Otherwise, you can access it via Tor Browser at `http://<onion-address>`.
You can find the `<onion-address>` with command `nodeinfo`.
The default password location is `$secretsDir/rtl-password`.
See: [Secrets dir](./configuration.md#secrets-dir)
# Use Zeus (mobile lightning wallet) via Tor
1. Install [Zeus](https://zeusln.app) (version ≥ 0.9.0)
2. Edit your `configuration.nix`
##### For lnd
Add the following config:
```nix
services.lnd.lndconnect = {
enable = true;
onion = true;
};
```
##### For clightning
Add the following config:
```nix
services.clightning.plugins.clnrest = {
enable = true;
lnconnect = {
enable = true;
onion = true;
};
};
```
3. Deploy your configuration
4. Run the following command on your node (as user `operator`) to create a QR code
with address and authentication information:
##### For lnd
```
lndconnect
```
##### For clightning
```
lnconnect-clnrest
```
5. Configure Zeus
- Add a new node and scan the QR code
- Click `Save node config`
- Start sending and stacking sats privately
### Additional lndconnect features
- Create a plain text URL:
```bash
lndconnect --url
```
- Set a custom host. By default, `lndconnect` detects the system's external IP and uses it as the host.
```bash
lndconnect --host myhost
```
# Use Zeus (mobile lightning wallet) via WireGuard
Connecting Zeus directly to your node is much faster than using Tor, but a bit more complex to setup.
There are two ways to establish a secure, direct connection:
- Connecting via TLS. This requires installing your lightning app's
TLS Certificate on your mobile device.
- Connecting via WireGuard. This approach is simpler and more versatile, and is
described in this guide.
1. Install [Zeus](https://zeusln.app) (version ≥ 0.9.0) and
[WireGuard](https://www.wireguard.com/install/) on your mobile device.
2. Add the following to your `configuration.nix`:
```nix
imports = [
# Use this line when using the default deployment method
<nix-bitcoin/modules/presets/wireguard.nix>
# Use this line when using Flakes
(nix-bitcoin + /modules/presets/wireguard.nix)
]
# For lnd
services.lnd.lndconnect.enable = true;
# For clightning
services.clightning = {
plugins.clnrest = {
enable = true;
lnconnect.enable = true;
};
};
```
3. Deploy your configuration.
4. If your node is behind an external firewall or NAT (e.g. a router), add the following port forwarding
rule to the external device:
- Port: 51820 (the default value of option `networking.wireguard.interfaces.wg-nb.listenPort`)
- Protocol: UDP
- Destination: IP of your node
5. Setup WireGuard on your mobile device.
Run the following command on your node (as user `operator`) to create a QR code
for WireGuard:
```bash
nix-bitcoin-wg-connect
# For debugging: Show the WireGuard config as text
nix-bitcoin-wg-connect --text
```
The above commands automatically detect your node's external IP.\
To set a custom IP or hostname, run the following:
```
nix-bitcoin-wg-connect 93.184.216.34
nix-bitcoin-wg-connect mynode.org
```
Configure WireGuard:
- Press the `+` button in the bottom right corner
- Scan the QR code
- Add the tunnel
6. Setup Zeus
Run the following command on your node (as user `operator`) to create a QR code for Zeus:
##### For lnd
```
lndconnect-wg
```
##### For clightning
```
lnconnect-clnrest-wg
```
Configure Zeus:
- Add a new node and scan the QR code
- Click `Save node config`
- On the certificate warning screen, click `I understand, save node config`.\
Certificates are not needed when connecting via WireGuard.
- Start sending and stacking sats privately
### Additional lndconnect features
Create a plain text URL:
```bash
lndconnect-wg --url
``````
# Connect to electrs
### Requirements Android
* Android phone
* [Orbot](https://guardianproject.info/apps/orbot/) installed from [F-Droid](https://guardianproject.info/fdroid) (recommended) or [Google Play](https://play.google.com/store/apps/details?id=org.torproject.android&hl=en)
* [Electrum mobile app](https://electrum.org/#home) 4.0.1 and newer installed from [direct download](https://electrum.org/#download) or [Google Play](https://play.google.com/store/apps/details?id=org.electrum.electrum)
### Requirements Desktop
* [Tor](https://www.torproject.org/) installed from [source](https://www.torproject.org/docs/tor-doc-unix.html.en) or [repository](https://www.torproject.org/docs/debian.html.en)
* [Electrum](https://electrum.org/#download) installed
1. Enable electrs in `configuration.nix`
Change
```
# services.electrs.enable = true;
```
to
```
services.electrs.enable = true;
```
2. Deploy new `configuration.nix`
3. Get electrs onion address with format `<onion-address>:<port>`
```
nodeinfo | jq -r .electrs.onion_address
```
4. Connect to electrs
Make sure Tor is running on Desktop or as Orbot on Android.
On Desktop
```
electrum --oneserver -1 -s "<electrs onion address>:t" -p socks5:127.0.0.1:9050
```
On Android
```
Three dots in the upper-right-hand corner
Network > Proxy mode: socks5, Host: 127.0.0.1, Port: 9050
Network > Auto-connect: OFF
Network > One-server mode: ON
Network > Server: <electrs onion address>:t
```
# Connect to nix-bitcoin node through the SSH onion service
1. Get the SSH onion address (excluding the port suffix)
```
ssh operator@bitcoin-node
nodeinfo | jq -r .sshd.onion_address | sed 's/:.*//'
```
2. Create a SSH key
```
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519
```
3. Place the ed25519 key's fingerprint in the `configuration.nix` `openssh.authorizedKeys.keys` field like so
```
# FIXME: Add your SSH pubkey
services.openssh.enable = true;
users.users.root = {
openssh.authorizedKeys.keys = [ "<contents of ~/.ssh/id_ed25519.pub>" ];
};
```
4. Connect to your nix-bitcoin node's SSH onion service, forwarding a local port to the nix-bitcoin node's SSH server
```
ssh -i ~/.ssh/id_ed25519 -L <random port of your choosing>:127.0.0.1:22 root@<SSH onion address>
```
5. Edit your deployment tool's configuration and change the node's address to `127.0.0.1` and the ssh port to `<random port of your choosing>`.
If you use krops as described in the [installation tutorial](./install.md), set `target = "127.0.0.1:<random port of your choosing>";` in `krops/deploy.nix`.
6. After deploying the new configuration, it will connect through the SSH tunnel you established in step iv. This also allows you to do more complex SSH setups that some deployment tools don't support. An example would be authenticating with [Trezor's SSH agent](https://github.com/romanz/trezor-agent), which provides extra security.
# Initialize a Trezor for Bitcoin Core's Hardware Wallet Interface
1. Enable Trezor in `configuration.nix`
Change
```
# services.hardware-wallets.trezor = true;
```
to
```
services.hardware-wallets.trezor = true;
```
2. Deploy new `configuration.nix`
3. Check that your nix-bitcoin node recognizes your Trezor
```
ssh operator@bitcoin-node
lsusb
```
Should show something relating to your Trezor
4. If your Trezor has outdated firmware or is not yet initialized: Start your Trezor in bootloader mode
Trezor v1
```
Plug in your Trezor with both buttons depressed
```
Trezor v2
```
Start swiping your finger across your Trezor's touchscreen and plug in the USB cable when your finger is halfway through
```
5. If your Trezor's firmware is outdated: Update your Trezor's firmware
```
trezorctl firmware-update
```
Follow the on-screen instructions
**Caution: This command _will_ wipe your Trezor. If you already store Bitcoin on it, only do this with the recovery seed nearby.**
6. If your Trezor is not yet initialized: Set up your Trezor
```
trezorctl reset-device -p
```
Follow the on-screen instructions
7. Find your Trezor
```
hwi enumerate
hwi -t trezor -d <path from previous command> promptpin
hwi -t trezor -d <path> sendpin <number positions for the PIN as displayed on your device's screen>
hwi enumerate
```
8. Follow Bitcoin Core's instructions on [Using Bitcoin Core with Hardware Wallets](https://github.com/bitcoin-core/HWI/blob/master/docs/bitcoin-core-usage.md) to use your Trezor with `bitcoin-cli` on your nix-bitcoin node
# JoinMarket
## Diff to regular JoinMarket usage
For clarity reasons, nix-bitcoin renames all scripts to `jm-*` without `.py`, for
example `wallet-tool.py` becomes `jm-wallet-tool`. The rest of this section
details nix-bitcoin specific workflows for JoinMarket.
## Wallets
By default, a wallet is automatically generated at service startup.
It's stored at `/var/lib/joinmarket/wallets/wallet.jmdat`, and its mnmenoic recovery
seed phrase is stored at `/var/lib/joinmarket/jm-wallet-seed`.
A missing wallet file is automatically recreated if the seed file is still present.
If you want to manually initialize your wallet instead, follow these steps:
1. Enable JoinMarket in your node configuration
```
services.joinmarket.enable = true;
```
2. Move the automatically generated `wallet.jmdat`
```console
mv /var/lib/joinmarket/wallet.jmdat /var/lib/joinmarket/bak.jmdat
```
3. Generate wallet on your node
```console
jm-wallet-tool generate
```
Follow the on-screen instructions and write down your seed.
In order to use nix-bitcoin's `joinmarket.yieldgenerator`, use the password
from `$secretsDir/jm-wallet-password` and use the suggested default wallet name
`wallet.jmdat`. If you want to use your own `jm-wallet-password`, simply
replace the password string in your local secrets directory.
See: [Secrets dir](./configuration.md#secrets-dir)
## Run the tumbler
The tumbler needs to be able to run in the background for a long time, use screen
to run it accross SSH sessions. You can also use tmux in the same fashion.
1. Add screen to your `environment.systemPackages`, for example
```
environment.systemPackages = with pkgs; [
vim
screen
];
```
2. Start the screen session
```console
screen -S "tumbler"
```
3. Start the tumbler
Example: Tumbling into your wallet after buying from an exchange to improve privacy:
```console
jm-tumbler wallet.jmdat <addr1> <addr2> <addr3>
```
After tumbling your bitcoin end up in these three addresses. You can now
spend them without the exchange collecting data on your purchases.
Get more information [here](https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/master/docs/tumblerguide.md)
4. Detach the screen session to leave the tumbler running in the background
```
Ctrl-a d or Ctrl-a Ctrl-d
```
5. Re-attach to the screen session
```console
screen -r tumbler
```
6. End screen session
Type exit when tumbler is done
```console
exit
```
## Run a "maker" or "yield generator"
The maker/yield generator in nix-bitcoin is implemented using a systemd service.
See [here](https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/master/docs/YIELDGENERATOR.md) for more yield generator information.
1. Enable yield generator bot in your node configuration
```
services.joinmarket.yieldgenerator = {
enable = true;
# Optional: Add custom parameters
cjfee_a = 300;
cjfee_r = 0.00003;
};
'';
```
2. Check service status
```console
systemctl status joinmarket-yieldgenerator
```
3. Profit
# clightning
## Plugins
There is a number of [plugins](https://github.com/lightningd/plugins) available for clightning.
See [`Readme: Features → clightning`](../README.md#features) or [search.nixos.org][1] for a complete list.
[1]: https://search.nixos.org/flakes?channel=unstable&from=0&size=30&sort=relevance&type=options&query=services.clightning.plugins
You can activate and configure these plugins like so:
```nix
services.clightning = {
enable = true;
plugins = {
clboss.enable = true;
clboss.min-onchain = 40000;
};
};
```
Please have a look at the module for a plugin (e.g. [clboss.nix](../modules/clightning-plugins/clboss.nix)) to learn its configuration options.
### Trustedcoin
When `services.clightning.tor.proxy` is enabled, [trustedcoin](https://github.com/nbd-wtf/trustedcoin)
also uses Tor for all external connections by default.
In this case, connections to block explorers can sometimes get blocked.
An example of clightning log error output when connections are getting blocked:
```
lightningd[5138]: plugin-trustedcoin estimatefees error: https://blockstream.info/api error: 403 Forbidden
lightningd[4933]: plugin-trustedcoin getblock error: got something that isn't a block hash: <html><head>...
```
To work around this and connect via clearnet instead, set this option:
```nix
services.clightning.plugins.trustedcoin.tor.proxy = false;
```
-1
View File
@@ -1 +0,0 @@
secrets/
-77
View File
@@ -1,77 +0,0 @@
## Examples
The easiest way to try out nix-bitcoin is to use one of the provided examples.
### Flakes-based quick start
If you use a Flakes-enabled version of Nix, run the following command to start a minimal
nix-bitcoin QEMU VM:
```bash
nix run github:fort-nix/nix-bitcoin/release
```
The VM (defined in [flake.nix](../flake.nix)) runs in the terminal and has `bitcoind`
and `clightning` installed.\
It leaves no traces (outside of `/nix/store`) on the host system.
### More examples
Clone this repo and enter the examples shell:
```bash
git clone https://github.com/fort-nix/nix-bitcoin
cd nix-bitcoin/examples/
nix-shell
```
The following example scripts set up a nix-bitcoin node according to [`./configuration.nix`](configuration.nix) and then
shut down immediately. They leave no traces (outside of `/nix/store`) on the host system.\
By default, [`./configuration.nix`](configuration.nix) enables `bitcoind` and `clightning`.
- [`./deploy-container.sh`](deploy-container.sh) creates a [NixOS container](https://github.com/erikarvstedt/extra-container).\
This is the fastest way to set up a node.\
Requires: [Nix](https://nixos.org/), a systemd-based Linux distro and root privileges
- [`./deploy-qemu-vm.sh`](deploy-qemu-vm.sh) creates a QEMU VM.\
Requires: [Nix](https://nixos.org/nix/), Linux
- [`./deploy-krops.sh`](deploy-krops.sh) creates a QEMU VM and deploys a
nix-bitcoin configuration to it using [krops](https://github.com/krebs/krops).\
Requires: [Nix](https://nixos.org/nix/), Linux
- [`./deploy-container-minimal.sh`](deploy-container-minimal.sh) creates a
container defined by [importable-configuration.nix](importable-configuration.nix).\
You can copy and import this file to use nix-bitcoin in an existing NixOS configuration.\
The configuration doesn't use the [secure-node.nix](../modules/presets/secure-node.nix) preset.\
Requires: [Nix](https://nixos.org/), a systemd-based Linux distro and root privileges
Run the examples with option `--interactive` or `-i` to start a shell for interacting with
the node:
```bash
./deploy-qemu-vm.sh -i
```
### Tests
The [nix-bitcoin test suite](../test/README.md) is also useful for exploring features.
### Real-world example
Check the [server repo](https://github.com/fort-nix/nixbitcoin.org) for https://nixbitcoin.org
to see the configuration of a Flakes-based nix-bitcoin node that's used in production.
The commands in `shell.nix` allow you to locally run the node in a VM or container.
### Flakes
Flakes make it easy to include `nix-bitcoin` in an existing NixOS config.
The [flakes example](./flakes/flake.nix) shows how to use `nix-bitcoin` as an input to a system flake.
### Persistent container with Flakes
The [persistent container](./container) example shows how to run a Flake-based node
in a container.\
Requires: A systemd-based Linux distro and root privileges.
### Extending nix-bitcoin with Flakes
The [mempool extension flake](https://github.com/fort-nix/nix-bitcoin-mempool) shows how to define new
pkgs and modules in a Flake.\
Since mempool is now a core nix-bitcoin module, this Flake just serves as an example.
-333
View File
@@ -1,333 +0,0 @@
# Edit this configuration file to define what should be installed on
# your system. Help is available in the configuration.nix(5) man page
# and in the NixOS manual (accessible by running ‘nixos-help’).
{ config, pkgs, lib, ... }: {
imports = [
<nix-bitcoin/modules/modules.nix>
# FIXME: The secure-node preset is an opinionated config to enhance security
# and privacy.
# Among other settings, it routes traffic of all nix-bitcoin services through Tor.
# Turn it off when not needed.
<nix-bitcoin/modules/presets/secure-node.nix>
# FIXME: The hardened kernel profile improves security but
# decreases performance by ~50%.
# Turn it off when not needed.
<nix-bitcoin/modules/presets/hardened.nix>
#
# You can enable the hardened-extended preset instead to further improve security
# at the cost of functionality and performance.
# See the comments at the top of `hardened-extended.nix` for further details.
# <nix-bitcoin/modules/presets/hardened-extended.nix>
# FIXME: Uncomment the next line to import your hardware configuration. If so,
# add the hardware configuration file to the same directory as this file.
#./hardware-configuration.nix
];
# FIXME: Enable modules by uncommenting their respective line. Disable
# modules by commenting out their respective line.
### BITCOIND
# Bitcoind is enabled by default via secure-node.nix.
#
# Set this option to enable pruning with a specified MiB value.
# clightning is compatible with pruning. See
# https://github.com/ElementsProject/lightning/#pruning for more information.
# LND and electrs are not compatible with pruning.
# services.bitcoind.prune = 100000;
#
# Set this to accounce the onion service address to peers.
# The onion service allows accepting incoming connections via Tor.
# nix-bitcoin.onionServices.bitcoind.public = true;
#
# You can add options that are not defined in modules/bitcoind.nix as follows
# services.bitcoind.extraConfig = ''
# maxorphantx=110
# '';
### CLIGHTNING
# Enable clightning, a Lightning Network implementation in C.
services.clightning.enable = true;
#
# Set this to create an onion service by which clightning can accept incoming connections
# via Tor.
# The onion service is automatically announced to peers.
# nix-bitcoin.onionServices.clightning.public = true;
#
# == Plugins
# See ../README.md (Features → clightning) for the list of available plugins.
# services.clightning.plugins.clboss.enable = true;
#
# == REST server
# Set this to create a clightning REST onion service.
# This also adds binary `lnconnect-clnrest` to the system environment.
# This binary creates QR codes or URLs for connecting applications to clightning
# via the REST onion service.
# You can also connect via WireGuard instead of Tor.
# See ../docs/services.md for details.
#
# services.clightning.plugins.clnrest = {
# enable = true;
# lnconnect = {
# enable = true;
# onion = true;
# };
# };
### LND
# Set this to enable lnd, a lightning implementation written in Go.
# services.lnd.enable = true;
#
# NOTE: In order to avoid collisions with clightning you must disable clightning or
# change the services.clightning.port or services.lnd.port to a port other than
# 9735.
#
# Set this to create an onion service by which lnd can accept incoming connections
# via Tor.
# The onion service is automatically announced to peers.
# nix-bitcoin.onionServices.lnd.public = true;
#
# Set this to create a lnd REST onion service.
# This also adds binary `lndconnect` to the system environment.
# This binary generates QR codes or URLs for connecting applications to lnd via the
# REST onion service.
# You can also connect via WireGuard instead of Tor.
# See ../docs/services.md for details.
#
# services.lnd.lndconnect = {
# enable = true;
# onion = true;
# };
#
## WARNING
# If you use lnd, you should manually backup your wallet mnemonic
# seed. This will allow you to recover on-chain funds. You can run the
# following commands after the lnd service starts:
# mkdir -p ./backups/lnd/
# scp bitcoin-node:/var/lib/lnd/lnd-seed-mnemonic ./backups/lnd/
#
# You should also backup your channel state after opening new channels.
# This will allow you to recover off-chain funds, by force-closing channels.
# scp bitcoin-node:/var/lib/lnd/chain/bitcoin/mainnet/channel.backup ./backups/lnd/
#
# Alternatively, you can have these files backed up by services.backups below.
### RIDE THE LIGHTNING
# Set this to enable RTL, a web interface for lnd and clightning.
# services.rtl.enable = true;
#
# Set this to add a clightning node interface.
# Automatically enables clightning.
# services.rtl.nodes.clightning.enable = true;
#
# Set this to add a lnd node interface.
# Automatically enables lnd.
# services.rtl.nodes.lnd.enable = true;
#
# You can enable both nodes simultaneously.
#
# Set this option to enable swaps with lightning-loop.
# Automatically enables lightning-loop.
# services.rtl.nodes.lnd.loop = true;
### MEMPOOL
# Set this to enable mempool, a fully featured Bitcoin visualizer, explorer,
# and API service.
#
# services.mempool.enable = true;
#
# Possible options for the Electrum backend server:
#
# - electrs (enabled by default):
# Small database size, slow when querying new addresses.
#
# - fulcrum:
# Large database size, quickly serves arbitrary address queries.
# Enable with:
# services.mempool.electrumServer = "fulcrum";
#
# Set this to create an onion service to make the mempool web interface
# available via Tor:
# nix-bitcoin.onionServices.mempool-frontend.enable = true;
### ELECTRS
# Set this to enable electrs, an Electrum server implemented in Rust.
# services.electrs.enable = true;
### FULCRUM
# Set this to enable fulcrum, an Electrum server implemented in C++.
#
# Compared to electrs, fulcrum has higher storage demands but
# can serve arbitrary address queries instantly.
#
# Before enabling fulcrum, and for more info on storage demands,
# see the description of option `enable` in ../modules/fulcrum.nix
#
# services.fulcrum.enable = true;
### BTCPayServer
# Set this to enable BTCPayServer, a self-hosted, open-source
# cryptocurrency payment processor.
# services.btcpayserver.enable = true;
#
# Privacy Warning: BTCPayServer currently looks up price rates without
# proxying them through Tor. This means an outside observer can correlate
# your BTCPayServer usage, like invoice creation times, with your IP address.
#
# Enable this option to connect BTCPayServer to clightning.
# services.btcpayserver.lightningBackend = "clightning";
#
# Enable this option to connect BTCPayServert to lnd.
# services.btcpayserver.lightningBackend = "lnd";
#
# The lightning backend service is automatically enabled.
# Afterwards you need to go into Store > General Settings > Lightning Nodes
# and select "the internal lightning node of this BTCPay Server".
#
# Set this to create an onion service to make the btcpayserver web interface
# accessible via Tor.
# Security WARNING: Create a btcpayserver administrator account before allowing
# public access to the web interface.
# nix-bitcoin.onionServices.btcpayserver.enable = true;
### LIQUIDD
# Enable this module to use Liquid, a sidechain for an inter-exchange
# settlement network linking together cryptocurrency exchanges and
# institutions around the world.
# services.liquidd.enable = true;
#
# Liquid can be controlled with command 'elements-cli'.
### Hardware wallets
# Enable the following to allow using hardware wallets.
# See https://github.com/bitcoin-core/HWI for more information.
#
# Ledger must be initialized through the official ledger live app and the Bitcoin app must
# be installed and running on the device.
# services.hardware-wallets.ledger = true;
#
# Trezor can be initialized with the trezorctl command in nix-bitcoin. More information in
# `../docs/services.md`.
# services.hardware-wallets.trezor = true;
### lightning-loop
# Set this to enable lightninglab's non-custodial off/on chain bridge.
# services.lightning-loop.enable = true;
#
# loopd (lightning-loop daemon) will be started automatically. Users can
# interact with off/on chain bridge using `loop in` and `loop out`.
# Automatically enables lnd.
### lightning-pool
# Set this to enable Lightning Lab's non-custodial batched uniform
# clearing-price auction for Lightning Channel Leases.
# services.lightning-pool.enable = true;
#
# Use the `pool` command to interact with the lightning-pool service.
# Automatically enables lnd.
#
# lightning-pool requires that lnd has a publicly reachable address.
# Set this to create a public onion service for lnd.
# nix-bitcoin.onionServices.lnd.public = true;
### charge-lnd
# Set this to enable charge-lnd, a simple policy based fee manager for
# LND. With this tool you can set fees to autobalance, recover channel open
# costs, use on-chain fees as reference, or just use static fees. You decide.
# services.charge-lnd.enable = true;
#
# Define policies as outlined in the project documentation.
# services.charge-lnd.policies = ''
# '';
### JOINMARKET
# Set this to enable the JoinMarket service, including its command-line scripts.
# These scripts have prefix 'jm-', like 'jm-tumbler'.
# Note: JoinMarket has full access to bitcoind, including its wallet functionality.
# services.joinmarket.enable = true;
#
# Set this to enable the JoinMarket Yield Generator Bot. You will be able to
# earn sats by providing CoinJoin liquidity. This makes it impossible to use other
# scripts that access your wallet.
# services.joinmarket.yieldgenerator.enable = true;
#
# Set this to enable the JoinMarket order book watcher.
# services.joinmarket-ob-watcher.enable = true;
### Nodeinfo
# Set this to add command `nodeinfo` to the system environment.
# It shows info about running services like onion addresses and local addresses.
# It is enabled by default when importing `secure-node.nix`.
# nix-bitcoin.nodeinfo.enable = true;
### Backups
# Set this to enable nix-bitcoin's own backup service. By default, it
# uses duplicity to incrementally back up all important files in /var/lib to
# /var/lib/localBackups once a day.
# services.backups.enable = true;
#
# You can pull the localBackups folder with
# `scp -r bitcoin-node:/var/lib/localBackups /my-backup-path/`
# Alternatively, you can also set a remote target url, for example
# services.backups.destination = "sftp://user@host[:port]/[relative|/absolute]_path";
# Supply the sftp password by appending the FTP_PASSWORD environment variable
# to secrets/backup-encryption-env like so
# `echo "FTP_PASSWORD=<password>" >> secrets/backup-encryption-env`
# You many also need to set a ssh host and publickey with
# programs.ssh.knownHosts."host" = {
# hostNames = [ "host" ];
# publicKey = "<ssh public from `ssh-keyscan`>";
# };
# If you also want to backup bulk data like the Bitcoin & Liquid blockchains
# and electrs data directory, enable
# services.backups.with-bulk-data = true;
### netns-isolation (EXPERIMENTAL)
# Enable this module to use Network Namespace Isolation. This feature places
# every service in its own network namespace and only allows truly necessary
# connections between network namespaces, making sure services are isolated on
# a network-level as much as possible.
# nix-bitcoin.netns-isolation.enable = true;
# FIXME: Define your hostname.
networking.hostName = "host";
time.timeZone = "UTC";
services.openssh = {
enable = true;
settings.PasswordAuthentication = false;
};
users.users.root = {
openssh.authorizedKeys.keys = [
# FIXME: Replace this with your SSH pubkey
"ssh-ed25519 AAAAC3..."
];
};
# FIXME: Uncomment this to allow the operator user to run
# commands as root with `sudo` or `doas`
# users.users.operator.extraGroups = [ "wheel" ];
# FIXME: add packages you need in your system
environment.systemPackages = with pkgs; [
vim
];
# FIXME: Add custom options (like boot options, output of
# nixos-generate-config, etc.):
# This value determines the NixOS release from which the default
# settings for stateful data, like file locations and database versions
# on your system were taken. It's perfectly fine and recommended to leave
# this value at the release version of the first install of this system.
# Before changing this value read the documentation for this option
# (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
system.stateVersion = "26.05"; # Did you read the comment?
# The nix-bitcoin release version that your config is compatible with.
# When upgrading to a backwards-incompatible release, nix-bitcoin will display an
# an error and provide instructions for migrating your config to the new release.
nix-bitcoin.configVersion = "0.0.85";
}
-73
View File
@@ -1,73 +0,0 @@
# See how this flake is used in ./usage.sh
# See also:
# https://github.com/erikarvstedt/extra-container
# https://github.com/erikarvstedt/extra-container/blob/master/examples/flake
# Container-related NixOS options
# https://search.nixos.org/options?channel=unstable&query=containers.%3Cname%3E
{
description = "A basic nix-bitcoin container node";
inputs = {
nix-bitcoin.url = "github:fort-nix/nix-bitcoin/release";
# You can also use a version branch to track a specific NixOS release
# nix-bitcoin.url = "github:fort-nix/nix-bitcoin/nixos-26.05";
nixpkgs.follows = "nix-bitcoin/nixpkgs";
nixpkgs-unstable.follows = "nix-bitcoin/nixpkgs-unstable";
extra-container.follows = "nix-bitcoin/extra-container";
};
outputs = { nixpkgs, nix-bitcoin, extra-container, ... }:
extra-container.lib.eachSupportedSystem (system: {
packages.default = extra-container.lib.buildContainers {
inherit system;
# The container uses the nixpkgs from `nix-bitcoin.inputs.nixpkgs` by default
# Only set this if the `system.stateVersion` of your container
# host is < 22.05
# legacyInstallDirs = true;
config = {
# See the file for why this is needed and when it can be removed
imports = [ (nix-bitcoin.outPath + "/test/lib/extra-container-workaround.nix") ];
containers.mynode = {
# Always start container along with the container host
autoStart = true;
# This assigns the following addresses:
# Host IP: 10.250.0.1
# Container IP: 10.250.0.2
extra.addressPrefix = "10.250.0";
# Enable internet access for the container
extra.enableWAN = true;
# Map `/my/host/dir` to `/my/mount` in the container
# bindMounts."/my/mount" = { hostPath = "/my/host/dir"; isReadOnly = false; };
# Setup port forwarding
# forwardPorts = [ { containerPort = 80; hostPort = 8080; protocol = "tcp";} ];
config = { config, pkgs, ... }: {
imports = [
nix-bitcoin.nixosModules.default
];
# Automatically generate all secrets required by services.
# The secrets are stored in /etc/nix-bitcoin-secrets in the container
nix-bitcoin.generateSecrets = true;
# Enable some services.
# See ../configuration.nix for all available features.
services.bitcoind.enable = true;
services.electrs.enable = true;
};
};
};
};
});
}
-47
View File
@@ -1,47 +0,0 @@
# Requirements:
# - A systemd-based Linux distro
# - extra-container (https://github.com/erikarvstedt/extra-container/#install)
# - Nix
# - Root privileges
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Create container
# Create and start container defined by ./flake.nix
nix run . -- create --start
# You can use the same command to update the (running) container,
# after changing the container configuration.
# In the default configuration, the container is automatically started on
# system boot (option `autoStart`).
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Use container
# Run command in container
extra-container run mynode -- hostname
extra-container run mynode -- systemctl status bitcoind
extra-container run mynode -- bitcoin-cli -getinfo
extra-container run mynode -- bash -c 'bitcoin-cli -getinfo && systemctl status electrs'
# Start shell in container
extra-container root-login mynode
# Show the container filesystem
sudo ls -al /var/lib/nixos-containers/mynode
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Stop container
extra-container stop mynode
# Resume the container
extra-container start mynode
# You can also use the `create --start` command above
# Destroy container
extra-container destroy mynode
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Inspect container config
nix eval .#default.outPath
nix eval . --apply 'sys: sys.containers.mynode.config.networking.hostName'
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
tmpDir=$(mktemp -d /tmp/nix-bitcoin-minimal-container.XXX)
trap 'rm -rf $tmpDir' EXIT
cd "${BASH_SOURCE[0]%/*}"
# Modify importable-configuration.nix to use the local <nix-bitcoin>
# source instead of fetchTarball
<importable-configuration.nix sed '
s|nix-bitcoin = .*|nix-bitcoin = toString <nix-bitcoin>;|;
s|system.extraDependencies = .*||
' > "$tmpDir/importable-configuration.nix"
cat > "$tmpDir/configuration.nix" <<EOF
{
imports = [ $tmpDir/importable-configuration.nix ];
users.users.main = {
isNormalUser = true;
password = "a";
};
# When WAN is disabled, DNS bootstrapping slows down service startup by ~15 s
services.clightning.extraConfig = ''
disable-dns
'';
}
EOF
./deploy-container.sh "$tmpDir/configuration.nix" "$@"
-95
View File
@@ -1,95 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# This script demonstrates how to setup a nix-bitcoin node in a NixOS container.
# Running this script leaves no traces on your host system.
# This demo is a template for your own experiments.
# Run with option `--interactive` or `-i` to start a shell for interacting with
# the node.
if [[ $EUID != 0 ]]; then
# NixOS containers require root permissions
exec sudo "${BASH_SOURCE[0]}" "$@"
fi
if [[ $(sysctl -n net.ipv4.ip_forward) != 1 ]]; then
echo "Error: IP forwarding (net.ipv4.ip_forward) is not enabled."
echo "Needed for container WAN access."
exit 1
fi
if [[ ! -v DEPLOY_CONTAINER_NIX_SHELL ]]; then
echo "Running script in nix shell env..."
cd "${BASH_SOURCE[0]%/*}"
DEPLOY_CONTAINER_NIX_SHELL=1 exec nix-shell --run "./${BASH_SOURCE[0]##*/} $*"
fi
interactive=
configuration=
for arg in "$@"; do
case $arg in
-i|--interactive)
interactive=1
;;
*)
configuration=$arg
;;
esac
done
# These commands can also be executed interactively in a shell session
demoCmds='
echo
echo "Bitcoind service:"
c systemctl status bitcoind
echo
echo "Bitcoind network:"
c bitcoin-cli getnetworkinfo
echo
echo "lightning-cli state:"
c lightning-cli getinfo
echo
echo "Bitcoind data dir:"
sudo ls -al /var/lib/*containers/demo-node/var/lib/bitcoind
'
nodeInfoCmd='
echo
echo "Node info:"
c nodeinfo
'
if [[ ! $configuration ]]; then
configuration=configuration.nix
demoCmds="${demoCmds}${nodeInfoCmd}"
fi
if [[ $interactive ]]; then
runCmd=()
else
runCmd=(--run bash -c "$demoCmds")
fi
# Build container.
# Learn more: https://github.com/erikarvstedt/extra-container
#
read -rd '' src <<EOF || true
{ pkgs, lib, ... }: {
imports = [ $(realpath "${BASH_SOURCE[0]%/*}"/../test/lib/extra-container-workaround.nix) ];
containers.demo-node = {
extra.addressPrefix = "10.250.0";
extra.enableWAN = true;
config = { pkgs, config, lib, ... }: {
imports = [
$(realpath "$configuration")
];
nix-bitcoin.generateSecrets = true;
};
};
}
EOF
. "${BASH_SOURCE[0]%/*}"/../test/lib/extra-container-check-version.sh
extra-container shell -E "$src" "${runCmd[@]}"
# The container is automatically deleted at exit
-130
View File
@@ -1,130 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# This script demonstrates how to setup a nix-bitcoin node with krops.
# The node is deployed to a minimal NixOS QEMU VM.
# Running this script leaves no traces on your host system.
# This demo is a template for your own experiments.
# Run with option `--interactive` or `-i` to start a shell for interacting with
# the node.
# MAKE SURE TO REPLACE the SSH identity file if you use this script for
# anything serious.
if [[ ! -v NIX_BITCOIN_EXAMPLES_DIR ]]; then
echo "Running script in nix shell env..."
cd "${BASH_SOURCE[0]%/*}"
exec nix-shell --run "./${BASH_SOURCE[0]##*/} $*"
else
cd "$NIX_BITCOIN_EXAMPLES_DIR"
fi
source qemu-vm/run-vm.sh
echo "Building the target VM"
# Build the initial VM to which the nix-bitcoin node is deployed via krops
nix-build --out-link "$tmpDir/vm" - <<'EOF'
(import <nixpkgs/nixos> {
configuration = { config, lib, ... }: {
imports = [ <qemu-vm/vm-config.nix> ];
services.openssh.enable = true;
# Silence the following warning that appears when deploying via krops:
# warning: Nix search path entry '/nix/var/nix/profiles/per-user/root/channels' does not exist, ignoring
nix.nixPath = lib.mkForce [];
system.stateVersion = lib.mkDefault config.system.nixos.release;
};
}).config.system.build.vm
EOF
vmNumCPUs=4
vmMemoryMiB=2048
sshPort=60734
# Start the VM in the background
runVM "$tmpDir/vm" "$vmNumCPUs" "$vmMemoryMiB" "$sshPort"
# Build the krops deploy script
export sshPort
nix-build --out-link "$tmpDir/krops-deploy" - <<'EOF'
let
krops = (import <nix-bitcoin> {}).krops;
extraSources = {
# Skip uploading nixpkgs to the target node.
# This works because /nix/store is shared with the target VM.
nixpkgs.symlink = toString <nixpkgs>;
nixos-config.file = toString <krops-vm-configuration.nix>;
qemu-vm.file = toString <qemu-vm>;
};
in
krops.pkgs.krops.writeCommand "krops-deploy" {
source = import <krops/sources.nix> { inherit extraSources krops; };
force = true;
target = {
user = "root";
host = "127.0.0.1";
port = builtins.getEnv "sshPort";
extraOptions = [
"-i" (toString <qemu-vm/id-vm>) "-oConnectTimeout=1"
"-oStrictHostKeyChecking=no" "-oUserKnownHostsFile=/dev/null" "-oLogLevel=ERROR"
"-oControlMaster=auto" "-oControlPath=${builtins.getEnv "tmpDir"}/ssh-connection" "-oControlPersist=60"
];
};
# "test" instead of "switch" to avoid installing a bootloader which
# is not possible in this VM
command = targetPath: ''
nixos-rebuild test -I /var/src
'';
}
EOF
echo "Building the nix-bitcoin node"
# Pre-build the nix-bitcoin node outside of the VM to save some time
nix-build --out-link "$tmpDir/store-paths" -E '
let
system = (import <nixpkgs/nixos> { configuration = <krops-vm-configuration.nix>; }).system;
pkgsUnstable = (import <nix-bitcoin/pkgs/nixpkgs-pinned.nix>).nixpkgs-unstable;
pkgs = import <nixpkgs> {};
in
pkgs.closureInfo { rootPaths = [ system pkgsUnstable ]; }
' > /dev/null
vmWaitForSSH
# Add the store paths that include the nix-bitcoin node
# to the nix store db in the VM
c "nix-store --load-db < $(realpath "$tmpDir/store-paths")/registration"
echo
echo "Generate secrets"
nix-shell --run generate-secrets
echo
echo "Deploy with krops"
"$tmpDir/krops-deploy"
echo
echo "Bitcoind service:"
c systemctl status bitcoind
echo
echo "Bitcoind network:"
c bitcoin-cli getnetworkinfo
echo
echo "lightning-cli state:"
c lightning-cli getinfo
echo
echo "Node info:"
c nodeinfo
case ${1:-} in
-i|--interactive)
. ./start-bash-session.sh
;;
esac
# Cleanup happens at exit (defined in qemu-vm/run-vm.sh)
-69
View File
@@ -1,69 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# This script demonstrates how to run a nix-bitcoin node in QEMU.
# Running this script leaves no traces on your host system.
# This demo is a template for your own experiments.
# Run with option `--interactive` or `-i` to start a shell for interacting with
# the node.
# MAKE SURE TO REPLACE the SSH identity file if you use this script for
# anything serious.
if [[ ! -v NIX_BITCOIN_EXAMPLES_DIR ]]; then
echo "Running script in nix shell env..."
cd "${BASH_SOURCE[0]%/*}"
exec nix-shell --run "./${BASH_SOURCE[0]##*/} $*"
else
cd "$NIX_BITCOIN_EXAMPLES_DIR"
fi
source qemu-vm/run-vm.sh
echo "Building VM"
nix-build --out-link "$tmpDir/vm" - <<'EOF'
(import <nixpkgs/nixos> {
configuration = {
imports = [
<configuration.nix>
<qemu-vm/vm-config.nix>
];
nix-bitcoin.generateSecrets = true;
};
}).config.system.build.vm
EOF
vmNumCPUs=4
vmMemoryMiB=2048
sshPort=60734
runVM "$tmpDir/vm" "$vmNumCPUs" "$vmMemoryMiB" "$sshPort"
vmWaitForSSH
printf "Waiting until services are ready"
c "
$(cat qemu-vm/wait-until.sh)
waitUntil 'systemctl is-active clightning &> /dev/null' 100
"
echo
echo
echo "Bitcoind service:"
c systemctl status bitcoind
echo
echo "Bitcoind network:"
c bitcoin-cli getnetworkinfo
echo
echo "lightning-cli state:"
c lightning-cli getinfo
echo
echo "Node info:"
c nodeinfo
case ${1:-} in
-i|--interactive)
. ./start-bash-session.sh
;;
esac
# Cleanup happens at exit (defined in qemu-vm/run-vm.sh)
-70
View File
@@ -1,70 +0,0 @@
# This is a system configuration template that uses nix-bitcoin.
#
# You can adapt this to an existing system flake by copying the parts
# relevant to nix-bitcoin.
#
# Make sure to check and edit all lines marked by 'FIXME:'
{
description = "A basic nix-bitcoin node";
inputs.nix-bitcoin.url = "github:fort-nix/nix-bitcoin/release";
# You can also use a version branch to track a specific NixOS release
# inputs.nix-bitcoin.url = "github:fort-nix/nix-bitcoin/nixos-26.05";
inputs.nixpkgs.follows = "nix-bitcoin/nixpkgs";
inputs.nixpkgs-unstable.follows = "nix-bitcoin/nixpkgs-unstable";
outputs = { self, nixpkgs, nix-bitcoin, ... }: {
nixosConfigurations.mynode = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
nix-bitcoin.nixosModules.default
# Optional:
# Import the secure-node preset, an opinionated config to enhance security
# and privacy.
#
# (nix-bitcoin + "/modules/presets/secure-node.nix")
{
# Automatically generate all secrets required by services.
# The secrets are stored in /etc/nix-bitcoin-secrets
nix-bitcoin.generateSecrets = true;
# Enable some services.
# See ../configuration.nix for all available features.
services.bitcoind.enable = true;
services.clightning.enable = true;
# When using nix-bitcoin as part of a larger NixOS configuration, set the following to enable
# interactive access to nix-bitcoin features (like bitcoin-cli) for your system's main user
nix-bitcoin.operator = {
enable = true;
# FIXME: Set this to your system's main user
name = "main";
};
# The system's main unprivileged user.
# In an existing NixOS configuration, this setting is usually already defined.
users.users.main = {
isNormalUser = true;
# FIXME: This is unsafe. Use `hashedpassword` or `passwordFile` instead in a real
# deployment: https://search.nixos.org/options?show=users.users.%3Cname%3E.hashedPassword
password = "a";
};
# If you use a custom nixpkgs version for evaluating your system
# (instead of `nix-bitcoin.inputs.nixpkgs` like in this example),
# consider setting `useVersionLockedPkgs = true` to use the exact pkgs
# versions for nix-bitcoin services that are tested by nix-bitcoin.
# The downsides are increased evaluation times and increased system
# closure size.
#
# nix-bitcoin.useVersionLockedPkgs = true;
}
];
};
};
}
-38
View File
@@ -1,38 +0,0 @@
# You can directly copy and import this file to use nix-bitcoin
# in an existing NixOS configuration.
# Make sure to check and edit all lines marked by 'FIXME:'
# See ./flakes/flake.nix on how to include nix-bitcoin in a flake-based
# system configuration.
let
# FIXME:
# Overwrite `builtins.fetchTarball {}` with the output of
# command ../helper/fetch-release
nix-bitcoin = builtins.fetchTarball {};
in
{ config, pkgs, lib, ... }: {
imports = [
"${nix-bitcoin}/modules/modules.nix"
];
# Automatically generate all secrets required by services.
# The secrets are stored in /etc/nix-bitcoin-secrets
nix-bitcoin.generateSecrets = true;
# Enable some services.
# See ./configuration.nix for all available features.
services.bitcoind.enable = true;
services.clightning.enable = true;
# Enable interactive access to nix-bitcoin features (like bitcoin-cli) for
# your system's main user
nix-bitcoin.operator = {
enable = true;
# FIXME: Set this to your system's main user
name = "main";
};
# Prevent garbage collection of the nix-bitcoin source
system.extraDependencies = [ nix-bitcoin ];
}
-7
View File
@@ -1,7 +0,0 @@
{ lib, ... }: {
imports = [
./configuration.nix
<nix-bitcoin/modules/deployment/krops.nix>
<qemu-vm/vm-config.nix>
];
}
-20
View File
@@ -1,20 +0,0 @@
let
# FIXME:
target = "root@HOSTNAME_OR_IP_ADDRESS";
extraSources = {
"hardware-configuration.nix".file = toString ../hardware-configuration.nix;
};
krops = (import <nix-bitcoin> {}).krops;
in
krops.pkgs.krops.writeDeploy "deploy" {
inherit target;
source = import ./sources.nix { inherit extraSources krops; };
# Avoid having to create a sentinel file.
# Otherwise /var/src/.populate must be created on the target node to signal krops
# that it is allowed to deploy.
force = true;
}
-7
View File
@@ -1,7 +0,0 @@
# This file allows you to build your krops configuration locally
{
imports = [
../configuration.nix
<nix-bitcoin/modules/deployment/krops.nix>
];
}
-43
View File
@@ -1,43 +0,0 @@
{ extraSources, krops }:
krops.lib.evalSource [({
nixos-config.file = builtins.toFile "nixos-config" ''
{
imports = [
./configuration.nix
<nix-bitcoin/modules/deployment/krops.nix>
];
}
'';
"configuration.nix".file = toString ../configuration.nix;
# Enable `useChecksum` for sources which might be located in the nix store
# and which therefore might have static timestamps.
nixpkgs.file = {
path = toString <nixpkgs>;
useChecksum = true;
# TODO-EXTERNAL:
# Work around symlink sync error on macOS/BSD
# (https://github.com/NixOS/nixpkgs/issues/180046)
# by excluding the single symlink that's present in nixpkgs.
filters = [
{
type = "exclude";
pattern = "/pkgs/development/libraries/readline/update-patch-set.sh";
}
];
};
nix-bitcoin.file = {
path = toString <nix-bitcoin>;
useChecksum = true;
filters = [{
type = "exclude";
pattern = ".git";
}];
};
secrets.file = toString ../secrets;
} // extraSources)]
-1
View File
@@ -1 +0,0 @@
../.
-19
View File
@@ -1,19 +0,0 @@
# This is an example network definition for deploying a nix-bitcoin node via NixOps.
# NixOps deployment is currently untested.
{
network.description = "Bitcoin node";
bitcoin-node = { config, pkgs, lib, ... }: {
imports = [
../configuration.nix
<nix-bitcoin/modules/deployment/nixops.nix>
];
nix-bitcoin.deployment.secretsDir = toString ../secrets;
#FIXME:
# Set `deployment.*` options like
# deployment.targetHost = "<address_or_hostname>";
};
}
-7
View File
@@ -1,7 +0,0 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBbda93/QYwDf4PGJp2KgJ1xwKPgKhEHeJrubXAeZWPpgAAAIgDA7dzAwO3
cwAAAAtzc2gtZWQyNTUxOQAAACBbda93/QYwDf4PGJp2KgJ1xwKPgKhEHeJrubXAeZWPpg
AAAECuRSsNFRQgAOid87b/2kIhgycAH5nPgZwkY4bUpq7LQFt1r3f9BjAN/g8YmnYqAnXH
Ao+AqEQd4mu5tcB5lY+mAAAABG5vbmUB
-----END OPENSSH PRIVATE KEY-----
-1
View File
@@ -1 +0,0 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFt1r3f9BjAN/g8YmnYqAnXHAo+AqEQd4mu5tcB5lY+m none
-62
View File
@@ -1,62 +0,0 @@
nix-bitcoin: pkgs: system:
rec {
inherit (nix-bitcoin.inputs) nixpkgs;
mkVMScript = vm: pkgs.writers.writeBash "run-vm" ''
set -euo pipefail
export TMPDIR=$(mktemp -d /tmp/nix-bitcoin-vm.XXX)
trap 'rm -rf $TMPDIR' EXIT
export NIX_DISK_IMAGE=$TMPDIR/nixos.qcow2
# shellcheck disable=SC2211
QEMU_OPTS="-smp $(nproc) -m 1500" ${vm}/bin/run-*-vm
'';
vm = (import (nixpkgs + "/nixos") {
inherit system;
configuration = { config, lib, modulesPath, ... }: {
imports = [
nix-bitcoin.nixosModules.default
(nix-bitcoin + "/modules/presets/secure-node.nix")
(modulesPath + "/virtualisation/qemu-vm.nix")
];
virtualisation.graphics = false;
nix-bitcoin.generateSecrets = true;
services.clightning.enable = true;
# disable-dns leads to faster startup in offline VMs
services.clightning.extraConfig = ''
disable-dns
'';
# Avoid lengthy build of the nixos manual
documentation.nixos.enable = false;
nixpkgs.pkgs = pkgs;
services.getty.autologinUser = "root";
nix.nixPath = [ "nixpkgs=${nixpkgs}" ];
services.getty.helpLine = lib.mkAfter ''
Welcome to nix-bitcoin!
To explore running services, try the following commands:
nodeinfo
systemctl status bitcoind
systemctl status clightning
bitcoin-cli -getinfo
lightning-cli getinfo
'';
# Power off VM when the user exits the shell
systemd.services."serial-getty@".preStop = ''
echo o >/proc/sysrq-trigger
'';
system.stateVersion = lib.mkDefault config.system.nixos.release;
};
}).config.system.build.vm;
runVM = mkVMScript vm;
}
-52
View File
@@ -1,52 +0,0 @@
qemuDir=$(cd "${BASH_SOURCE[0]%/*}" && pwd)
# shellcheck disable=SC1091
source "$qemuDir/wait-until.sh"
tmpDir=/tmp/nix-bitcoin-qemu-vm
mkdir -p "$tmpDir"
# Cleanup on exit
cleanup() {
set +eu
if [[ $qemuPID ]]; then
kill -9 "$qemuPID"
fi
rm -rf "$tmpDir"
}
trap "cleanup" EXIT
identityFile=$qemuDir/id-vm
chmod 0600 "$identityFile"
runVM() {
vm=$1
vmNumCPUs=$2
vmMemoryMiB=$3
sshPort=$4
export NIX_DISK_IMAGE="$tmpDir/img"
export QEMU_NET_OPTS="hostfwd=tcp::${sshPort}-:22"
# shellcheck disable=SC2211
</dev/null "$vm"/bin/run-*-vm -m "$vmMemoryMiB" -smp "$vmNumCPUs" &>/dev/null &
qemuPID=$!
}
vmWaitForSSH() {
echo
printf "Waiting for SSH connection..."
waitUntil "c : 2>/dev/null" 500
echo
}
# Run command in VM
c() {
ssh -p "$sshPort" -i "$identityFile" -o IdentitiesOnly=yes -o ConnectTimeout=1 \
-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR \
-o ControlMaster=auto -o ControlPath=$tmpDir/ssh-connection -o ControlPersist=60 \
root@127.0.0.1 "$@"
}
export identityFile
export sshPort
export tmpDir
export -f c
-15
View File
@@ -1,15 +0,0 @@
{ modulesPath, ... }:
{
# Disable the hardened preset to improve VM performance
disabledModules = [ <nix-bitcoin/modules/presets/hardened.nix> ];
imports = [ (modulesPath + "/virtualisation/qemu-vm.nix") ];
config = {
virtualisation.graphics = false;
services.getty.autologinUser = "root";
users.users.root = {
openssh.authorizedKeys.keyFiles = [ ./id-vm.pub ];
};
};
}
-21
View File
@@ -1,21 +0,0 @@
# Wait until $condition is true, retrying every $intervalMs milliseconds.
# Print a '.' character every second as a progress indicator.
waitUntil() {
condition=$1
intervalMs=$2
lastDotTime=$(getTimeMs)
while ! { t0=$(getTimeMs); eval "$condition"; }; do
now=$(getTimeMs)
if ((now - lastDotTime >= 1000)); then
printf .
lastDotTime=$now
fi
toSleep=$((t0 + intervalMs - now))
if ((toSleep > 0)); then
sleep $((toSleep / 1000)).$((toSleep % 1000));
fi
done
}
getTimeMs() { date +%s%3N; }
-9
View File
@@ -1,9 +0,0 @@
let
nix-bitcoin = toString (import ./nix-bitcoin-release.nix);
in
import "${nix-bitcoin}/helper/makeShell.nix" {
configDir = ./.;
shellVersion = "0.0.51";
# Set this to modify your shell
# extraShellInitCmds = pkgs: ''<my bash code>'';
}
-21
View File
@@ -1,21 +0,0 @@
# Start an interactive bash session in the current bash environment.
USAGE_INFO='
Starting shell...
Run "c COMMAND" to execute a command on the bitcoin node
Run "c" to start a shell session inside the node
Example:
c systemctl status bitcoind
'
# BASH_ENVIRONMENT contains definitions of read-only variables like 'BASHOPTS' that
# cause warnings on evaluation. Suppress these warnings while sourcing.
#
# shellcheck disable=SC2016
BASH_ENVIRONMENT=<(declare -p; declare -pf) \
USAGE_INFO="$USAGE_INFO" \
bash --rcfile <(echo '
source $BASH_ENVIRONMENT 2>/dev/null
echo "$USAGE_INFO"
')
Generated
+1 -94
View File
@@ -1,47 +1,5 @@
{ {
"nodes": { "nodes": {
"extra-container": {
"inputs": {
"flake-utils": [
"flake-utils"
],
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1766155727,
"narHash": "sha256-XGp4HHH6D6ZKiO5RnMzqYJYnZB538EnEflvlTsOKpvo=",
"owner": "erikarvstedt",
"repo": "extra-container",
"rev": "b450bdb24fca1076973c852d87bcb49b8eb5fd49",
"type": "github"
},
"original": {
"owner": "erikarvstedt",
"ref": "0.14",
"repo": "extra-container",
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1786313170, "lastModified": 1786313170,
@@ -58,60 +16,9 @@
"type": "github" "type": "github"
} }
}, },
"nixpkgs-25_05": {
"locked": {
"lastModified": 1767313136,
"narHash": "sha256-16KkgfdYqjaeRGBaYsNrhPRRENs0qzkQVUooNHtoy2w=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "ac62194c3917d5f474c1a844b6fd6da2db95077d",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-25.05",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-unstable": {
"locked": {
"lastModified": 1786348146,
"narHash": "sha256-we5zDEFfn8TgzeWKjKDMIjeQZ59omEPl23NIF+13/ys=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "d482ef84049d9b7276b83a06e4e4d76983830097",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": { "root": {
"inputs": { "inputs": {
"extra-container": "extra-container", "nixpkgs": "nixpkgs"
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs",
"nixpkgs-25_05": "nixpkgs-25_05",
"nixpkgs-unstable": "nixpkgs-unstable"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
} }
} }
}, },
+17 -125
View File
@@ -1,135 +1,27 @@
{ {
description = '' description = ''
A collection of Nix packages and NixOS modules for easily NixOS modules for a Bitcoin node (bitcoind, lnd, electrs, mempool),
installing full-featured Bitcoin nodes with an emphasis on security. trimmed from fort-nix/nix-bitcoin.
''; '';
inputs = { inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
nixpkgs-unstable.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
nixpkgs-25_05.url = "github:NixOS/nixpkgs/nixos-25.05";
flake-utils.url = "github:numtide/flake-utils";
extra-container = {
url = "github:erikarvstedt/extra-container/0.14";
inputs.nixpkgs.follows = "nixpkgs";
inputs.flake-utils.follows = "flake-utils";
};
};
outputs = { self, nixpkgs, nixpkgs-unstable, nixpkgs-25_05, flake-utils, ... }: outputs = { self, nixpkgs }:
let let
supportedSystems = [ supportedSystems = [ "x86_64-linux" "aarch64-linux" ];
"x86_64-linux" forAllSystems = f: nixpkgs.lib.genAttrs supportedSystems
"aarch64-linux" (system: f nixpkgs.legacyPackages.${system});
# On these 32-bit platforms, Python pkg `pymemcache` 4.0.0 (required by
# `joinmarket`) is broken:
# "i686-linux"
# "armv7l-linux"
];
test = import ./test/tests.nix nixpkgs.lib self.nixosModules.default;
in { in {
lib = { nixosModules.default = ./modules/modules.nix;
mkNbPkgs = {
system
, pkgs ? nixpkgs.legacyPackages.${system}
, pkgsUnstable ? nixpkgs-unstable.legacyPackages.${system}
, pkgs-25_05 ? nixpkgs-25_05.legacyPackages.${system}
}:
import ./pkgs { inherit pkgs pkgsUnstable pkgs-25_05; };
test = { overlays.default = final: prev: import ./pkgs { pkgs = final; };
inherit (test) scenarios;
packages = forAllSystems (pkgs: {
inherit (import ./pkgs { inherit pkgs; })
mempool-backend
mempool-frontend
mempool-rust-gbt
mempool-nginx-conf;
});
}; };
inherit supportedSystems;
};
overlays.default = final: prev: let
nbPkgs = self.lib.mkNbPkgs { inherit (final) system; pkgs = final; };
in removeAttrs nbPkgs [ "pinned" "nixops19_09" "krops" ];
nixosModules.default = { config, pkgs, lib, ... }: {
imports = [ ./modules/modules.nix ];
options = with lib; {
nix-bitcoin.useVersionLockedPkgs = mkOption {
type = types.bool;
default = false;
description = ''
Use the nixpkgs version locked by this flake for `nix-bitcoin.pkgs`.
Only relevant if you are using a nixpkgs version for evaluating your system
that differs from the one that is locked by this flake (via input `nixpkgs`).
If this is the case, enabling this option may result in a more stable system
because the nix-bitcoin services use the exact pkgs versions that are tested
by nix-bitcoin.
The downsides are increased evaluation times and increased system
closure size.
If `false`, the default system pkgs are used.
'';
};
};
config = {
nix-bitcoin.pkgs =
if config.nix-bitcoin.useVersionLockedPkgs
then (self.lib.mkNbPkgs { inherit (config.nixpkgs) system; }).modulesPkgs
else (self.lib.mkNbPkgs { inherit (pkgs.stdenv.hostPlatform) system; inherit pkgs; }).modulesPkgs;
};
};
templates.default = {
description = "Basic node template";
path = ./examples/flakes;
};
} // (flake-utils.lib.eachSystem supportedSystems (system:
let
pkgs = nixpkgs.legacyPackages.${system};
nbPkgs = self.lib.mkNbPkgs { inherit system pkgs; };
in rec {
packages = flake-utils.lib.flattenTree (removeAttrs nbPkgs [
"fetchNodeModules"
"krops"
"modulesPkgs"
"netns-exec"
"nixops19_09"
"pinned"
"generate-secrets"
"nbPython3Packages"
"nbPython3PackagesJoinmarket"
]) // {
inherit (import ./examples/qemu-vm/minimal-vm.nix self pkgs system)
# A simple demo VM.
# See ./examples/flakes/flake.nix on how to use nix-bitcoin with flakes.
runVM
vm;
};
# Allow accessing the whole nested `nbPkgs` attrset (including `modulesPkgs`)
# via this flake.
# `packages` is not allowed to contain nested pkgs attrsets.
legacyPackages =
nbPkgs //
(test.pkgs self pkgs) //
{
extra-container = self.inputs.extra-container.packages.${system}.default;
ciTestInfo = import ./test/ci/test-info.nix pkgs legacyPackages.instantiateTests;
};
apps = rec {
default = vm;
# Run a basic nix-bitcoin node in a VM
vm = {
type = "app";
program = toString packages.runVM;
};
};
devShells.default = import ./dev/dev-env/dev-shell.nix pkgs;
}
));
} }
-46
View File
@@ -1,46 +0,0 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash coreutils curl jq gnupg gnugrep
set -euo pipefail
scriptDir=$(cd "${BASH_SOURCE[0]%/*}" && pwd)
trap 'echo "Error at ${BASH_SOURCE[0]}:$LINENO"' ERR
repo=fort-nix/nix-bitcoin
if [[ ! -v version ]]; then
version=$(curl -fsS "https://api.github.com/repos/$repo/releases/latest" | jq -r '.tag_name' | tail -c +2)
fi
TMPDIR=$(mktemp -d)
trap 'rm -rf $TMPDIR' EXIT
export GNUPGHOME=$TMPDIR/gpg-home
mkdir -m 700 "$GNUPGHOME"
# Import key
gpg --import "$scriptDir/key-jonasnick.bin" &> /dev/null
# Check that exactly one key was imported
(($(gpg --list-keys --with-colons | grep -c pub) == 1))
# Verify key fingerprint
gpg --list-keys "36C7 1A37 C9D9 88BD E825 08D9 B1A7 0E4F 8DCD 0366" > /dev/null
# Fetch nar-hash of release
cd "$TMPDIR"
baseUrl=https://github.com/$repo/releases/download/v$version
curl -fsS -L -O "$baseUrl/nar-hash.txt"
curl -fsS -L -O "$baseUrl/nar-hash.txt.asc"
# Verify signature for nar-hash
gpg --verify nar-hash.txt.asc &> /dev/null || {
>&2 echo "Error: Signature verification failed. Please open an issue in the project repository."
exit 1
}
>&2 echo "Fetched and verified release $version"
cat <<EOF
builtins.fetchTarball {
url = "https://github.com/$repo/archive/v$version.tar.gz";
sha256 = "$(cat nar-hash.txt)";
}
EOF
Binary file not shown.
-159
View File
@@ -1,159 +0,0 @@
{ configDir, shellVersion ? null, extraShellInitCmds ? (pkgs: "") }:
let
pinned = import ../pkgs/nixpkgs-pinned.nix;
pkgs = import nixpkgs { config = {}; overlays = []; };
inherit (pkgs) lib;
inherit (pinned) nixpkgs;
nbPkgs = import ../pkgs { inherit pkgs; };
cfgDir = toString configDir;
setPath = lib.optionalString pkgs.stdenv.isLinux ''
export PATH="${lib.makeBinPath [ nbPkgs.pinned.extra-container ]}''${PATH:+:}$PATH"
'';
in
pkgs.stdenv.mkDerivation {
name = "nix-bitcoin-environment";
helpMessage = ''
nix-bitcoin path: ${toString ../.}
Available commands
==================
deploy
Run krops-deploy and eval-config in parallel.
This ensures that eval failures appear quickly when deploying.
In this case, deployment is stopped.
krops-deploy
Deploy your node via krops
eval-config
Evaluate your node system configuration
build-config
Build your node system on your local machine
generate-secrets
Create secrets required by your node configuration.
Secrets are written to ./secrets/
This function is automatically called by krops-deploy.
update-nix-bitcoin
Fetch and use the latest version of nix-bitcoin
'';
shellHook = ''
export NIX_PATH="nixpkgs=${nixpkgs}:nix-bitcoin=${toString ../.}:."
${setPath}
export NIX_BITCOIN_EXAMPLES_DIR="${cfgDir}"
export nixpkgsUnstable="${pinned.nixpkgs-unstable}"
# Set isInteractive=1 if
# 1. stdout is a TTY, i.e. we're not piping the output
# 2. the shell is interactive
if [[ -t 1 && $- == *i* ]]; then isInteractive=1; else isInteractive=; fi
# Make this a non-environment var
export -n helpMessage
help() { echo "$helpMessage"; }
h() { help; }
fetch-release() {
${toString ./fetch-release}
}
update-nix-bitcoin() {(
set -euo pipefail
releaseFile="${cfgDir}/nix-bitcoin-release.nix"
current=$(cat "$releaseFile" 2>/dev/null || true)
new=$(fetch-release)
if [[ $new == $current ]]; then
echo "nix-bitcoin-release.nix already contains the latest release"
else
echo "$new" > "$releaseFile"
echo "Updated nix-bitcoin-release.nix"
if [[ $isInteractive ]]; then
exec nix-shell
fi
fi
)}
generate-secrets() {(
set -euo pipefail
config="${cfgDir}/krops/krops-configuration.nix"
if [[ ! -e $config ]]; then
config="${cfgDir}/configuration.nix"
fi
genSecrets=$(nix-build --no-out-link -I nixos-config="$config" \
'<nixpkgs/nixos>' -A config.nix-bitcoin.generateSecretsScript)
mkdir -p "${cfgDir}/secrets"
(cd "${cfgDir}/secrets"; $genSecrets)
)}
deploy() {(
set -euo pipefail
krops-deploy &
kropsPid=$!
if eval-config; then
wait $kropsPid
else
# Kill all subprocesses
kill $(pidClosure $kropsPid)
return 1
fi
)}
krops-deploy() {(
set -euo pipefail
generate-secrets
# Ensure strict permissions on secrets/ directory before rsyncing it to
# the target machine
chmod 700 "${cfgDir}/secrets"
$(nix-build --no-out-link "${cfgDir}/krops/deploy.nix")
)}
eval-config() {(
set -euo pipefail
system=$(getNodeSystem)
NIXOS_CONFIG="${cfgDir}/krops/krops-configuration.nix" \
nix-instantiate --eval ${nixpkgs}/nixos $system -A system.outPath | tr -d '"'
echo
)}
build-config() {(
set -euo pipefail
system=$(getNodeSystem)
NIXOS_CONFIG="${cfgDir}/krops/krops-configuration.nix" \
nix-build --no-out-link ${nixpkgs}/nixos $system -A system
)}
getNodeSystem() {
if [[ -e '${cfgDir}/krops/system' ]]; then
echo -n "--argstr system "; cat '${cfgDir}/krops/system'
elif [[ $OSTYPE == darwin* ]]; then
# On macOS, `builtins.currentSystem` (`*-darwin`) can never equal
# the node system (`*-linux`), so we can always provide a helpful error message:
>&2 echo "Error, node system not set. See here how to fix this:"
>&2 echo "https://github.com/fort-nix/nix-bitcoin/blob/master/docs/install.md#optional-specify-the-system-of-your-node"
return 1
fi
};
pidClosure() {
echo "$1"
for pid in $(ps -o pid= --ppid "$1"); do
pidClosure "$pid"
done
}
if [[ $isInteractive ]]; then
${pkgs.figlet}/bin/figlet "nix-bitcoin"
echo 'Enter "h" or "help" for documentation.'
fi
# Don't run this hook when another nix-shell is run inside this shell
unset shellHook
${extraShellInitCmds pkgs}
'';
}
-119
View File
@@ -1,119 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
REPO=fort-nix/nix-bitcoin
BRANCH=master
GIT_REMOTE=origin
OAUTH_TOKEN=
DRY_RUN=
releaseVersion=
trap 'echo "Error at ${BASH_SOURCE[0]}:$LINENO"' ERR
cd "${BASH_SOURCE[0]%/*}"
for arg in "$@"; do
case $arg in
--dry-run|-n)
DRY_RUN=1
;;
*)
releaseVersion="$arg"
;;
esac
done
latestVersion=$(curl -fsS https://api.github.com/repos/$REPO/releases/latest | jq -r '.tag_name' | tail -c +2)
if [[ ! $releaseVersion ]]; then
# Increment the lowest/last part of `latestVersion`
releaseVersion=$(echo "$latestVersion" | awk -F. '/[0-9]+\./{$NF++;print}' OFS=.)
fi
if [[ $DRY_RUN ]]; then
echo "Dry run"
else
OAUTH_TOKEN=$(pass show nix-bitcoin/github/oauth-token)
if [[ ! $OAUTH_TOKEN ]]; then
echo "Error fetching OAUTH_TOKEN"
exit 1
fi
fi
echo "Latest release: $latestVersion"
if [[ ! $DRY_RUN ]]; then
while true; do
read -rp "Create release ${releaseVersion}? [yn] " yn
case $yn in
[Yy]* ) break;;
[Nn]* ) exit;;
* ) echo "Please answer y or n.";;
esac
done
fi
nixosVersion=$(sed -nE 's|.*system.stateVersion = "(.*?)".*|\1|p' ../examples/configuration.nix)
if [[ ! $nixosVersion ]]; then
echo "Error fetching NixOS version"
exit 1
fi
nixosVersionBranch=nixos-$nixosVersion
TMPDIR=$(mktemp -d)
if [[ ! $DRY_RUN ]]; then trap 'rm -rf $TMPDIR' EXIT; fi
ARCHIVE_NAME=nix-bitcoin-$releaseVersion.tar.gz
ARCHIVE=$TMPDIR/$ARCHIVE_NAME
# Need to be in the repo root directory for archiving
(cd "$(git rev-parse --show-toplevel)"; git archive --format=tar.gz -o "$ARCHIVE" "$BRANCH")
SHA256SUMS=$TMPDIR/SHA256SUMS.txt
# Use relative path with sha256sums because it'll output the first
# argument
(cd "$TMPDIR"; sha256sum "$ARCHIVE_NAME" > "$SHA256SUMS")
gpg -o "$SHA256SUMS.asc" -a --detach-sig "$SHA256SUMS"
pushd "$TMPDIR" >/dev/null
nix hash to-sri --type sha256 "$(nix-prefetch-url --unpack "file://$ARCHIVE" 2> /dev/null)" > nar-hash.txt
gpg -o nar-hash.txt.asc -a --detach-sig nar-hash.txt
if [[ $DRY_RUN ]]; then
echo "Created v$releaseVersion in $TMPDIR"
echo "NixOS version branch: $nixosVersionBranch"
exit 0
fi
#―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
# Create release
POST_DATA="{ \"tag_name\": \"v$releaseVersion\", \"name\": \"nix-bitcoin-$releaseVersion\", \"body\": \"nix-bitcoin-$releaseVersion\", \"target_comitish\": \"$BRANCH\" }"
RESPONSE=$(curl -fsS -H "Authorization: token $OAUTH_TOKEN" -d "$POST_DATA" https://api.github.com/repos/$REPO/releases)
ID=$(echo "$RESPONSE" | jq -r '.id')
if [[ $ID == null ]]; then
echo "Failed to create release with $POST_DATA"
exit 1
fi
post_asset() {
GH_ASSET="https://uploads.github.com/repos/$REPO/releases/$ID/assets?name="
curl -fsS -H "Authorization: token $OAUTH_TOKEN" --data-binary "@$1" -H "Content-Type: application/octet-stream" \
"$GH_ASSET/$(basename "$1")"
}
post_asset nar-hash.txt
post_asset nar-hash.txt.asc
# Post additional assets for backwards compatibility.
# This allows older nix-bitcoin installations to upgrade via `fetch-release`.
post_asset "$ARCHIVE"
post_asset "$SHA256SUMS"
post_asset "$SHA256SUMS.asc"
popd >/dev/null
if [[ ! $DRY_RUN ]]; then
git push "$GIT_REMOTE" "$BRANCH:release"
git push "$GIT_REMOTE" "$BRANCH:$nixosVersionBranch"
fi
echo "Successfully created" "$(echo "$POST_DATA" | jq -r .tag_name)"
-20
View File
@@ -1,20 +0,0 @@
#!/usr/bin/env bash
# Usage:
# source "path/to/run-in-nix-env" "pkg1 pkg2 ..." "$@"
#
# Runs the calling script with pkgs1, pkg2, ... in PATH.
# The packages are sourced from the nixpkgs input of the nix-bitcoin root flake.
if [[ ${_NIX_BITCOIN_ENV_PKGS:-} != "$1" ]]; then
export _NIX_BITCOIN_ENV_PKGS=$1
shift
_shell_pkgs=()
for _pkg in $_NIX_BITCOIN_ENV_PKGS; do
_shell_pkgs+=("nixpkgs#$_pkg")
done
# BASH_SOURCE[0] is this file
# BASH_SOURCE[-1] is the root src file
exec nix shell --inputs-from "${BASH_SOURCE[0]%/*}/.." "${_shell_pkgs[@]}" -c "${BASH_SOURCE[-1]}" "$@"
fi
-12
View File
@@ -1,12 +0,0 @@
# Start an interactive bash session in the current bash environment.
# This is helpful for debugging bash scripts like pkg update scripts,
# by adding `source <path-to>/start-bash-session.sh` at the location to
# be inspected.
# BASH_ENVIRONMENT contains definitions of read-only variables like 'BASHOPTS' that
# cause warnings on evaluation. Suppress these warnings while sourcing.
#
# shellcheck disable=SC2016
BASH_ENVIRONMENT=<(declare -p; declare -pf) \
bash --rcfile <(echo 'source $BASH_ENVIRONMENT 2>/dev/null')
-78
View File
@@ -1,78 +0,0 @@
{ prevVersions ? null }:
let
flake = builtins.getFlake (toString ../.);
inherit (flake.inputs.nixpkgs) lib;
in rec {
# Convert the list of pinned pkgs to an attrset with form
# {
# stable = { bitcoind = "0.21.1"; ... };
# unstable = { btcpayserver = "1.2.1"; ... };
# }
# A pinned pkg is added to `stable` if its stable version is newer or
# identical to the unstable version.
versions = let
pinned = flake.legacyPackages.x86_64-linux.pinned;
pinnedPkgs = lib.filterAttrs (n: v: lib.isDerivation v) pinned;
stable = pinned.pkgs;
unstable = pinned.pkgsUnstable;
isStable = builtins.partition (pkgName:
!(unstable ? "${pkgName}") ||
((stable ? "${pkgName}")
&& (builtins.compareVersions stable.${pkgName}.version unstable.${pkgName}.version >= 0))
) (builtins.attrNames pinnedPkgs);
in {
stable = lib.genAttrs isStable.right (pkgName: stable.${pkgName}.version);
unstable = lib.genAttrs isStable.wrong (pkgName: unstable.${pkgName}.version);
};
showUpdates = let
prev = builtins.fromJSON prevVersions;
prevPkgs = prev.stable // prev.unstable;
mapFilter = f: xs: lib.remove null (map f xs);
mkChanges = title: pkgs:
let
lines = mapFilter (pkgName:
let
version = pkgs.${pkgName};
prevVersion = prevPkgs.${pkgName};
in
if version != prevVersion then
"${pkgName}: ${prevVersion} -> ${version}"
else
null
) (builtins.attrNames pkgs);
in
if lines == [] then
null
else
builtins.concatStringsSep "\n" ([title] ++ lines);
changes = [
(mkChanges "Pkg updates in nixpkgs stable:" versions.stable)
(mkChanges "Pkg updates in nixpkgs unstable:" versions.unstable)
];
allChanges = builtins.concatStringsSep "\n\n" (lib.remove null changes);
in
if allChanges == "" then
"No pkg version updates."
else
allChanges;
pinnedFile = let
toLines = pkgs: builtins.concatStringsSep "\n " (builtins.attrNames pkgs);
in ''
# This file is generated by ../helper/update-flake.nix
pkgs: pkgsUnstable: pkgs-25_05:
{
inherit (pkgs)
${toLines versions.stable};
inherit (pkgsUnstable)
${toLines versions.unstable};
inherit pkgs pkgsUnstable pkgs-25_05;
}
'';
}
-80
View File
@@ -1,80 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# This script does the following:
# - When called without arguments, update all flake inputs, including nixpkgs.
# - When called with a version argument, set input `nixpkgs` in `flake.nix` to the
# specified version and only update this input.
# - Print version updates of pinned pkgs like so:
# Pkg updates in nixpkgs unstable:
# bitcoin: 0.20.0 -> 0.21.1
# btcpayserver: 1.1.0 -> 1.1.2
# - Write ../pkgs/pinned.nix:
# Packages for which the stable und unstable versions are identical are
# pinned to stable.
# All other pkgs are pinned to unstable.
forceRun=
nixosVersion=
for arg in "$@"; do
case $arg in
-f)
forceRun=1
;;
*)
nixosVersion=$arg
;;
esac
done
# cd to script dir
cd "${BASH_SOURCE[0]%/*}"
if [[ $(nix flake 2>&1) != *"requires a sub-command"* ]]; then
echo "Error. This script requires nix flake support."
echo "https://nixos.wiki/wiki/Flakes#Installing_flakes"
exit 1
fi
if [[ $forceRun ]] && ! git diff --quiet ../flake.{nix,lock}; then
echo "error: flake.nix/flake.lock have changes. Run with option -f to ignore."
exit 1
fi
if [[ ! $nixosVersion ]]; then
echo "Updating flake 'nixos-search'"
nix flake update --flake ../test/nixos-search
echo
fi
versions=$(nix eval --json -f update-flake.nix versions)
## Uncomment the following to generate a version change message for testing
# versions=$(echo "$versions" | sed 's|1|0|g')
setVersion() {
sed -Ei "s|($1)[0-9.]+|\1$nixosVersion|" "$2"
}
echo "Updating main flake"
if [[ $nixosVersion ]]; then
setVersion 'nixpkgs.url = .*?nixos-' ../flake.nix
setVersion 'system.stateVersion = "' ../examples/configuration.nix
setVersion 'nix-bitcoin.url = .*?/nixos-' ../examples/flakes/flake.nix
setVersion 'nix-bitcoin.url = .*?/nixos-' ../examples/container/flake.nix
setVersion 'update-flake.sh ' ../dev/README.md
nix flake update nixpkgs --flake ..
else
nix flake update --flake ..
fi
echo
nix eval --raw -f update-flake.nix --argstr prevVersions "$versions" showUpdates; echo
pinned=../pkgs/pinned.nix
pinnedSrc=$(nix eval --raw -f update-flake.nix --argstr prevVersions "$versions" pinnedFile)
if [[ $pinnedSrc != $(cat "$pinned") ]]; then
echo "$pinnedSrc" > "$pinned"
echo
echo "Updated pinned.nix"
fi
-127
View File
@@ -1,127 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.backups = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Enable backups of node data.
This uses the NixOS duplicity service.
To further configure the backup, you can set NixOS options `services.duplicity.*`.
The `services.duplicity.cleanup.*` options are particularly useful.
'';
};
with-bulk-data = mkOption {
type = types.bool;
default = false;
description = ''
Whether to also backup Bitcoin blockchain and other bulk data.
'';
};
destination = mkOption {
type = types.str;
default = "file:///var/lib/localBackups";
description = ''
Where to back up to.
'';
};
frequency = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Run backup with the given frequency. If null, do not run automatically.
'';
};
postgresqlDatabases = mkOption {
type = types.listOf types.str;
default = [];
description = "List of database names to backup.";
};
extraFiles = mkOption {
type = types.listOf types.str;
default = [];
example = [ "/var/lib/nginx" ];
description = "Additional files to be appended to filelist.";
};
};
cfg = config.services.backups;
# Potential backup file paths are matched against filelist
# entries from top to bottom.
# The first match determines inclusion or exclusion.
includeFileList = builtins.toFile "filelist.txt" ''
${builtins.concatStringsSep "\n" cfg.extraFiles}
${optionalString (!cfg.with-bulk-data) ''
- ${config.services.bitcoind.dataDir}/blocks
- ${config.services.bitcoind.dataDir}/chainstate
- ${config.services.bitcoind.dataDir}/indexes
''}
${config.services.bitcoind.dataDir}
${config.services.clightning.dataDir}
${config.services.clightning-rest.dataDir}
${config.services.lnd.dataDir}
${optionalString (!cfg.with-bulk-data) ''
- ${config.services.liquidd.dataDir}/*/blocks
- ${config.services.liquidd.dataDir}/*/chainstate
- ${config.services.liquidd.dataDir}/*/indexes
''}
${config.services.liquidd.dataDir}
${optionalString cfg.with-bulk-data "${config.services.electrs.dataDir}"}
${config.services.nbxplorer.dataDir}
${config.services.btcpayserver.dataDir}
${config.services.joinmarket.dataDir}
${optionalString config.nix-bitcoin.generateSecrets "${config.nix-bitcoin.secretsDir}"}
/var/lib/tor
/var/lib/nixos
${builtins.concatStringsSep "\n" postgresqlBackupPaths}
# Exclude all unspecified files and directories
- /
'';
postgresqlBackupDir = config.services.postgresqlBackup.location;
postgresqlBackupPaths = map (db: "${postgresqlBackupDir}/${db}.sql.gz") cfg.postgresqlDatabases;
postgresqlBackupServices = map (db: "postgresqlBackup-${db}.service") cfg.postgresqlDatabases;
in {
inherit options;
config = mkIf cfg.enable {
environment.systemPackages = [ pkgs.duplicity ];
services.duplicity = {
enable = true;
inherit includeFileList;
fullIfOlderThan = mkDefault "1M";
targetUrl = cfg.destination;
frequency = cfg.frequency;
secretFile = "${config.nix-bitcoin.secretsDir}/backup-encryption-env";
};
systemd.services.duplicity = {
wants = postgresqlBackupServices;
after = postgresqlBackupServices ++ [ "nix-bitcoin-secrets.target" ];
};
services.postgresqlBackup = {
enable = mkIf (cfg.postgresqlDatabases != []) true;
databases = cfg.postgresqlDatabases;
};
nix-bitcoin.secrets.backup-encryption-env.user = "root";
nix-bitcoin.generateSecretsCmds.backups = ''
makePasswordSecret backup-encryption-password
if [[ backup-encryption-password -nt backup-encryption-env ]]; then
echo "PASSPHRASE=$(cat backup-encryption-password)" > backup-encryption-env
fi
'';
services.backups.postgresqlDatabases = mkIf config.services.btcpayserver.enable (
[ "btcpaydb" ] ++ optional cfg.with-bulk-data "nbxplorer"
);
};
}
+3 -23
View File
@@ -57,15 +57,15 @@ let
}; };
package = mkOption { package = mkOption {
type = types.package; type = types.package;
default = config.nix-bitcoin.pkgs.bitcoind; default = pkgs.bitcoind;
defaultText = "config.nix-bitcoin.pkgs.bitcoind"; defaultText = lib.literalExpression "pkgs.bitcoind";
description = '' description = ''
The package providing bitcoind binaries. The package providing bitcoind binaries.
You can use this option to select other bitcoind-compatible implementations. You can use this option to select other bitcoind-compatible implementations.
Example: Example:
```nix ```nix
services.bitcoind.package = config.nix-bitcoin.pkgs.bitcoind-knots; services.bitcoind.package = pkgs.bitcoind-knots;
``` ```
''; '';
}; };
@@ -173,14 +173,6 @@ let
default = if cfg.tor.proxy then config.nix-bitcoin.torClientAddressWithPort else null; default = if cfg.tor.proxy then config.nix-bitcoin.torClientAddressWithPort else null;
description = "Connect through SOCKS5 proxy"; description = "Connect through SOCKS5 proxy";
}; };
i2p = mkOption {
type = types.enum [ false true "only-outgoing" ];
default = false;
description = ''
Enable peer connections via i2p.
With `only-outgoing`, incoming i2p connections are disabled.
'';
};
dataDirReadableByGroup = mkOption { dataDirReadableByGroup = mkOption {
type = types.bool; type = types.bool;
default = false; default = false;
@@ -289,8 +281,6 @@ let
nbLib = config.nix-bitcoin.lib; nbLib = config.nix-bitcoin.lib;
secretsDir = config.nix-bitcoin.secretsDir; secretsDir = config.nix-bitcoin.secretsDir;
i2pSAM = config.services.i2pd.proto.sam;
configFile = builtins.toFile "bitcoin.conf" '' configFile = builtins.toFile "bitcoin.conf" ''
# We're already logging via journald # We're already logging via journald
nodebuglogfile=1 nodebuglogfile=1
@@ -318,8 +308,6 @@ let
${optionalString cfg.listenWhitelisted ${optionalString cfg.listenWhitelisted
"whitebind=${cfg.address}:${toString cfg.whitelistedPort}"} "whitebind=${cfg.address}:${toString cfg.whitelistedPort}"}
${optionalString (cfg.proxy != null) "proxy=${cfg.proxy}"} ${optionalString (cfg.proxy != null) "proxy=${cfg.proxy}"}
${optionalString (cfg.i2p != false) "i2psam=${nbLib.addressWithPort i2pSAM.address i2pSAM.port}"}
${optionalString (cfg.i2p == "only-outgoing") "i2pacceptincoming=0"}
${optionalString (cfg.discover != null) "discover=${if cfg.discover then "1" else "0"}"} ${optionalString (cfg.discover != null) "discover=${if cfg.discover then "1" else "0"}"}
${lib.concatMapStrings (node: "addnode=${node}\n") cfg.addnodes} ${lib.concatMapStrings (node: "addnode=${node}\n") cfg.addnodes}
@@ -377,11 +365,6 @@ in {
} }
]; ];
services.i2pd = mkIf (cfg.i2p != false) {
enable = true;
proto.sam.enable = true;
};
systemd.tmpfiles.rules = [ systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group} - -" "d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group} - -"
]; ];
@@ -392,9 +375,6 @@ in {
# Use `wants` instead of `requires` for `nix-bitcoin-secrets.target` # Use `wants` instead of `requires` for `nix-bitcoin-secrets.target`
# so that bitcoind and all dependent services are not restarted when # so that bitcoind and all dependent services are not restarted when
# the secrets target restarts. # the secrets target restarts.
# The secrets target always restarts when deploying with one of the methods
# in ./deployment.
#
# TODO-EXTERNAL: Instead of `wants`, use a future systemd dependency type # TODO-EXTERNAL: Instead of `wants`, use a future systemd dependency type
# that propagates initial start failures but no restarts # that propagates initial start failures but no restarts
"nix-bitcoin-secrets.target" "nix-bitcoin-secrets.target"
-287
View File
@@ -1,287 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services = {
btcpayserver = {
enable = mkEnableOption "btcpayserver, a self-hosted Bitcoin payment processor";
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen on.";
};
port = mkOption {
type = types.port;
default = 23000;
description = "Port to listen on.";
};
package = mkOption {
type = types.package;
default = if cfg.btcpayserver.lbtc then
config.nix-bitcoin.pkgs.btcpayserver.override { altcoinSupport = true; }
else
config.nix-bitcoin.pkgs.btcpayserver;
defaultText = "(See source)";
description = "The package providing btcpayserver binaries.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/btcpayserver";
description = "The data directory for btcpayserver.";
};
lightningBackend = mkOption {
type = types.nullOr (types.enum [ "clightning" "lnd" ]);
default = null;
description = "The lightning node implementation to use.";
};
lbtc = mkOption {
type = types.bool;
default = false;
description = "Enable liquid support in btcpayserver.";
};
rootpath = mkOption {
type = types.nullOr types.str;
default = null;
example = "btcpayserver";
description = "The prefix for root-relative btcpayserver URLs.";
};
user = mkOption {
type = types.str;
default = "btcpayserver";
description = "The user as which to run btcpayserver.";
};
group = mkOption {
type = types.str;
default = cfg.btcpayserver.user;
description = "The group as which to run btcpayserver.";
};
tor.enforce = nbLib.tor.enforce;
};
nbxplorer = {
enable = mkOption {
# This option is only used by netns-isolation
internal = true;
default = cfg.btcpayserver.enable;
description = ''
nbxplorer is always enabled when btcpayserver is enabled.
'';
};
package = mkOption {
type = types.package;
default = config.nix-bitcoin.pkgs.nbxplorer;
defaultText = "config.nix-bitcoin.pkgs.nbxplorer";
description = "The package providing nbxplorer binaries.";
};
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen on.";
};
port = mkOption {
type = types.port;
default = 24444;
description = "Port to listen on.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/nbxplorer";
description = "The data directory for nbxplorer.";
};
user = mkOption {
type = types.str;
default = "nbxplorer";
description = "The user as which to run nbxplorer.";
};
group = mkOption {
type = types.str;
default = cfg.nbxplorer.user;
description = "The group as which to run nbxplorer.";
};
tor.enforce = nbLib.tor.enforce;
};
};
cfg = config.services;
nbLib = config.nix-bitcoin.lib;
inherit (config.services) bitcoind liquidd;
in {
inherit options;
config = mkIf cfg.btcpayserver.enable {
services.bitcoind = {
enable = true;
rpc.users.btcpayserver = {
passwordHMACFromFile = true;
rpcwhitelist = cfg.bitcoind.rpc.users.public.rpcwhitelist ++ [
"setban"
"generatetoaddress"
];
};
listenWhitelisted = true;
};
services.clightning.enable = mkIf (cfg.btcpayserver.lightningBackend == "clightning") true;
services.lnd = mkIf (cfg.btcpayserver.lightningBackend == "lnd") {
enable = true;
macaroons.btcpayserver = {
inherit (cfg.btcpayserver) user;
permissions = ''{"entity":"info","action":"read"},{"entity":"onchain","action":"read"},{"entity":"offchain","action":"read"},{"entity":"address","action":"read"},{"entity":"message","action":"read"},{"entity":"peers","action":"read"},{"entity":"signer","action":"read"},{"entity":"invoices","action":"read"},{"entity":"invoices","action":"write"},{"entity":"address","action":"write"}'';
};
};
services.liquidd = mkIf cfg.btcpayserver.lbtc {
enable = true;
listenWhitelisted = true;
};
services.postgresql = {
enable = true;
ensureDatabases = [
"btcpaydb" # This name is kept for backwards compatibility
"nbxplorer"
];
ensureUsers = [
{ name = cfg.btcpayserver.user; }
{ name = cfg.nbxplorer.user; }
];
};
systemd.services.postgresql-setup.postStart = ''
psql -tAc '
ALTER DATABASE "btcpaydb" OWNER TO "${cfg.btcpayserver.user}";
ALTER DATABASE "nbxplorer" OWNER TO "${cfg.nbxplorer.user}";
'
'';
systemd.tmpfiles.rules = [
"d '${cfg.nbxplorer.dataDir}' 0770 ${cfg.nbxplorer.user} ${cfg.nbxplorer.group} - -"
"d '${cfg.btcpayserver.dataDir}' 0770 ${cfg.btcpayserver.user} ${cfg.btcpayserver.group} - -"
];
systemd.services.nbxplorer = let
configFile = builtins.toFile "config" ''
network=${bitcoind.network}
btcrpcuser=${cfg.bitcoind.rpc.users.btcpayserver.name}
btcrpcurl=http://${nbLib.addressWithPort bitcoind.rpc.address cfg.bitcoind.rpc.port}
btcnodeendpoint=${nbLib.addressWithPort bitcoind.address bitcoind.whitelistedPort}
bind=${cfg.nbxplorer.address}
port=${toString cfg.nbxplorer.port}
${optionalString cfg.btcpayserver.lbtc ''
chains=btc,lbtc
lbtcrpcuser=${liquidd.rpcuser}
lbtcrpcurl=http://${nbLib.addressWithPort liquidd.rpc.address liquidd.rpc.port}
lbtcnodeendpoint=${nbLib.addressWithPort liquidd.address liquidd.whitelistedPort}
''}
postgres=User ID=${cfg.nbxplorer.user};Host=/run/postgresql;Database=nbxplorer
'';
in rec {
wantedBy = [ "multi-user.target" ];
requires = [ "postgresql.target" ];
wants = [ "bitcoind.service" ] ++ optional cfg.btcpayserver.lbtc "liquidd.service";
after = requires ++ wants ++ [ "nix-bitcoin-secrets.target" ];
preStart = ''
install -m 600 ${configFile} '${cfg.nbxplorer.dataDir}/settings.config'
{
echo "btcrpcpassword=$(cat ${config.nix-bitcoin.secretsDir}/bitcoin-rpcpassword-btcpayserver)"
${optionalString cfg.btcpayserver.lbtc ''
echo "lbtcrpcpassword=$(cat ${config.nix-bitcoin.secretsDir}/liquid-rpcpassword)"
''}
} >> '${cfg.nbxplorer.dataDir}/settings.config'
'';
serviceConfig = nbLib.defaultHardening // {
ExecStart = ''
${cfg.nbxplorer.package}/bin/nbxplorer --conf=${cfg.nbxplorer.dataDir}/settings.config \
--datadir=${cfg.nbxplorer.dataDir}
'';
User = cfg.nbxplorer.user;
Restart = "on-failure";
RestartSec = "10s";
ReadWritePaths = [ cfg.nbxplorer.dataDir ];
MemoryDenyWriteExecute = false;
} // nbLib.allowedIPAddresses cfg.nbxplorer.tor.enforce;
};
systemd.services.btcpayserver = let
nbExplorerUrl = "http://${nbLib.addressWithPort cfg.nbxplorer.address cfg.nbxplorer.port}/";
nbExplorerCookie = "${cfg.nbxplorer.dataDir}/${bitcoind.makeNetworkName "Main" "RegTest"}/.cookie";
configFile = builtins.toFile "btcpayserver-config" (''
network=${bitcoind.network}
bind=${cfg.btcpayserver.address}
port=${toString cfg.btcpayserver.port}
socksendpoint=${config.nix-bitcoin.torClientAddressWithPort}
btcexplorerurl=${nbExplorerUrl}
btcexplorercookiefile=${nbExplorerCookie}
postgres=User ID=${cfg.btcpayserver.user};Host=/run/postgresql;Database=btcpaydb
'' + optionalString (cfg.btcpayserver.rootpath != null) ''
rootpath=${cfg.btcpayserver.rootpath}
'' + optionalString (cfg.btcpayserver.lightningBackend == "clightning") ''
btclightning=type=clightning;server=unix:///${cfg.clightning.dataDir}/${bitcoind.makeNetworkName "bitcoin" "regtest"}/lightning-rpc
'' + optionalString (cfg.btcpayserver.lightningBackend == "lnd")
(
"btclightning=type=lnd-rest;" +
"server=https://${nbLib.address cfg.lnd.restAddress}:${toString cfg.lnd.restPort}/;" +
"macaroonfilepath=/run/lnd/btcpayserver.macaroon;" +
"certfilepath=${config.services.lnd.certPath}" +
"\n"
)
+ optionalString cfg.btcpayserver.lbtc ''
chains=btc,lbtc
lbtcexplorerurl=${nbExplorerUrl}
lbtcexplorercookiefile=${nbExplorerCookie}
'');
in rec {
wantedBy = [ "multi-user.target" ];
requires = [ "postgresql.target" ];
wants = [ "nbxplorer.service" ]
++ optional (cfg.btcpayserver.lightningBackend != null) "${cfg.btcpayserver.lightningBackend}.service";
after = requires ++ wants;
serviceConfig = nbLib.defaultHardening // {
ExecStart = ''
${cfg.btcpayserver.package}/bin/btcpayserver --conf=${configFile} \
--datadir='${cfg.btcpayserver.dataDir}'
'';
User = cfg.btcpayserver.user;
# Since 2.4.0, btcpayserver uses `Host.CreateDefaultBuilder`, which sets the
# ASP.NET content root to the working directory instead of the app directory.
# The web root (`wwwroot`) is resolved relative to the content root, so
# btcpayserver must be started from its app directory.
WorkingDirectory = "${cfg.btcpayserver.package}/lib/btcpayserver";
# Also restart after the program has exited successfully.
# This is required to support restarting from the web interface after
# interactive plugin installation.
# Restart rate limiting is implemented via the `startLimit*` options below.
Restart = "always";
ReadWritePaths = [ cfg.btcpayserver.dataDir ];
MemoryDenyWriteExecute = false;
} // nbLib.allowedIPAddresses cfg.btcpayserver.tor.enforce;
startLimitIntervalSec = 30;
startLimitBurst = 10;
};
users.users.${cfg.nbxplorer.user} = {
isSystemUser = true;
group = cfg.nbxplorer.group;
extraGroups = [ "bitcoinrpc-public" ]
++ optional cfg.btcpayserver.lbtc liquidd.group;
home = cfg.nbxplorer.dataDir;
};
users.groups.${cfg.nbxplorer.group} = {};
users.users.${cfg.btcpayserver.user} = {
isSystemUser = true;
group = cfg.btcpayserver.group;
extraGroups = [ cfg.nbxplorer.group ]
++ optional (cfg.btcpayserver.lightningBackend == "clightning") cfg.clightning.user;
home = cfg.btcpayserver.dataDir;
};
users.groups.${cfg.btcpayserver.group} = {};
nix-bitcoin.secrets = {
bitcoin-rpcpassword-btcpayserver = {
user = cfg.bitcoind.user;
group = cfg.nbxplorer.group;
};
bitcoin-HMAC-btcpayserver.user = cfg.bitcoind.user;
};
nix-bitcoin.generateSecretsCmds.btcpayserver = ''
makeBitcoinRPCPassword btcpayserver
'';
};
}
-136
View File
@@ -1,136 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.charge-lnd = with types; {
enable = mkEnableOption "charge-lnd, policy-based fee manager";
extraFlags = mkOption {
type = listOf str;
default = [];
example = [ "--verbose" "--dry-run" ];
description = "Extra flags to pass to the charge-lnd command.";
};
interval = mkOption {
type = str;
default = "*-*-* 04:00:00";
example = "hourly";
description = ''
Systemd calendar expression when to adjust fees.
See {man}`systemd.time(7)` for possible values.
Default is once a day.
'';
};
randomDelay = mkOption {
type = str;
default = "1h";
description = ''
Random delay to add to scheduled time.
'';
};
policies = mkOption {
type = types.lines;
default = "";
example = ''
[discourage-routing-out-of-balance]
chan.max_ratio = 0.1
chan.min_capacity = 250000
strategy = static
base_fee_msat = 10000
fee_ppm = 500
[encourage-routing-to-balance]
chan.min_ratio = 0.9
chan.min_capacity = 250000
strategy = static
base_fee_msat = 1
fee_ppm = 2
[default]
strategy = ignore
'';
description = ''
Policy definitions in INI format.
See https://github.com/accumulator/charge-lnd/blob/master/README.md#usage
for possible properties and parameters.
Policies are evaluated from top to bottom.
The first matching policy (or `default`) is applied.
'';
};
};
cfg = config.services.charge-lnd;
nbLib = config.nix-bitcoin.lib;
lnd = config.services.lnd;
user = "charge-lnd";
group = user;
dataDir = "/var/lib/charge-lnd";
configFile = builtins.toFile "charge-lnd.config" cfg.policies;
checkedConfig = pkgs.runCommand "charge-lnd-checked.config" { } ''
${config.nix-bitcoin.pkgs.charge-lnd}/bin/charge-lnd --check --config ${configFile}
cp ${configFile} $out
'';
in
{
inherit options;
config = mkIf cfg.enable {
services.lnd = {
enable = true;
macaroons.charge-lnd = {
user = user;
permissions = ''{"entity":"info","action":"read"},{"entity":"onchain","action":"read"},{"entity":"offchain","action":"read"},{"entity":"offchain","action":"write"}'';
};
};
systemd.services.charge-lnd = {
documentation = [ "https://github.com/accumulator/charge-lnd/blob/master/README.md" ];
after = [ "lnd.service" ];
requires = [ "lnd.service" ];
# lnd's data directory (--lnddir) is not accessible to charge-lnd.
# Instead use directory "lnddir-proxy" as lnddir and link relevant files to it.
preStart = ''
macaroonDir=${dataDir}/lnddir-proxy/data/chain/bitcoin/mainnet
mkdir -p $macaroonDir
ln -sf /run/lnd/charge-lnd.macaroon $macaroonDir
ln -sf ${lnd.certPath} ${dataDir}/lnddir-proxy/tls.cert
'';
serviceConfig = nbLib.defaultHardening // {
ExecStart = ''
${config.nix-bitcoin.pkgs.charge-lnd}/bin/charge-lnd \
--lnddir ${dataDir}/lnddir-proxy \
--grpc ${nbLib.addressWithPort lnd.rpcAddress lnd.rpcPort} \
--config ${checkedConfig} \
${escapeShellArgs cfg.extraFlags}
'';
Type = "oneshot";
User = user;
Group = group;
StateDirectory = "charge-lnd";
} // nbLib.allowLocalIPAddresses;
};
systemd.timers.charge-lnd = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = cfg.interval;
RandomizedDelaySec = cfg.randomDelay;
};
};
users.users.${user} = {
isSystemUser = true;
group = group;
};
users.groups.${group} = {};
};
}
-64
View File
@@ -1,64 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let cfg = config.services.clightning.plugins.clboss; in
{
options.services.clightning.plugins.clboss = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Whether to enable CLBOSS (clightning plugin).
See also: https://github.com/ZmnSCPxj/clboss#operating
'';
};
min-onchain = mkOption {
type = types.ints.positive;
default = 30000;
description = ''
Target amount (in satoshi) that CLBOSS will leave on-chain.
clboss will only open new channels if the funds in your clightning wallet are
larger than this amount.
'';
};
min-channel = mkOption {
type = types.ints.positive;
default = 500000;
description = "The minimum size (in satoshi) of channels created by CLBOSS.";
};
max-channel = mkOption {
type = types.ints.positive;
default = 16777215;
description = "The maximum size (in satoshi) of channels created by CLBOSS.";
};
zerobasefee = mkOption {
type = types.enum [ "require" "allow" "disallow" ];
default = "allow";
description = ''
`require`: set `base_fee` to 0.
`allow`: set `base_fee` according to the CLBOSS heuristics, which may include value 0.
`disallow`: set `base_fee` to according to the CLBOSS heuristics, with a minimum value of 1.
'';
};
package = mkOption {
type = types.package;
default = config.nix-bitcoin.pkgs.clboss;
defaultText = "config.nix-bitcoin.pkgs.clboss";
description = "The package providing clboss binaries.";
};
};
config = mkIf cfg.enable {
services.clightning.extraConfig = ''
plugin=${cfg.package}/bin/clboss
clboss-min-onchain=${toString cfg.min-onchain}
clboss-min-channel=${toString cfg.min-channel}
clboss-max-channel=${toString cfg.max-channel}
clboss-zerobasefee=${cfg.zerobasefee}
'';
systemd.services.clightning.path = [
pkgs.dnsutils
] ++ optional config.services.clightning.tor.proxy (hiPrio config.nix-bitcoin.torify);
};
}
-90
View File
@@ -1,90 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options = {
services.clightning.plugins.clnrest = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Enable clnrest (clightning plugin).
clnrest provides a clightning REST API, using clightning RPC calls as its backend.
It also broadcasts clightning notifications to listeners connected to its websocket server.
See here for all available options:
https://docs.corelightning.org/docs/rest
Extra options can be set via `services.clightning.extraConfig`.
'';
};
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen for REST connections.";
};
port = mkOption {
type = types.port;
default = 3010;
description = "REST server port.";
};
createAdminRune = mkOption {
type = types.bool;
default = true;
description = ''
Create a rune with admin permissions at path `''${config.services.clightning.networkDir}/admin-rune`.
'';
};
package = mkOption {
type = types.package;
default = config.nix-bitcoin.pkgs.clnrest;
defaultText = "config.nix-bitcoin.pkgs.clnrest";
description = "The package providing clnrest binaries.";
};
};
# Internal read-only options used by `./nodeinfo.nix` and `./onion-services.nix`
services.clnrest = let
inherit (config.nix-bitcoin.lib) mkAlias;
in {
enable = mkAlias cfg.enable;
address = mkAlias cfg.address;
port = mkAlias cfg.port;
};
};
cfg = config.services.clightning.plugins.clnrest;
nbLib = config.nix-bitcoin.lib;
inherit (config.services) clightning;
runePath = "${clightning.networkDir}/admin-rune";
in
{
inherit options;
config = mkIf cfg.enable {
services.clightning.extraConfig = ''
plugin=${cfg.package}/bin/clnrest
clnrest-host=${cfg.address}
clnrest-port=${toString cfg.port}
'';
systemd.services.clightning.postStart = mkAfter (
optionalString cfg.createAdminRune ''
if [[ ! -e '${runePath}' ]]; then
rune=$(${clightning.cli}/bin/lightning-cli createrune | ${pkgs.jq}/bin/jq -r .rune)
install -m 640 <(echo "$rune") '${runePath}'
fi
'' +
# Wait until the clnrest server is listening.
# Usually, the server is already listening at this point.
# But when clnrest is running for the first time, certificates are generated
# before the server starts, which can take a few seconds.
''
while ! { exec 3>/dev/tcp/${nbLib.address cfg.address}/${toString cfg.port}; } &>/dev/null; do
sleep 0.1
done
''
);
};
}
-31
View File
@@ -1,31 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.clightning.plugins = {
currencyrate.enable = mkEnableOption "Currencyrate (clightning plugin)";
monitor.enable = mkEnableOption "Monitor (clightning plugin)";
rebalance.enable = mkEnableOption "Rebalance (clightning plugin)";
};
cfg = config.services.clightning.plugins;
pluginPkgs = config.nix-bitcoin.pkgs.clightning-plugins;
in {
imports = [
./clboss.nix
./clnrest.nix
./feeadjuster.nix
./trustedcoin.nix
./zmq.nix
];
inherit options;
config = {
services.clightning.extraConfig = mkMerge [
(mkIf cfg.currencyrate.enable "plugin=${pluginPkgs.currencyrate.path}")
(mkIf cfg.monitor.enable "plugin=${pluginPkgs.monitor.path}")
(mkIf cfg.rebalance.enable "plugin=${pluginPkgs.rebalance.path}")
];
};
}
@@ -1,78 +0,0 @@
{ config, lib, ... }:
with lib;
let
options.services.clightning.plugins.feeadjuster = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Enable feeaduster (clightning plugin).
This plugin auto-updates channel fees to keep channels balanced.
See here for all available options:
https://github.com/lightningd/plugins/blob/master/feeadjuster/feeadjuster.py
Extra options can be set via `services.clightning.extraConfig`.
'';
};
fuzz = mkOption {
type = types.bool;
default = true;
description = "Enable update threshold randomization and hysteresis.";
};
adjustOnForward = mkOption {
type = types.bool;
default = false;
description = "Automatically update fees on forward events.";
};
method = mkOption {
type = types.enum [ "soft" "default" "hard" ];
default = "default";
description = ''
Adjustment method to calculate channel fees.
`soft`: less difference when adjusting fees.
`hard`: greater difference when adjusting fees.
'';
};
adjustDaily = mkOption {
type = types.bool;
default = true;
description = "Automatically update fees daily.";
};
};
cfg = config.services.clightning.plugins.feeadjuster;
inherit (config.services) clightning;
in
{
inherit options;
config = mkIf (cfg.enable && clightning.enable) {
services.clightning.extraConfig = ''
plugin=${config.nix-bitcoin.pkgs.clightning-plugins.feeadjuster.path}
feeadjuster-adjustment-method="${cfg.method}"
'' + optionalString (!cfg.fuzz) ''
feeadjuster-deactivate-fuzz
'' + optionalString (!cfg.adjustOnForward) ''
feeadjuster-deactivate-fee-update
'';
systemd = mkIf cfg.adjustDaily {
services.clightning-feeadjuster = {
# Only run when clightning is running
requisite = [ "clightning.service" ];
after = [ "clightning.service" ];
serviceConfig = {
Type = "oneshot";
User = "clightning";
ExecStart = "${clightning.package}/bin/lightning-cli --lightning-dir ${clightning.dataDir} feeadjust";
};
unitConfig.JoinsNamespaceOf = [ "clightning.service" ];
startAt = [ "daily" ];
};
timers.clightning-feeadjuster.timerConfig = {
RandomizedDelaySec = "6h";
};
};
};
}
@@ -1,40 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let cfg = config.services.clightning.plugins.trustedcoin; in
{
options.services.clightning.plugins.trustedcoin = {
enable = mkEnableOption "Trustedcoin (clightning plugin)";
package = mkOption {
type = types.package;
default = config.nix-bitcoin.pkgs.trustedcoin;
defaultText = "config.nix-bitcoin.pkgs.trustedcoin";
description = "The package providing trustedcoin binaries.";
};
tor.proxy = mkOption {
type = types.bool;
default = config.services.clightning.tor.proxy;
description = "Whether to proxy outgoing connections with Tor.";
};
};
config = mkIf cfg.enable {
services.clightning = {
useBcliPlugin = false;
extraConfig = ''
plugin=${cfg.package}/bin/trustedcoin
'';
tor.enforce = mkIf (!cfg.tor.proxy) false;
};
systemd.services.clightning.environment = mkIf (cfg.tor.proxy) {
HTTPS_PROXY = let
clnProxy = config.services.clightning.proxy;
proxy = if clnProxy != null then clnProxy else config.nix-bitcoin.torClientAddressWithPort;
in
"socks5://${proxy}";
};
};
}
-50
View File
@@ -1,50 +0,0 @@
{ config, lib, ... }:
with lib;
let
options.services.clightning.plugins.zmq = {
enable = mkEnableOption "ZMQ (clightning plugin)";
} // lib.genAttrs endpoints mkEndpointOption;
cfg = config.services.clightning.plugins.zmq;
nbLib = config.nix-bitcoin.lib;
endpoints = [
"channel-opened"
"connect"
"disconnect"
"invoice-payment"
"warning"
"forward-event"
"sendpay-success"
"sendpay-failure"
];
mkEndpointOption = name:
mkOption {
type = types.nullOr types.str;
default = null;
description = "Endpoint for ${name}";
};
setEndpoint = ep:
let value = builtins.getAttr ep cfg; in
optionalString (value != null) ''
zmq-pub-${ep}=${value}
'';
in
{
inherit options;
config = mkIf cfg.enable {
services.clightning.extraConfig = ''
plugin=${config.nix-bitcoin.pkgs.clightning-plugins.zmq.path}
${concatStrings (map setEndpoint endpoints)}
'';
# The zmq server requires AF_NETLINK
systemd.services.clightning.serviceConfig.RestrictAddressFamilies =
mkForce nbLib.allowNetlink.RestrictAddressFamilies;
};
}
-230
View File
@@ -1,230 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.clightning.replication = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Enable live replication of the clightning database.
This prevents losing off-chain funds when the primary wallet file becomes
inaccessible.
For setting the destination, you can either define option `sshfs.destination`
or `local.directory`.
When `encrypt` is `false`, file `lightningd.sqlite3` is written to the destination.
When `encrypt` is `true`, directory `lightningd-db` is written to the destination.
It includes the encrypted database and gocryptfs metadata.
See also: https://github.com/ElementsProject/lightning/blob/master/doc/BACKUP.md
'';
};
sshfs = {
destination = mkOption {
type = types.nullOr types.str;
default = null;
example = "user@10.0.0.1:directory";
description = ''
The SSH destination for which a SSHFS will be mounted.
`directory` is relative to the home of `user`.
A SSH key is automatically generated and stored in file
`$secretsDir/clightning-replication-ssh`.
The SSH server must allow logins via this key.
I.e., the `authorized_keys` file of `user` must contain
`$secretsDir/clightning-replication-ssh.pub`.
'';
};
port = mkOption {
type = types.port;
default = 22;
description = "SSH port of the remote server.";
};
sshOptions = mkOption {
type = with types; listOf str;
default = [ "reconnect" "ServerAliveInterval=50" ];
description = "SSH options used for mounting the SSHFS.";
};
};
local = {
directory = mkOption {
type = types.nullOr types.path;
default = null;
example = "/var/backup/clightning";
description = ''
This option can be specified instead of `sshfs.destination` to enable
replication to a local directory.
If `local.setupDirectory` is disabled, the directory
- must already exist when `clightning.service` (or `clightning-replication-mounts.service`
if `encrypt` is `true`) starts.
- must have write permissions for the `clightning` user.
This option is also useful if you want to use a custom remote destination,
like a NFS or SMB share.
'';
};
setupDirectory = mkOption {
type = types.bool;
default = true;
description = ''
Create `local.directory` if it doesn't exist and set write permissions
for the `clightning` user.
'';
};
};
encrypt = mkOption {
type = types.bool;
default = false;
description = ''
Whether to encrypt the replicated database with gocryptfs.
The encryption password is automatically generated and stored
in file {file}`$secretsDir/clightning-replication-password`.
'';
};
};
cfg = config.services.clightning.replication;
inherit (config.services) clightning;
secretsDir = config.nix-bitcoin.secretsDir;
network = config.services.bitcoind.makeNetworkName "bitcoin" "regtest";
user = clightning.user;
group = clightning.group;
useSshfs = cfg.sshfs.destination != null;
useMounts = useSshfs || cfg.encrypt;
localDir = cfg.local.directory;
mountsDir = "/var/cache/clightning-replication";
sshfsDir = "${mountsDir}/sshfs";
plaintextDir = "${mountsDir}/plaintext";
destDir =
if cfg.encrypt then
plaintextDir
else if useSshfs then
sshfsDir
else
localDir;
in {
inherit options;
config = mkIf cfg.enable {
assertions = [
{ assertion = useSshfs || (localDir != null);
message = ''
services.clightning.replication: One of `sshfs.destination` or
`local.directory` must be set.
'';
}
{ assertion = !useSshfs || (localDir == null);
message = ''
services.clightning.replication: Only one of `sshfs.destination` and
`local.directory` must be set.
'';
}
];
environment.systemPackages = optionals cfg.encrypt [ pkgs.gocryptfs ];
systemd.tmpfiles.rules = optional (localDir != null && cfg.local.setupDirectory)
"d '${localDir}' 0770 ${user} ${group} - -";
services.clightning.wallet = let
mainDB = "${clightning.dataDir}/${network}/lightningd.sqlite3";
replicaDB = "${destDir}/lightningd.sqlite3";
in "sqlite3://${mainDB}:${replicaDB}";
systemd.services.clightning = {
bindsTo = mkIf useMounts [ "clightning-replication-mounts.service" ];
serviceConfig.ReadWritePaths = [
# We can't simply set `destDir` here because it might point to
# a FUSE mount.
# FUSE mounts can only be set up as `ReadWritePaths` by systemd when they
# are accessible by root.
# But FUSE mounts are only accessible by the mounting user and
# not by root.
# (This could be circumvented by FUSE-mounting `destDir` with option `allow_other`,
# but this would grant access to all users.)
(if useMounts then mountsDir else localDir)
];
};
systemd.services.clightning-replication-mounts = mkIf useMounts {
requiredBy = [ "clightning.service" ];
before = [ "clightning.service" ];
wants = [ "nix-bitcoin-secrets.target" ];
after = [ "nix-bitcoin-secrets.target" ];
path = [
# Includes
# - The SUID-wrapped `fusermount` binary which enables FUSE
# for non-root users
# - The SUID-wrapped `mount` binary, used for unmounting
"/run/wrappers"
] ++ optionals cfg.encrypt [
# Includes `logger`, required by gocryptfs
pkgs.util-linux
];
script =
optionalString useSshfs ''
mkdir -p ${sshfsDir}
${pkgs.sshfs}/bin/sshfs ${cfg.sshfs.destination} -p ${toString cfg.sshfs.port} ${sshfsDir} \
-o ${builtins.concatStringsSep "," ([
"IdentityFile='${secretsDir}'/clightning-replication-ssh-key"
] ++ cfg.sshfs.sshOptions)}
'' +
optionalString cfg.encrypt ''
cipherDir="${if useSshfs then sshfsDir else localDir}/lightningd-db"
mkdir -p "$cipherDir" ${plaintextDir}
gocryptfs=(${pkgs.gocryptfs}/bin/gocryptfs -passfile '${secretsDir}/clightning-replication-password')
# 1. init
if [[ ! -e $cipherDir/gocryptfs.conf ]]; then
"''${gocryptfs[@]}" -init "$cipherDir"
fi
# 2. mount
"''${gocryptfs[@]}" "$cipherDir" ${plaintextDir}
'';
postStop =
optionalString cfg.encrypt ''
umount ${plaintextDir} || true
'' +
optionalString useSshfs ''
umount ${sshfsDir}
'';
serviceConfig = {
StopPropagatedFrom = [ "clightning.service" ];
CacheDirectory = "clightning-replication";
CacheDirectoryMode = "770";
User = user;
RemainAfterExit = "yes";
Type = "oneshot";
};
};
nix-bitcoin = mkMerge [
(mkIf useSshfs {
secrets.clightning-replication-ssh-key = {
user = user;
permissions = "400";
};
generateSecretsCmds.clightning-replication-ssh-key = ''
if [[ ! -f clightning-replication-ssh-key ]]; then
${pkgs.openssh}/bin/ssh-keygen -t ed25519 -q -N "" -C "" -f clightning-replication-ssh-key
fi
'';
})
(mkIf cfg.encrypt {
secrets.clightning-replication-password.user = user;
generateSecretsCmds.clightning-replication-password = ''
makePasswordSecret clightning-replication-password
'';
})
];
};
}
-105
View File
@@ -1,105 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.clightning-rest = {
enable = mkEnableOption "lightning-rest";
port = mkOption {
type = types.port;
default = 3001;
description = "REST server port.";
};
docPort = mkOption {
type = types.port;
default = 4001;
description = "Swagger API documentation server port.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/clightning-rest";
description = "The data directory for clightning-rest.";
};
extraConfig = mkOption {
type = types.attrs;
default = {};
example = {
DOMAIN = "mynode.org";
};
description = ''
Extra config options.
See: https://github.com/Ride-The-Lightning/c-lightning-REST#option-1-via-config-file-cl-rest-configjson
'';
};
# Used by ./rtl.nix
group = mkOption {
readOnly = true;
default = clightning.group;
description = "The group under which clightning-rest is run.";
};
# Rest server address.
# Not configurable. The server always listens on all interfaces:
# https://github.com/Ride-The-Lightning/c-lightning-REST/issues/84
# Required by netns-isolation.
address = mkOption {
internal = true;
default = "0.0.0.0";
};
tor.enforce = nbLib.tor.enforce;
};
cfg = config.services.clightning-rest;
nbLib = config.nix-bitcoin.lib;
nbPkgs = config.nix-bitcoin.pkgs;
inherit (config.services)
bitcoind
clightning;
configFile = builtins.toFile "clightning-rest-config" (builtins.toJSON ({
PORT = cfg.port;
DOCPORT = cfg.docPort;
LNRPCPATH = "${clightning.dataDir}/${bitcoind.makeNetworkName "bitcoin" "regtest"}/lightning-rpc";
EXECMODE = "production";
PROTOCOL = "https";
RPCCOMMANDS = ["*"];
} // cfg.extraConfig));
in {
inherit options;
config = mkIf cfg.enable {
services.clightning.enable = true;
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${clightning.user} ${cfg.group} - -"
];
systemd.services.clightning-rest = mkIf cfg.enable {
wantedBy = [ "multi-user.target" ];
wants = [ "clightning.service" ];
after = [ "clightning.service" ];
path = [ pkgs.openssl ];
environment.CL_REST_STATE_DIR = cfg.dataDir;
preStart = ''
ln -sfn ${configFile} cl-rest-config.json
'';
postStart = ''
while [[ ! -e '${cfg.dataDir}/certs/access.macaroon' ]]; do
sleep 0.1
done
'';
serviceConfig = nbLib.defaultHardening // {
# clightning-rest reads the config file from the working directory
WorkingDirectory = cfg.dataDir;
ExecStart = "${nbPkgs.clightning-rest}/bin/cl-rest";
# Show "clightning-rest" instead of "node" in the journal
SyslogIdentifier = "clightning-rest";
User = clightning.user;
Restart = "on-failure";
RestartSec = "10s";
ReadWritePaths = [ cfg.dataDir ];
inherit (nbLib.allowNetlink) RestrictAddressFamilies;
} // nbLib.allowedIPAddresses cfg.tor.enforce
// nbLib.nodejs;
};
};
}
-208
View File
@@ -1,208 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.clightning = {
enable = mkEnableOption "clightning, a Lightning Network implementation in C";
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen for peer connections.";
};
port = mkOption {
type = types.port;
default = 9735;
description = "Port to listen for peer connections.";
};
proxy = mkOption {
type = types.nullOr types.str;
default = if cfg.tor.proxy then config.nix-bitcoin.torClientAddressWithPort else null;
description = ''
Socks proxy for connecting to Tor nodes (or for all connections if option always-use-proxy is set).
'';
};
always-use-proxy = mkOption {
type = types.bool;
default = cfg.tor.proxy;
description = ''
Always use the proxy, even to connect to normal IP addresses.
You can still connect to Unix domain sockets manually.
This also disables all DNS lookups, to avoid leaking address information.
'';
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/clightning";
description = "The data directory for clightning.";
};
networkDir = mkOption {
readOnly = true;
default = "${cfg.dataDir}/${network}";
description = "The network data directory.";
};
wallet = mkOption {
type = types.nullOr types.str;
default = null;
example = "sqlite3:///var/lib/clightning/bitcoin/lightningd.sqlite3";
description = ''
Wallet data scheme (sqlite3 or postgres) and location/connection
parameters, as fully qualified data source name.
'';
};
useBcliPlugin = mkOption {
type = types.bool;
default = true;
description = ''
Use bitcoind (via plugin `bcli`) for getting block data.
This option is disabled by plugins that use other sources for
fetching block data, like `trustedcoin`.
'';
};
extraConfig = mkOption {
type = types.lines;
default = "";
example = ''
alias=mynode
'';
description = ''
Extra lines appended to the configuration file.
See all available options at
https://github.com/ElementsProject/lightning/blob/master/doc/lightningd-config.5.md
or by running {command}`lightningd --help`.
'';
};
user = mkOption {
type = types.str;
default = "clightning";
description = "The user as which to run clightning.";
};
group = mkOption {
type = types.str;
default = cfg.user;
description = "The group as which to run clightning.";
};
package = mkOption {
type = types.package;
default = nbPkgs.clightning;
defaultText = "config.nix-bitcoin.pkgs.clightning";
description = "The package providing clightning binaries.";
};
cli = mkOption {
readOnly = true;
default = pkgs.writers.writeBashBin "lightning-cli" ''
${cfg.package}/bin/lightning-cli --lightning-dir='${cfg.dataDir}' "$@"
'';
defaultText = "(See source)";
description = "Binary to connect with the clightning instance.";
};
getPublicAddressCmd = mkOption {
type = types.str;
default = "";
description = ''
Bash expression which outputs the public service address to announce to peers.
If left empty, no address is announced.
'';
};
tor = nbLib.tor;
};
cfg = config.services.clightning;
nbLib = config.nix-bitcoin.lib;
nbPkgs = config.nix-bitcoin.pkgs;
inherit (config.services) bitcoind;
network = bitcoind.makeNetworkName "bitcoin" "regtest";
configFile = pkgs.writeText "config" ''
network=${network}
${optionalString (!cfg.useBcliPlugin) "disable-plugin=bcli"}
${optionalString (cfg.proxy != null) "proxy=${cfg.proxy}"}
always-use-proxy=${boolToString cfg.always-use-proxy}
bind-addr=${cfg.address}:${toString cfg.port}
bitcoin-rpcconnect=${nbLib.address bitcoind.rpc.address}
bitcoin-rpcport=${toString bitcoind.rpc.port}
bitcoin-rpcuser=${bitcoind.rpc.users.public.name}
rpc-file-mode=0660
log-timestamps=false
${optionalString (cfg.wallet != null) "wallet=${cfg.wallet}"}
${ # TODO-EXTERNAL: When updating from a version of clightning before 22.11
# to version 22.11.1, then the database upgrade needs to be allowed
# explicitly. Remove this when it's unlikely that this module is used
# with a clightning version 22.11.1 package.
optionalString (cfg.package.version == "22.11.1") "database-upgrade=true"}
${cfg.extraConfig}
'';
# If a public clightning onion service is enabled, use the onion port as the public port
publicPort = if (config.nix-bitcoin.onionServices.clightning.enable or false)
&& config.nix-bitcoin.onionServices.clightning.public
then
(builtins.elemAt config.services.tor.relay.onionServices.clightning.map 0).port
else
cfg.port;
in {
inherit options;
config = mkIf cfg.enable {
services.bitcoind = {
enable = true;
# Increase rpc thread count due to reports that lightning implementations fail
# under high bitcoind rpc load
rpc.threads = 16;
};
environment.systemPackages = [ cfg.package (hiPrio cfg.cli) ];
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group} - -"
];
systemd.services.clightning = {
path = [ bitcoind.package ];
wantedBy = [ "multi-user.target" ];
requires = [ "bitcoind.service" ];
after = [ "bitcoind.service" "nix-bitcoin-secrets.target" ];
preStart = ''
# Remove an existing socket so that `postStart` can detect when when a new
# socket has been created and clightning is ready to accept RPC connections.
# This will no longer be needed when clightning supports systemd startup notifications.
rm -f ${cfg.networkDir}/lightning-rpc
umask u=rw,g=r,o=
{
cat ${configFile}
echo "bitcoin-rpcpassword=$(cat ${config.nix-bitcoin.secretsDir}/bitcoin-rpcpassword-public)"
${optionalString (cfg.getPublicAddressCmd != "") ''
echo "announce-addr=$(${cfg.getPublicAddressCmd}):${toString publicPort}"
''}
} > '${cfg.dataDir}/config'
'';
serviceConfig = nbLib.defaultHardening // {
ExecStart = "${cfg.package}/bin/lightningd --lightning-dir=${cfg.dataDir}";
User = cfg.user;
Restart = "on-failure";
RestartSec = "10s";
ReadWritePaths = [ cfg.dataDir ];
# DB upgrades or recovery after a crash can take a while
TimeoutStartSec = "10m";
} // nbLib.allowedIPAddresses cfg.tor.enforce;
# Wait until the rpc socket appears
postStart = ''
while [[ ! -e ${cfg.networkDir}/lightning-rpc ]]; do
sleep 0.1
done
# Needed to enable lightning-cli for users with group 'clightning'
chmod g+x ${cfg.networkDir}
'';
};
users.users.${cfg.user} = {
isSystemUser = true;
group = cfg.group;
extraGroups = [ "bitcoinrpc-public" ];
};
users.groups.${cfg.group} = {};
nix-bitcoin.operator.groups = [ cfg.group ];
};
}
-24
View File
@@ -1,24 +0,0 @@
{ lib, ... }:
{
nix-bitcoin = {
secretsDir = "/var/src/secrets";
setupSecrets = true;
};
environment.variables.NIX_PATH = lib.mkForce "/var/src";
# The file syncing step in krops resets the secrets file permissions.
# So force `setup-secrets.service` to restart on deployment.
# Stop it at activation start so that it gets restarted at the end.
system.activationScripts.nixBitcoinStopSetupSecrets = ''
${/* Skip this step if systemd is not running, i.e. when booting or in nixos-install */ ""}
if [[ -e /run/systemd/system ]]; then
if ! output=$(/run/current-system/systemd/bin/systemctl stop setup-secrets.service --no-block 2>&1); then
# Ignore if the unit is not loaded, which can happen on the first deployment
if [[ $output != *setup-secrets.service\ not\ loaded* ]]; then
echo "$output"
false
fi
fi
fi
'';
}
-27
View File
@@ -1,27 +0,0 @@
{ config, ... }:
{
nix-bitcoin.secretsSetupMethod = "nixops";
deployment.keys = builtins.mapAttrs (n: v: {
keyFile = "${config.nix-bitcoin.deployment.secretsDir}/${n}";
destDir = config.nix-bitcoin.secretsDir;
inherit (v) user group permissions;
}) config.nix-bitcoin.secrets;
# nixops makes the secrets directory accessible only for users with group 'key'.
# For compatibility with other deployment methods besides nixops, we forego the
# use of the 'key' group and make the secrets dir world-readable instead.
# This is safe because all containing files have their specific private
# permissions set.
systemd.services.allowSecretsDirAccess = {
requires = [ "keys.target" ];
after = [ "keys.target" ];
script = "chmod o+x ${config.nix-bitcoin.secretsDir}";
serviceConfig.Type = "oneshot";
};
systemd.targets.nix-bitcoin-secrets = {
requires = [ "allowSecretsDirAccess.service" ];
after = [ "allowSecretsDirAccess.service" ];
};
}
+1 -1
View File
@@ -77,7 +77,7 @@ in {
# electrs only uses the working directory for reading electrs.toml # electrs only uses the working directory for reading electrs.toml
WorkingDirectory = cfg.dataDir; WorkingDirectory = cfg.dataDir;
ExecStart = '' ExecStart = ''
${config.nix-bitcoin.pkgs.electrs}/bin/electrs \ ${pkgs.electrs}/bin/electrs \
--log-filters=INFO \ --log-filters=INFO \
--network=${bitcoind.makeNetworkName "bitcoin" "regtest"} \ --network=${bitcoind.makeNetworkName "bitcoin" "regtest"} \
--db-dir='${cfg.dataDir}' \ --db-dir='${cfg.dataDir}' \
-140
View File
@@ -1,140 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.fulcrum = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Enable fulcrum, an Electrum server implemented in C++.
Compared to electrs, fulcrum has a 3x larger database size but
can serve arbitrary address queries instantly.
fulcrum also enables `txindex` in bitcoind (this is a requirement),
which increases the bitcoind datadir size by 8% of the `blocks` size.
This module disables peering (a distributed list of electrum servers that can
be queried by clients), but you can manually enable it via option
{option}`extraConfig`.
'';
};
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen for RPC connections.";
};
port = mkOption {
type = types.port;
default = 50001;
description = "Port to listen for RPC connections.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/fulcrum";
description = "The data directory for fulcrum.";
};
extraConfig = mkOption {
type = types.lines;
default = "";
example = ''
peering = true
'';
description = ''
Extra lines appended to the configuration file.
See all available options at
https://github.com/cculianu/Fulcrum/blob/master/doc/fulcrum-example-config.conf
'';
};
user = mkOption {
type = types.str;
default = "fulcrum";
description = "The user as which to run fulcrum.";
};
group = mkOption {
type = types.str;
default = cfg.user;
description = "The group as which to run fulcrum.";
};
tor.enforce = nbLib.tor.enforce;
};
cfg = config.services.fulcrum;
nbLib = config.nix-bitcoin.lib;
secretsDir = config.nix-bitcoin.secretsDir;
bitcoind = config.services.bitcoind;
configFile = builtins.toFile "fulcrum.conf" ''
datadir = ${cfg.dataDir}
tcp = ${cfg.address}:${toString cfg.port}
bitcoind = ${nbLib.addressWithPort bitcoind.rpc.address bitcoind.rpc.port}
rpcuser = ${bitcoind.rpc.users.public.name}
# Disable logging timestamps
ts-format = none
peering = false
${cfg.extraConfig}
'';
in {
inherit options;
config = mkIf cfg.enable {
assertions = [
{ assertion = bitcoind.prune == 0;
message = "Fulcrum does not support bitcoind pruning.";
}
{ assertion =
!(config.services ? electrs)
|| !config.services.electrs.enable
|| config.services.electrs.port != cfg.port;
message = ''
Fulcrum and Electrs can't both bind to TCP RPC port ${cfg.port}.
Change `services.electrs.port` or `services.fulcrum.port`
to a port other than ${cfg.port}.
'';
}
];
services.bitcoind = {
enable = true;
txindex = true;
};
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group} - -"
];
systemd.services.fulcrum = {
wantedBy = [ "multi-user.target" ];
wants = [ "bitcoind.service" ];
after = [ "bitcoind.service" "nix-bitcoin-secrets.target" ];
preStart = ''
{
cat ${configFile}
echo "rpcpassword = $(cat ${secretsDir}/bitcoin-rpcpassword-public)"
} > '${cfg.dataDir}/fulcrum.conf'
'';
serviceConfig = nbLib.defaultHardening // {
ExecStart = "${config.nix-bitcoin.pkgs.fulcrum}/bin/Fulcrum '${cfg.dataDir}/fulcrum.conf'";
User = cfg.user;
Group = cfg.group;
Restart = "on-failure";
RestartSec = "10s";
ReadWritePaths = cfg.dataDir;
ProcSubset = "all"; # Fulcrum requires read access to /proc/meminfo
} // nbLib.allowedIPAddresses cfg.tor.enforce;
};
users.users.${cfg.user} = {
isSystemUser = true;
group = cfg.group;
extraGroups = [ "bitcoinrpc-public" ];
};
users.groups.${cfg.group} = {};
};
}
-84
View File
@@ -1,84 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.hardware-wallets = {
ledger = mkOption {
type = types.bool;
default = false;
description = ''
If enabled, the ledger udev rules will be installed.
'';
};
trezor = mkOption {
type = types.bool;
default = false;
description = ''
If enabled, the trezor udev rules will be installed.
'';
};
group = mkOption {
type = types.str;
default = "hardware-wallets";
description = ''
Group the hardware wallet udev rules apply to.
'';
};
};
cfg = config.services.hardware-wallets;
in {
inherit options;
config = mkMerge [
(mkIf (cfg.ledger || cfg.trezor) {
assertions = [
{ assertion = (config.services.bitcoind.disablewallet == null || !config.services.bitcoind.disablewallet);
message = ''
Hardware-Wallets are not compatible with bitcoind.disablewallet.
'';
}
];
environment.systemPackages = [
config.nix-bitcoin.pkgs.hwi
# Provides lsusb for debugging
pkgs.usbutils
];
users.groups.${cfg.group} = {};
nix-bitcoin.operator.groups = [ cfg.group ];
})
(mkIf cfg.ledger {
# Ledger Nano S according to https://github.com/LedgerHQ/udev-rules/blob/master/add_udev_rules.sh
# Don't use rules from nixpkgs because we want to use our own group.
services.udev.packages = lib.singleton (pkgs.writeTextFile {
name = "ledger-udev-rules";
destination = "/etc/udev/rules.d/20-ledger.rules";
text = ''
SUBSYSTEMS=="usb", ATTRS{idVendor}=="2c97", ATTRS{idProduct}=="0001", MODE="0660", GROUP="${cfg.group}"
'';
});
})
(mkIf cfg.trezor {
environment.systemPackages = [ config.nix-bitcoin.pkgs.pyPkgs.nbPython3PackagesWithUnlockedEcdsa.trezor ];
# Don't use rules from nixpkgs because we want to use our own group.
services.udev.packages = lib.singleton (pkgs.writeTextFile {
name = "trezord-udev-rules";
destination = "/etc/udev/rules.d/52-trezor.rules";
text = ''
# TREZOR v1 (One)
SUBSYSTEM=="usb", ATTR{idVendor}=="534c", ATTR{idProduct}=="0001", MODE="0660", GROUP="${cfg.group}", TAG+="uaccess", SYMLINK+="trezor%n"
KERNEL=="hidraw*", ATTRS{idVendor}=="534c", ATTRS{idProduct}=="0001", MODE="0660", GROUP="${cfg.group}", TAG+="uaccess"
# TREZOR v2 (T)
SUBSYSTEM=="usb", ATTR{idVendor}=="1209", ATTR{idProduct}=="53c0", MODE="0660", GROUP="${cfg.group}", TAG+="uaccess", SYMLINK+="trezor%n"
SUBSYSTEM=="usb", ATTR{idVendor}=="1209", ATTR{idProduct}=="53c1", MODE="0660", GROUP="${cfg.group}", TAG+="uaccess", SYMLINK+="trezor%n"
KERNEL=="hidraw*", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="53c1", MODE="0660", GROUP="${cfg.group}", TAG+="uaccess"
'';
});
services.trezord.enable = true;
})
];
}
-133
View File
@@ -1,133 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.joinmarket-ob-watcher = {
enable = mkEnableOption "JoinMarket orderbook watcher";
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "HTTP server address.";
};
port = mkOption {
type = types.port;
default = 62601;
description = "HTTP server port.";
};
dataDir = mkOption {
readOnly = true;
default = "/var/lib/joinmarket-ob-watcher";
description = "The data directory for JoinMarket orderbook watcher.";
};
settings = mkOption {
type = with types; attrsOf anything;
example = {
LOGGING = {
console_log_level = "DEBUG";
};
};
description = ''
Joinmarket settings.
See here for possible options:
https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/v0.9.11/src/jmclient/configure.py#L98
'';
};
user = mkOption {
type = types.str;
default = "joinmarket-ob-watcher";
description = "The user as which to run JoinMarket.";
};
group = mkOption {
type = types.str;
default = cfg.user;
description = "The group as which to run JoinMarket.";
};
# This option is only used by netns-isolation.
# Tor is always enabled.
tor.enforce = nbLib.tor.enforce;
};
cfg = config.services.joinmarket-ob-watcher;
nbLib = config.nix-bitcoin.lib;
nbPkgs = config.nix-bitcoin.pkgs;
secretsDir = config.nix-bitcoin.secretsDir;
inherit (config.services) bitcoind joinmarket;
in {
inherit options;
config = mkIf cfg.enable {
services.bitcoind.rpc.users.joinmarket-ob-watcher = {
passwordHMACFromFile = true;
rpcwhitelist = bitcoind.rpc.users.public.rpcwhitelist ++ [
"listwallets"
];
};
# Joinmarket is Tor-only
services.tor = {
enable = true;
client.enable = true;
};
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group} - -"
];
services.joinmarket-ob-watcher.settings = {
BLOCKCHAIN = config.services.joinmarket.settings.BLOCKCHAIN // {
rpc_user = bitcoind.rpc.users.joinmarket-ob-watcher.name;
rpc_wallet_file = "";
};
inherit (config.services.joinmarket.settings)
"MESSAGING:onion"
"MESSAGING:server1"
"MESSAGING:server2"
"MESSAGING:server3";
};
systemd.services.joinmarket-ob-watcher = rec {
wantedBy = [ "multi-user.target" ];
requires = [ "tor.service" "bitcoind.service" ];
after = requires ++ [ "nix-bitcoin-secrets.target" ];
# The service writes to HOME/.config/matplotlib
environment.HOME = cfg.dataDir;
preStart = ''
{
cat ${builtins.toFile "joinmarket-ob-watcher.cfg" ((generators.toINI {}) cfg.settings)}
echo
echo '[BLOCKCHAIN]'
echo "rpc_password = $(cat ${secretsDir}/bitcoin-rpcpassword-joinmarket-ob-watcher)"
} > '${cfg.dataDir}/joinmarket.cfg'
'';
serviceConfig = nbLib.defaultHardening // rec {
StateDirectory = "joinmarket-ob-watcher";
StateDirectoryMode = "770";
WorkingDirectory = cfg.dataDir; # The service creates dir 'logs' in the working dir
User = cfg.user;
ExecStart = ''
${nbPkgs.joinmarket}/bin/jm-ob-watcher --datadir=${cfg.dataDir} \
--host=${cfg.address} --port=${toString cfg.port}
'';
SystemCallFilter = nbLib.defaultHardening.SystemCallFilter ++ [ "mbind" ] ;
Restart = "on-failure";
RestartSec = "10s";
} // nbLib.allowedIPAddresses cfg.tor.enforce;
};
users.users.${cfg.user} = {
isSystemUser = true;
group = cfg.group;
home = cfg.dataDir;
};
users.groups.${cfg.group} = {};
nix-bitcoin.secrets = {
bitcoin-rpcpassword-joinmarket-ob-watcher.user = cfg.user;
bitcoin-HMAC-joinmarket-ob-watcher.user = bitcoind.user;
};
nix-bitcoin.generateSecretsCmds.joinmarket-ob-watcher = ''
makeBitcoinRPCPassword joinmarket-ob-watcher
'';
};
}
-398
View File
@@ -1,398 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.joinmarket = {
enable = mkEnableOption "JoinMarket, a Bitcoin CoinJoin implementation";
payjoinAddress = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
The address where payjoin onion connections are forwarded to.
This address is never used directly, it only serves as the internal endpoint
for the payjoin onion service.
The onion service is automatically setup by joinmarket and accepts
connections at port 80.
'';
};
payjoinPort = mkOption {
type = types.port;
default = 64180; # A random private port
description = "The port corresponding to option {option}`payjoinAddress`.";
};
messagingAddress = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
The address where messaging onion connections are forwarded to.
This address is never used directly, it only serves as the internal endpoint
for the messaging onion service.
The onion service is automatically setup by joinmarket.
'';
};
messagingPort = mkOption {
type = types.port;
default = 64181; # payjoinPort + 1
description = "The port corresponding to option {option}`messagingAddress`.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/joinmarket";
description = "The data directory for JoinMarket.";
};
rpcWalletFile = mkOption {
type = types.nullOr types.nonEmptyStr;
default = "jm_wallet";
description = ''
Name of the watch-only bitcoind wallet the JoinMarket addresses are imported to.
'';
};
settings = mkOption {
type = with types; attrsOf anything;
example = {
POLICY = {
merge_algorithm = "gradual";
tx_fees = 5;
};
LOGGING = {
console_log_level = "DEBUG";
};
};
description = ''
Joinmarket settings.
See here for possible options:
https://raw.githubusercontent.com/JoinMarket-Org/joinmarket-clientserver/master/src/jmclient/configure.py#:~:text=defaultconfig%20=
If your web browser does not support text fragment URLs, you can can manually
search for string `defaultconfig =` to jump to the correct location.
'';
};
user = mkOption {
type = types.str;
default = "joinmarket";
description = "The user as which to run JoinMarket.";
};
group = mkOption {
type = types.str;
default = cfg.user;
description = "The group as which to run JoinMarket.";
};
cli = mkOption {
default = cli;
defaultText = "(See source)";
};
# This option is only used by netns-isolation.
# Tor is always enabled.
tor.enforce = nbLib.tor.enforce;
inherit (nbLib) cliExec;
yieldgenerator = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Enable the JoinMarket yield generator bot.
Documentation: https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/master/docs/YIELDGENERATOR.md
'';
};
ordertype = mkOption {
type = types.enum [ "reloffer" "absoffer" ];
default = "reloffer";
description = ''
Which fee type to actually use.
'';
};
cjfee_a = mkOption {
type = types.ints.unsigned;
default = 500;
description = ''
Absolute offer fee you wish to receive for coinjoins (cj) in Satoshis.
'';
};
cjfee_r = mkOption {
type = types.float;
default = 0.00002;
description = ''
Relative offer fee you wish to receive based on a cj's amount.
'';
};
cjfee_factor = mkOption {
type = types.float;
default = 0.1;
description = ''
Variance around the average cj fee.
'';
};
txfee_contribution_factor = mkOption {
type = types.float;
default = 0.3;
description = ''
Variance around the average tx fee.
'';
};
minsize = mkOption {
type = types.ints.unsigned;
default = 100000;
description = ''
Minimum size of your cj offer in Satoshis. Lower cj amounts will be disregarded.
'';
};
size_factor = mkOption {
type = types.float;
default = 0.1;
description = ''
Variance around all offer sizes.
'';
};
};
};
cfg = config.services.joinmarket;
nbLib = config.nix-bitcoin.lib;
nbPkgs = config.nix-bitcoin.pkgs;
secretsDir = config.nix-bitcoin.secretsDir;
runAsUser = config.nix-bitcoin.runAsUserCmd;
inherit (config.services) bitcoind;
torAddress = config.services.tor.client.socksListenAddress;
socks5Settings = {
socks5 = true;
socks5_host = torAddress.addr;
socks5_port = torAddress.port;
};
# The jm scripts create a 'logs' dir in the working dir,
# so run them inside dataDir.
cli = pkgs.runCommand "joinmarket-cli" {} ''
mkdir -p "$out/bin"
jm=${nbPkgs.joinmarket}/bin
cd "$jm"
for bin in jm-*; do
{
echo "#!${pkgs.bash}/bin/bash";
echo "cd '${cfg.dataDir}' && ${cfg.cliExec} ${runAsUser} ${cfg.user} "$jm/$bin" --datadir='${cfg.dataDir}' \"\$@\"";
} > "$out/bin/$bin"
done
chmod -R +x "$out/bin"
'';
in {
inherit options;
config = mkMerge [
{
services.joinmarket.settings = {
DAEMON = {
no_daemon = 0;
daemon_port = 27183;
daemon_host = "127.0.0.1";
};
BLOCKCHAIN = {
blockchain_source = bitcoind.makeNetworkName "bitcoin-rpc" "regtest";
network = bitcoind.makeNetworkName "mainnet" "testnet";
rpc_host = nbLib.address bitcoind.rpc.address;
rpc_port = bitcoind.rpc.port;
rpc_user = bitcoind.rpc.users.privileged.name;
rpc_wallet_file = if cfg.rpcWalletFile == null then "" else cfg.rpcWalletFile;
};
LOGGING = {
color = false;
};
PAYJOIN = {
onion_socks5_host = torAddress.addr;
onion_socks5_port = torAddress.port;
tor_control_host = "unix:/run/tor/control";
onion_serving_host = cfg.payjoinAddress;
onion_serving_port = cfg.payjoinPort;
hidden_service_ssl = false;
};
YIELDGENERATOR = removeAttrs cfg.yieldgenerator [
"enable"
# TODO: This is only needed when ./obsolete-options.nix is imported
"txfee"
];
# Messaging settings have to be fully specified because joinmarket doesn't
# provide default messaging settings.
# (`jmclient/configure.py` actually does contain default messaging settings, but
# they are removed via fn `_remove_unwanted_default_settings`)
"MESSAGING:onion" = socks5Settings // {
type = "onion";
tor_control_host = "unix:/run/tor/control";
# Required option, but ignored because `tor_control_host` is a unix socket
tor_control_port = 9051;
onion_serving_host = cfg.messagingAddress;
onion_serving_port = cfg.messagingPort;
hidden_service_dir = "";
directory_nodes = "g3hv4uynnmynqqq2mchf3fcm3yd46kfzmcdogejuckgwknwyq5ya6iad.onion:5222,3kxw6lf5vf6y26emzwgibzhrzhmhqiw6ekrek3nqfjjmhwznb2moonad.onion:5222,bqlpq6ak24mwvuixixitift4yu42nxchlilrcqwk2ugn45tdclg42qid.onion:5222";
};
# irc.darkscience.net
"MESSAGING:server1" = socks5Settings // {
host = "darkirc6tqgpnwd3blln3yfv5ckl47eg7llfxkmtovrv7c7iwohhb6ad.onion";
channel = "joinmarket-pit";
port = 6697;
usessl = true;
};
# ilita
"MESSAGING:server2" = socks5Settings // {
host = "ilitafrzzgxymv6umx2ux7kbz3imyeko6cnqkvy4nisjjj4qpqkrptid.onion";
channel = "joinmarket-pit";
port = 6667;
usessl = false;
};
# irc.hackint.org
"MESSAGING:server3" = socks5Settings // {
host = "ncwkrwxpq2ikcngxq3dy2xctuheniggtqeibvgofixpzvrwpa77tozqd.onion";
channel = "joinmarket-pit";
port = 6667;
usessl = false;
};
};
}
(mkIf cfg.enable {
assertions = [
{
assertion = lib.versionOlder bitcoind.package.version "30";
message = ''
Joinmarket is not compatible with bitcoind >= 30.
(https://github.com/JoinMarket-Org/joinmarket-clientserver/pull/1775)
To fix this, add the following to your config:
services.bitcoind.package = config.nix-bitcoin.pkgs.bitcoind_29;
'';
}
];
services.bitcoind = {
enable = true;
disablewallet = false;
# TODO-EXTERNAL: remove when joinmarket supports descriptor wallets
# (https://github.com/JoinMarket-Org/joinmarket-clientserver/issues/1571).
extraConfig = ''
deprecatedrpc=create_bdb
'';
};
# Joinmarket is Tor-only
services.tor = {
enable = true;
client.enable = true;
# Needed for payjoin onion service creation
controlSocket.enable = true;
};
environment.systemPackages = [
(hiPrio cfg.cli)
];
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group} - -"
];
systemd.services.joinmarket = {
wantedBy = [ "multi-user.target" ];
requires = [ "bitcoind.service" ];
after = [ "bitcoind.service" "nix-bitcoin-secrets.target" ];
preStart = ''
{
cat ${builtins.toFile "joinmarket.cfg" ((generators.toINI {}) cfg.settings)}
echo
echo '[BLOCKCHAIN]'
echo "rpc_password = $(cat ${secretsDir}/bitcoin-rpcpassword-privileged)"
} > '${cfg.dataDir}/joinmarket.cfg'
'';
postStart = ''
walletname=wallet.jmdat
wallet="${cfg.dataDir}/wallets/$walletname"
if [[ ! -f $wallet ]]; then
${optionalString (cfg.rpcWalletFile != null) ''
echo "Create watch-only wallet ${cfg.rpcWalletFile}"
if ! output=$(${bitcoind.cli}/bin/bitcoin-cli -named createwallet \
wallet_name="${cfg.rpcWalletFile}" \
descriptors=false \
${optionalString (!bitcoind.regtest) "disable_private_keys=true"} 2>&1
); then
# Ignore error if bitcoind wallet already exists
if [[ $output != *"already exists"* ]]; then
echo "$output"
exit 1
fi
fi
''}
# Restore wallet from seed if available
seed=()
if [[ -e jm-wallet-seed ]]; then
seed=(--recovery-seed-file jm-wallet-seed)
fi
cd "${cfg.dataDir}"
# Strip trailing newline from password file
if ! tr -d '\n' < '${secretsDir}/jm-wallet-password' \
| ${nbPkgs.joinmarket}/bin/jm-genwallet \
--datadir="${cfg.dataDir}" --wallet-password-stdin "''${seed[@]}" "$walletname" \
| (if ((! ''${#seed[@]})); then
umask u=r,go=
grep -ohP '(?<=recovery_seed:).*' > jm-wallet-seed
else
cat > /dev/null
fi); then
echo "wallet creation failed"
rm -f "$wallet" jm-wallet-seed
exit 1
fi
fi
'';
serviceConfig = nbLib.defaultHardening // {
ExecStart = "${nbPkgs.joinmarket}/bin/joinmarketd";
WorkingDirectory = cfg.dataDir; # The service creates 'commitmentlist' in the working dir
User = cfg.user;
Restart = "on-failure";
RestartSec = "10s";
ReadWritePaths = [ cfg.dataDir ];
} // nbLib.allowedIPAddresses cfg.tor.enforce;
};
users.users.${cfg.user} = {
isSystemUser = true;
group = cfg.group;
home = cfg.dataDir;
# Allow access to the tor control socket, needed for payjoin onion service creation
extraGroups = [ "tor" "bitcoin" ];
};
users.groups.${cfg.group} = {};
nix-bitcoin.operator = {
groups = [ cfg.group ];
allowRunAsUsers = [ cfg.user ];
};
nix-bitcoin.secrets.jm-wallet-password.user = cfg.user;
nix-bitcoin.generateSecretsCmds.joinmarket = ''
makePasswordSecret jm-wallet-password
'';
})
(mkIf (cfg.enable && cfg.yieldgenerator.enable) {
systemd.services.joinmarket-yieldgenerator = {
wantedBy = [ "joinmarket.service" ];
requires = [ "joinmarket.service" ];
after = [ "joinmarket.service" "nix-bitcoin-secrets.target" ];
script = ''
tr -d "\n" <"${secretsDir}/jm-wallet-password" \
| ${nbPkgs.joinmarket}/bin/jm-yg-privacyenhanced --datadir='${cfg.dataDir}' \
--wallet-password-stdin wallet.jmdat
'';
serviceConfig = nbLib.defaultHardening // rec {
WorkingDirectory = cfg.dataDir; # The service creates dir 'logs' in the working dir
# Show "joinmarket-yieldgenerator" instead of "bash" in the journal.
# The start script has to run alongside the main process
# because it provides the wallet password via stdin to the main process
SyslogIdentifier = "joinmarket-yieldgenerator";
User = cfg.user;
ReadWritePaths = [ cfg.dataDir ];
} // nbLib.allowTor;
};
})
];
}
-147
View File
@@ -1,147 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.lightning-loop = {
enable = mkEnableOption "Lightning Loop, a non-custodial off/on chain bridge";
rpcAddress = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen for gRPC connections.";
};
rpcPort = mkOption {
type = types.port;
default = 11010;
description = "Port to listen for gRPC connections.";
};
restAddress = mkOption {
type = types.str;
default = cfg.rpcAddress;
description = "Address to listen for REST connections.";
};
restPort = mkOption {
type = types.port;
default = 8081;
description = "Port to listen for REST connections.";
};
package = mkOption {
type = types.package;
default = config.nix-bitcoin.pkgs.lightning-loop;
defaultText = "config.nix-bitcoin.pkgs.lightning-loop";
description = "The package providing lightning-loop binaries.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/lightning-loop";
description = "The data directory for lightning-loop.";
};
proxy = mkOption {
type = types.nullOr types.str;
default = if cfg.tor.proxy then config.nix-bitcoin.torClientAddressWithPort else null;
description = "`host:port` of SOCKS5 proxy for connnecting to the loop server.";
};
certificate = {
extraIPs = mkOption {
type = with types; listOf str;
default = [];
example = [ "60.100.0.1" ];
description = ''
Extra `subjectAltName` IPs added to the certificate.
This works the same as loop option {option}`tlsextraip`.
'';
};
extraDomains = mkOption {
type = with types; listOf str;
default = [];
example = [ "example.com" ];
description = ''
Extra `subjectAltName` domain names added to the certificate.
This works the same as loop option {option}`tlsextradomain`.
'';
};
};
extraConfig = mkOption {
type = types.lines;
default = "";
example = ''
debuglevel=trace
'';
description = ''
Extra lines appended to the configuration file.
See here for all available options:
https://github.com/lightninglabs/loop/blob/11ab596080e9d36f1df43edbeba0702b25aa7457/loopd/config.go#L119
'';
};
cli = mkOption {
default = pkgs.writers.writeBashBin "loop" ''
${cfg.package}/bin/loop \
--rpcserver ${nbLib.addressWithPort cfg.rpcAddress cfg.rpcPort} \
--macaroonpath '${cfg.dataDir}/${network}/loop.macaroon' \
--tlscertpath '${secretsDir}/loop-cert' "$@"
'';
defaultText = "(See source)";
description = "Binary to connect with the lightning-loop instance.";
};
tor = nbLib.tor;
};
cfg = config.services.lightning-loop;
nbLib = config.nix-bitcoin.lib;
secretsDir = config.nix-bitcoin.secretsDir;
lnd = config.services.lnd;
network = config.services.bitcoind.network;
configFile = builtins.toFile "loop.conf" ''
datadir=${cfg.dataDir}
network=${network}
rpclisten=${cfg.rpcAddress}:${toString cfg.rpcPort}
restlisten=${cfg.restAddress}:${toString cfg.restPort}
logdir=${cfg.dataDir}/logs
tlscertpath=${secretsDir}/loop-cert
tlskeypath=${secretsDir}/loop-key
lnd.host=${nbLib.addressWithPort lnd.rpcAddress lnd.rpcPort}
lnd.macaroonpath=${lnd.networkDir}/admin.macaroon
lnd.tlspath=${lnd.certPath}
${optionalString (cfg.proxy != null) "server.proxy=${cfg.proxy}"}
${cfg.extraConfig}
'';
in {
inherit options;
config = mkIf cfg.enable {
services.lnd.enable = true;
environment.systemPackages = [ cfg.package (hiPrio cfg.cli) ];
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${lnd.user} ${lnd.group} - -"
];
services.lightning-loop.certificate.extraIPs = mkIf (cfg.rpcAddress != "127.0.0.1") [ "${cfg.rpcAddress}" ];
systemd.services.lightning-loop = {
wantedBy = [ "multi-user.target" ];
requires = [ "lnd.service" ];
after = [ "lnd.service" "nix-bitcoin-secrets.target" ];
serviceConfig = nbLib.defaultHardening // {
ExecStart = "${cfg.package}/bin/loopd --configfile=${configFile}";
User = lnd.user;
Restart = "on-failure";
RestartSec = "10s";
ReadWritePaths = [ cfg.dataDir ];
} // nbLib.allowedIPAddresses cfg.tor.enforce;
};
nix-bitcoin.secrets = {
loop-key.user = lnd.user;
loop-cert.user = lnd.user;
};
nix-bitcoin.generateSecretsCmds.lightning-loop = ''
makeCert loop '${nbLib.mkCertExtraAltNames cfg.certificate}'
'';
};
}
-113
View File
@@ -1,113 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.lightning-pool = {
enable = mkEnableOption "Lightning Pool, a marketplace for inbound lightning liquidity ";
rpcAddress = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen for gRPC connections.";
};
rpcPort = mkOption {
type = types.port;
default = 12010;
description = "Port to listen for gRPC connections.";
};
restAddress = mkOption {
type = types.str;
default = cfg.rpcAddress;
description = "Address to listen for REST connections.";
};
restPort = mkOption {
type = types.port;
default = 8281;
description = "Port to listen for REST connections.";
};
package = mkOption {
type = types.package;
default = config.nix-bitcoin.pkgs.lightning-pool;
defaultText = "config.nix-bitcoin.pkgs.lightning-pool";
description = "The package providing lightning-pool binaries.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/lightning-pool";
description = "The data directory for lightning-pool.";
};
proxy = mkOption {
type = types.nullOr types.str;
default = if cfg.tor.proxy then config.nix-bitcoin.torClientAddressWithPort else null;
description = "host:port of SOCKS5 proxy for connnecting to the pool auction server.";
};
extraConfig = mkOption {
type = types.lines;
default = "";
example = ''
debuglevel=trace
'';
description = "Extra lines appended to the configuration file.";
};
cli = mkOption {
default = pkgs.writers.writeBashBin "pool" ''
exec ${cfg.package}/bin/pool \
--rpcserver ${nbLib.addressWithPort cfg.rpcAddress cfg.rpcPort} \
--network ${network} \
--basedir '${cfg.dataDir}' "$@"
'';
defaultText = "(See source)";
description = "Binary to connect with the lightning-pool instance.";
};
tor = nbLib.tor;
};
cfg = config.services.lightning-pool;
nbLib = config.nix-bitcoin.lib;
lnd = config.services.lnd;
network = config.services.bitcoind.network;
configFile = builtins.toFile "pool.conf" ''
rpclisten=${cfg.rpcAddress}:${toString cfg.rpcPort}
restlisten=${cfg.restAddress}:${toString cfg.restPort}
${optionalString (cfg.proxy != null) "proxy=${cfg.proxy}"}
lnd.host=${lnd.rpcAddress}:${toString lnd.rpcPort}
lnd.macaroondir=${lnd.networkDir}
lnd.tlspath=${lnd.certPath}
${cfg.extraConfig}
'';
in {
inherit options;
config = mkIf cfg.enable {
services.lnd.enable = true;
environment.systemPackages = [ cfg.package (hiPrio cfg.cli) ];
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 lnd lnd - -"
];
systemd.services.lightning-pool = {
wantedBy = [ "multi-user.target" ];
requires = [ "lnd.service" ];
after = [ "lnd.service" ];
preStart = ''
mkdir -p '${cfg.dataDir}/${network}'
ln -sfn ${configFile} '${cfg.dataDir}/${network}/poold.conf'
'';
serviceConfig = nbLib.defaultHardening // {
# TODO: temporary sleep to prevent race condition
ExecStartPre = "${pkgs.coreutils}/bin/sleep 5";
ExecStart = "${cfg.package}/bin/poold --basedir='${cfg.dataDir}' --network=${network}";
User = "lnd";
Restart = "on-failure";
RestartSec = "10s";
ReadWritePaths = [ cfg.dataDir ];
} // (nbLib.allowedIPAddresses cfg.tor.enforce)
// nbLib.allowNetlink; # required by gRPC-Go
};
};
}
-294
View File
@@ -1,294 +0,0 @@
{ config, pkgs, lib, ... }:
with lib;
let
options = {
services.liquidd = {
enable = mkEnableOption "Liquid Bitcoin sidechain daemon";
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen for peer connections.";
};
port = mkOption {
type = types.port;
default = 7042;
description = "Override the default port on which to listen for connections.";
};
onionPort = mkOption {
type = types.nullOr types.port;
# When the liquidd onion service is enabled, add an onion-tagged socket
# to distinguish local connections from Tor connections
default = if (config.nix-bitcoin.onionServices.liquidd.enable or false) then 7043 else null;
description = ''
Port to listen for Tor peer connections.
If set, inbound connections to this port are tagged as onion peers.
'';
};
listen = mkOption {
type = types.bool;
default = false;
description = ''
Listen for peer connections at `address:port`
and `address:onionPort` (if {option}`onionPort` is set).
'';
};
listenWhitelisted = mkOption {
type = types.bool;
default = false;
description = ''
Listen for peer connections at `address:whitelistedPort`.
Peers connected through this socket are automatically whitelisted.
'';
};
whitelistedPort = mkOption {
type = types.port;
default = 7044;
description = "See {option}`listenWhitelisted`.";
};
extraConfig = mkOption {
type = types.lines;
default = "";
example = ''
par=16
rpcthreads=16
logips=1
'';
description = "Extra lines appended to {file}`elements.conf`.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/liquidd";
description = "The data directory for liquidd.";
};
rpc = {
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Address to listen for JSON-RPC connections.";
};
port = mkOption {
type = types.port;
default = 7041;
description = "Port to listen for JSON-RPC connections.";
};
users = mkOption {
default = {};
example = {
alice.passwordHMAC = "f7efda5c189b999524f151318c0c86$d5b51b3beffbc02b724e5d095828e0bc8b2456e9ac8757ae3211a5d9b16a22ae";
bob.passwordHMAC = "b2dd077cb54591a2f3139e69a897ac$4e71f08d48b4347cf8eff3815c0e25ae2e9a4340474079f55705f40574f4ec99";
};
type = with types; attrsOf (submodule rpcUserOpts);
description = ''
RPC user information for JSON-RPC connections.
'';
};
};
rpcallowip = mkOption {
type = types.listOf types.str;
default = [ "127.0.0.1" ];
description = ''
Allow JSON-RPC connections from specified source.
'';
};
rpcuser = mkOption {
type = types.str;
default = "liquidrpc";
description = "Username for JSON-RPC connections";
};
proxy = mkOption {
type = types.nullOr types.str;
default = if cfg.tor.proxy then config.nix-bitcoin.torClientAddressWithPort else null;
description = "Connect through SOCKS5 proxy";
};
dbCache = mkOption {
type = types.nullOr (types.ints.between 4 16384);
default = null;
example = 4000;
description = "Override the default database cache size in megabytes.";
};
prune = mkOption {
type = types.nullOr (types.coercedTo
(types.enum [ "disable" "manual" ])
(x: if x == "disable" then 0 else 1)
types.ints.unsigned
);
default = null;
example = 10000;
description = ''
Reduce storage requirements by enabling pruning (deleting) of old
blocks. This allows the pruneblockchain RPC to be called to delete
specific blocks, and enables automatic pruning of old blocks if a
target size in MiB is provided. This mode is incompatible with -txindex
and -rescan. Warning: Reverting this setting requires re-downloading
the entire blockchain. (`disable` = disable pruning blocks, `manual`
= allow manual pruning via RPC, >=550 = automatically prune block files
to stay under the specified target size in MiB)
'';
};
validatepegin = mkOption {
type = types.nullOr types.bool;
default = null;
description = ''
Validate pegin claims. All functionaries must run this.
'';
};
user = mkOption {
type = types.str;
default = "liquid";
description = "The user as which to run liquidd.";
};
group = mkOption {
type = types.str;
default = cfg.user;
description = "The group as which to run liquidd.";
};
cli = mkOption {
readOnly = true;
default = pkgs.writers.writeBashBin "elements-cli" ''
${nbPkgs.elementsd}/bin/elements-cli -datadir='${cfg.dataDir}' "$@"
'';
defaultText = "(See source)";
description = "Binary to connect with the liquidd instance.";
};
swapCli = mkOption {
default = pkgs.writers.writeBashBin "liquidswap-cli" ''
${nbPkgs.liquid-swap}/bin/liquidswap-cli -c '${cfg.dataDir}/elements.conf' "$@"
'';
defaultText = "(See source)";
description = "Binary for managing liquid swaps.";
};
tor = nbLib.tor;
};
};
cfg = config.services.liquidd;
nbLib = config.nix-bitcoin.lib;
nbPkgs = config.nix-bitcoin.pkgs;
secretsDir = config.nix-bitcoin.secretsDir;
bitcoind = config.services.bitcoind;
configFile = pkgs.writeText "elements.conf" ''
# We're already logging via journald
nodebuglogfile=1
startupnotify=/run/current-system/systemd/bin/systemd-notify --ready
chain=${bitcoind.makeNetworkName "liquidv1" ''
regtest
[regtest]'' # Add [regtest] config section
}
${optionalString (cfg.dbCache != null) "dbcache=${toString cfg.dbCache}"}
${optionalString (cfg.prune != null) "prune=${toString cfg.prune}"}
${optionalString (cfg.validatepegin != null) "validatepegin=${if cfg.validatepegin then "1" else "0"}"}
# Connection options
listen=${if (cfg.listen || cfg.listenWhitelisted) then "1" else "0"}
${optionalString cfg.listen
"bind=${cfg.address}:${toString cfg.port}"}
${optionalString (cfg.listen && cfg.onionPort != null)
"bind=${cfg.address}:${toString cfg.onionPort}=onion"}
${optionalString cfg.listenWhitelisted
"whitebind=${cfg.address}:${toString cfg.whitelistedPort}"}
${optionalString (cfg.proxy != null) "proxy=${cfg.proxy}"}
# RPC server options
rpcport=${toString cfg.rpc.port}
${concatMapStringsSep "\n"
(rpcUser: "rpcauth=${rpcUser.name}:${rpcUser.passwordHMAC}")
(attrValues cfg.rpc.users)
}
rpcbind=${cfg.rpc.address}
rpcconnect=${cfg.rpc.address}
${lib.concatMapStrings (rpcallowip: "rpcallowip=${rpcallowip}\n") cfg.rpcallowip}
rpcuser=${cfg.rpcuser}
mainchainrpchost=${nbLib.address bitcoind.rpc.address}
mainchainrpcport=${toString bitcoind.rpc.port}
mainchainrpcuser=${bitcoind.rpc.users.public.name}
# Extra config options (from liquidd nixos service)
${cfg.extraConfig}
'';
rpcUserOpts = { name, ... }: {
options = {
name = mkOption {
type = types.str;
example = "alice";
description = ''
Username for JSON-RPC connections.
'';
};
passwordHMAC = mkOption {
type = with types; uniq (strMatching "[0-9a-f]+\\$[0-9a-f]{64}");
example = "f7efda5c189b999524f151318c0c86$d5b51b3beffbc02b724e5d095828e0bc8b2456e9ac8757ae3211a5d9b16a22ae";
description = ''
Password HMAC-SHA-256 for JSON-RPC connections. Must be a string of the
format `<SALT-HEX>$<HMAC-HEX>`.
'';
};
};
config = {
name = mkDefault name;
};
};
in {
inherit options;
config = mkIf cfg.enable {
assertions = [
{ assertion = bitcoind.regtest -> cfg.validatepegin != true;
message = "liquidd: `validatepegin` is incompatible with regtest.";
}
];
services.bitcoind.enable = true;
environment.systemPackages = [
nbPkgs.elementsd
(hiPrio cfg.cli)
(hiPrio cfg.swapCli)
];
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group} - -"
];
systemd.services.liquidd = {
wants = [ "bitcoind.service" ];
after = [ "bitcoind.service" "nix-bitcoin-secrets.target" ];
wantedBy = [ "multi-user.target" ];
preStart = ''
install -m 640 ${configFile} '${cfg.dataDir}/elements.conf'
{
echo "rpcpassword=$(cat ${secretsDir}/liquid-rpcpassword)"
echo "mainchainrpcpassword=$(cat ${secretsDir}/bitcoin-rpcpassword-public)"
} >> '${cfg.dataDir}/elements.conf'
'';
serviceConfig = nbLib.defaultHardening // {
Type = "notify";
NotifyAccess = "all";
User = cfg.user;
Group = cfg.group;
TimeoutStartSec = "2h";
TimeoutStopSec = "2h";
ExecStart = "${nbPkgs.elementsd}/bin/elementsd -datadir='${cfg.dataDir}'";
Restart = "on-failure";
ReadWritePaths = [ cfg.dataDir ];
} // nbLib.allowedIPAddresses cfg.tor.enforce;
};
users.users.${cfg.user} = {
isSystemUser = true;
group = cfg.group;
extraGroups = [ "bitcoinrpc-public" ];
};
users.groups.${cfg.group} = {};
nix-bitcoin.operator.groups = [ cfg.group ];
nix-bitcoin.secrets.liquid-rpcpassword.user = cfg.user;
nix-bitcoin.generateSecretsCmds.liquid = ''
makePasswordSecret liquid-rpcpassword
'';
};
}
+7 -17
View File
@@ -104,8 +104,8 @@ let
}; };
package = mkOption { package = mkOption {
type = types.package; type = types.package;
default = config.nix-bitcoin.pkgs.lnd; default = pkgs.lnd;
defaultText = "config.nix-bitcoin.pkgs.lnd"; defaultText = lib.literalExpression "pkgs.lnd";
description = "The package providing lnd binaries."; description = "The package providing lnd binaries.";
}; };
cli = mkOption { cli = mkOption {
@@ -150,7 +150,7 @@ let
nbLib = config.nix-bitcoin.lib; nbLib = config.nix-bitcoin.lib;
secretsDir = config.nix-bitcoin.secretsDir; secretsDir = config.nix-bitcoin.secretsDir;
runAsUser = config.nix-bitcoin.runAsUserCmd; runAsUser = config.nix-bitcoin.runAsUserCmd;
lndinit = "${config.nix-bitcoin.pkgs.lndinit}/bin/lndinit"; lndinit = "${pkgs.lndinit}/bin/lndinit";
bitcoind = config.services.bitcoind; bitcoind = config.services.bitcoind;
@@ -191,19 +191,6 @@ in {
inherit options; inherit options;
config = mkIf cfg.enable { config = mkIf cfg.enable {
assertions = [
{ assertion =
!(config.services ? clightning)
|| !config.services.clightning.enable
|| config.services.clightning.port != cfg.port;
message = ''
LND and clightning can't both bind to lightning port 9735. Either
disable LND/clightning or change services.clightning.port or
services.lnd.port to a port other than 9735.
'';
}
];
services.bitcoind = { services.bitcoind = {
enable = true; enable = true;
@@ -265,13 +252,16 @@ in {
curl = "${pkgs.curl}/bin/curl -fsS --cacert ${cfg.certPath}"; curl = "${pkgs.curl}/bin/curl -fsS --cacert ${cfg.certPath}";
restUrl = "https://${nbLib.addressWithPort cfg.restAddress cfg.restPort}/v1"; restUrl = "https://${nbLib.addressWithPort cfg.restAddress cfg.restPort}/v1";
# Setting macaroon permissions for other users needs root permissions # Setting macaroon permissions for other users needs root permissions
# The admin macaroon is passed to curl via a fd because argv is
# world-readable through /proc/<pid>/cmdline
script = nbLib.rootScript "lnd-create-macaroons" '' script = nbLib.rootScript "lnd-create-macaroons" ''
umask ug=r,o= umask ug=r,o=
${lib.concatMapStrings (macaroon: '' ${lib.concatMapStrings (macaroon: ''
echo "Create custom macaroon ${macaroon}" echo "Create custom macaroon ${macaroon}"
macaroonPath="$RUNTIME_DIRECTORY/${macaroon}.macaroon" macaroonPath="$RUNTIME_DIRECTORY/${macaroon}.macaroon"
adminMacaroonHex=$(${pkgs.xxd}/bin/xxd -ps -u -c 99999 '${networkDir}/admin.macaroon')
${curl} \ ${curl} \
-H "Grpc-Metadata-macaroon: $(${pkgs.xxd}/bin/xxd -ps -u -c 99999 '${networkDir}/admin.macaroon')" \ -H @<(printf 'Grpc-Metadata-macaroon: %s\n' "$adminMacaroonHex") \
-X POST \ -X POST \
-d '{"permissions":[${cfg.macaroons.${macaroon}.permissions}]}' \ -d '{"permissions":[${cfg.macaroons.${macaroon}.permissions}]}' \
${restUrl}/macaroon |\ ${restUrl}/macaroon |\
-282
View File
@@ -1,282 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options = {
services.lnd.lndconnect = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Add a `lndconnect` binary to the system environment which prints
connection info for lnd clients.
See: https://github.com/LN-Zap/lndconnect
Usage:
```bash
# Print QR code
lndconnect
# Print URL
lndconnect --url
```
'';
};
onion = mkOption {
type = types.bool;
default = false;
description = ''
Create an onion service for the lnd REST server,
which is used by lndconnect.
'';
};
};
services.clightning.plugins.clnrest.lnconnect = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Add a `lnconnect-clnrest` binary to the system environment which prints
connection info for clightning clients.
See: https://github.com/LN-Zap/lndconnect
Usage:
```bash
# Print QR code
lnconnect-clnrest
# Print URL
lnconnect-clnrest --url
```
'';
};
onion = mkOption {
type = types.bool;
default = false;
description = ''
Create an onion service for the clnrest server,
which is used by lnconnect.
'';
};
};
services.clightning-rest.lndconnect = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Add a `lndconnect-clightning` binary to the system environment which prints
connection info for clightning clients.
See: https://github.com/LN-Zap/lndconnect
Usage:
```bash
# Print QR code
lndconnect-clightning
# Print URL
lndconnect-clightning --url
```
'';
};
onion = mkOption {
type = types.bool;
default = false;
description = ''
Create an onion service for the clightning REST server,
which is used by lndconnect.
'';
};
};
nix-bitcoin.mkLndconnect = mkOption {
readOnly = true;
default = mkLndconnect;
description = ''
A function to create a lndconnect binary.
See the source for further details.
'';
};
};
nbLib = config.nix-bitcoin.lib;
runAsUser = config.nix-bitcoin.runAsUserCmd;
inherit (config.services)
lnd
clightning
clightning-rest;
inherit (clightning.plugins) clnrest;
mkLndconnect = {
name,
shebang ? "#!${pkgs.stdenv.shell} -e",
isClightning ? false,
isClnrest ? false,
port,
authSecretPath,
enableOnion,
onionService ? null,
certPath ? null
}:
# TODO-EXTERNAL:
# lndconnect requires a --configfile argument, although it's unused
# https://github.com/LN-Zap/lndconnect/issues/25
lib.hiPrio (pkgs.writeScriptBin name ''
${shebang}
url=$(
${getExe config.nix-bitcoin.pkgs.lndconnect} --url \
${optionalString enableOnion "--host=$(cat ${config.nix-bitcoin.onionAddresses.dataDir}/${onionService})"} \
--port=${toString port} \
${if enableOnion || certPath == null then "--nocert" else "--tlscertpath='${certPath}'"} \
--adminmacaroonpath='${authSecretPath}' \
--configfile=/dev/null "$@"
)
${optionalString isClightning
# - Change URL procotcol to c-lightning-rest
# - Encode macaroon as hex (in uppercase) instead of base 64.
# Because `macaroon` is always the last URL fragment, the
# sed replacement below works correctly.
''
macaroonHex=$(${getExe pkgs.xxd} -p -u -c 99999 '${authSecretPath}')
url=$(
echo "$url" | ${getExe pkgs.gnused} "
s|^lndconnect|c-lightning-rest|
s|macaroon=.*|macaroon=$macaroonHex|
";
)
''
}
${optionalString isClnrest
# Change URL procotcol to clnrest
''
url=$(
echo "$url" | ${getExe pkgs.gnused} "
s|^lndconnect|clnrest|
s|macaroon=.*|rune=$(cat '${authSecretPath}')|
";
)
''
}
# If --url is in args
if [[ " $* " =~ " --url " ]]; then
echo "$url"
else
# This UTF-8 encoding yields a smaller, more convenient output format
# compared to the native lndconnect output
echo -n "$url" | ${getExe pkgs.qrencode} -t UTF8 -o -
fi
'');
operatorName = config.nix-bitcoin.operator.name;
in {
inherit options;
config = mkMerge [
(mkIf (lnd.enable && lnd.lndconnect.enable)
(mkMerge [
{
environment.systemPackages = [(
mkLndconnect {
name = "lndconnect";
# Run as lnd user because the macaroon and cert are not group-readable
shebang = "#!/usr/bin/env -S ${runAsUser} ${lnd.user} ${pkgs.bash}/bin/bash";
enableOnion = lnd.lndconnect.onion;
onionService = "${lnd.user}/lnd-rest";
port = lnd.restPort;
certPath = lnd.certPath;
authSecretPath = "${lnd.networkDir}/admin.macaroon";
}
)];
services.lnd.restAddress = mkIf (!lnd.lndconnect.onion) "0.0.0.0";
}
(mkIf lnd.lndconnect.onion {
services.tor = {
enable = true;
relay.onionServices.lnd-rest = nbLib.mkOnionService {
target.addr = nbLib.address lnd.restAddress;
target.port = lnd.restPort;
port = lnd.restPort;
};
};
nix-bitcoin.onionAddresses.access = {
${lnd.user} = [ "lnd-rest" ];
${operatorName} = [ "lnd-rest" ];
};
})
]))
(mkIf (clnrest.enable && clnrest.lnconnect.enable)
(mkMerge [
{
environment.systemPackages = [(
mkLndconnect {
name = "lnconnect-clnrest";
isClnrest = true;
enableOnion = clnrest.lnconnect.onion;
onionService = "${operatorName}/clnrest";
port = clnrest.port;
certPath = "${clightning.networkDir}/client.pem";
authSecretPath = "${clightning.networkDir}/admin-rune";
}
)];
services.clightning.plugins.clnrest.address = mkIf (!clnrest.lnconnect.onion) "0.0.0.0";
}
(mkIf clnrest.lnconnect.onion {
services.tor = {
enable = true;
relay.onionServices.clnrest = nbLib.mkOnionService {
target.addr = nbLib.address clnrest.address;
target.port = clnrest.port;
port = clnrest.port;
};
};
# This also allows nodeinfo to show the clnrest onion address
nix-bitcoin.onionAddresses.access.${operatorName} = [ "clnrest" ];
})
])
)
(mkIf (clightning-rest.enable && clightning-rest.lndconnect.enable)
(mkMerge [
{
environment.systemPackages = [(
mkLndconnect {
name = "lndconnect-clightning";
isClightning = true;
enableOnion = clightning-rest.lndconnect.onion;
onionService = "${operatorName}/clightning-rest";
port = clightning-rest.port;
certPath = "${clightning-rest.dataDir}/certs/certificate.pem";
authSecretPath = "${clightning-rest.dataDir}/certs/access.macaroon";
}
)];
# clightning-rest always binds to all interfaces
}
(mkIf clightning-rest.lndconnect.onion {
services.tor = {
enable = true;
relay.onionServices.clightning-rest = nbLib.mkOnionService {
target.addr = nbLib.address clightning-rest.address;
target.port = clightning-rest.port;
port = clightning-rest.port;
};
};
# This also allows nodeinfo to show the clightning-rest onion address
nix-bitcoin.onionAddresses.access.${operatorName} = [ "clightning-rest" ];
})
])
)
];
}
+6 -23
View File
@@ -94,19 +94,6 @@ let
default = 8999; default = 8999;
description = "Mempool backend port."; description = "Mempool backend port.";
}; };
electrumServer = mkOption {
type = types.enum [ "electrs" "fulcrum" ];
default = "electrs";
description = ''
The Electrum server to use for fetching address information.
Possible options:
- electrs:
Small database size, slow when querying new addresses.
- fulcrum:
Large database size, quickly serves arbitrary address queries.
'';
};
settings = mkOption { settings = mkOption {
type = with types; attrsOf (attrsOf anything); type = with types; attrsOf (attrsOf anything);
example = { example = {
@@ -170,8 +157,7 @@ let
inherit (config.services) inherit (config.services)
bitcoind bitcoind
electrs electrs;
fulcrum;
torSocket = config.services.tor.client.socksListenAddress; torSocket = config.services.tor.client.socksListenAddress;
@@ -240,8 +226,7 @@ in {
config = mkIf cfg.enable { config = mkIf cfg.enable {
services.bitcoind.txindex = true; services.bitcoind.txindex = true;
services.electrs.enable = mkIf (cfg.electrumServer == "electrs" ) true; services.electrs.enable = true;
services.fulcrum.enable = mkIf (cfg.electrumServer == "fulcrum" ) true;
services.mysql = { services.mysql = {
enable = true; enable = true;
package = pkgs.mariadb; package = pkgs.mariadb;
@@ -272,11 +257,9 @@ in {
USERNAME = bitcoind.rpc.users.public.name; USERNAME = bitcoind.rpc.users.public.name;
PASSWORD = "@btcRpcPassword@"; PASSWORD = "@btcRpcPassword@";
}; };
ELECTRUM = let ELECTRUM = {
server = config.services.${cfg.electrumServer}; HOST = electrs.address;
in { PORT = electrs.port;
HOST = server.address;
PORT = server.port;
TLS_ENABLED = false; TLS_ENABLED = false;
}; };
DATABASE = { DATABASE = {
@@ -298,7 +281,7 @@ in {
systemd.services.mempool = rec { systemd.services.mempool = rec {
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
requires = [ "mysql.service" ]; requires = [ "mysql.service" ];
wants = [ "${cfg.electrumServer}.service" ]; wants = [ "electrs.service" ];
after = requires ++ wants; after = requires ++ wants;
preStart = '' preStart = ''
mkdir -p '${cacheDir}/cache' mkdir -p '${cacheDir}/cache'
-18
View File
@@ -10,33 +10,15 @@
# Main features # Main features
./bitcoind.nix ./bitcoind.nix
./clightning.nix
./clightning-plugins
./clightning-rest.nix
./clightning-replication.nix
./lnd.nix ./lnd.nix
./lightning-loop.nix
./lightning-pool.nix
./charge-lnd.nix
./lndconnect.nix # Requires onion-addresses.nix
./rtl.nix
./mempool.nix ./mempool.nix
./electrs.nix ./electrs.nix
./fulcrum.nix
./liquid.nix
./btcpayserver.nix
./joinmarket.nix
./joinmarket-ob-watcher.nix
./hardware-wallets.nix
# Support features # Support features
./versioning.nix
./security.nix ./security.nix
./onion-addresses.nix ./onion-addresses.nix
./onion-services.nix ./onion-services.nix
./netns-isolation.nix
./nodeinfo.nix ./nodeinfo.nix
./backups.nix
]; ];
disabledModules = [ "services/networking/bitcoind.nix" ]; disabledModules = [ "services/networking/bitcoind.nix" ];
-366
View File
@@ -1,366 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.nix-bitcoin.netns-isolation = {
enable = mkEnableOption "netns isolation";
addressblock = mkOption {
type = types.ints.u8;
default = 1;
description = ''
The address block N in 169.254.N.0/24, used as the prefix for netns addresses.
'';
};
services = mkOption {
default = {};
type = types.attrsOf (types.submodule {
options = {
id = mkOption {
# TODO: Assert uniqueness
type = types.ints.between 11 255;
description = ''
id for the netns, used for the IP address host part and
for naming the interfaces. Must be unique. Must be greater than 10.
'';
};
connections = mkOption {
type = with types; listOf str;
default = [];
};
};
});
};
allowedUser = mkOption {
type = types.str;
description = ''
User that is allowed to execute commands in the service network namespaces.
'';
default = config.nix-bitcoin.operator.name;
};
netns = mkOption {
readOnly = true;
default = netns;
description = "Exposes netns parameters.";
};
bridgeIp = mkOption {
readOnly = true;
default = bridgeIp;
description = "IP of the netns bridge interface.";
};
};
cfg = config.nix-bitcoin.netns-isolation;
netns = builtins.mapAttrs (n: v: {
inherit (v) id;
address = "169.254.${toString cfg.addressblock}.${toString v.id}";
availableNetns = availableNetns.${n};
netnsName = "nb-${n}";
}) enabledServices;
# Symmetric netns connection matrix
# if clightning.connections = [ "bitcoind" ]; then
# availableNetns.bitcoind = [ "clighting" ];
# and
# availableNetns.clighting = [ "bitcoind" ];
#
# TODO-EXTERNAL:
# Although negligible for our purposes, this calculation's runtime
# is in the order of (number of connections * number of services),
# because attrsets and lists are fully copied on each update with '//' or '++'.
# This can only be improved with an update in the nix language.
#
availableNetns = let
# base = { clightning = [ "bitcoind" ]; ... }
base = builtins.mapAttrs (n: v:
builtins.filter isEnabled v.connections
) enabledServices;
in
foldl (xs: s1:
foldl (xs: s2:
xs // { "${s2}" = xs.${s2} ++ [ s1 ]; }
) xs cfg.services.${s1}.connections
) base (builtins.attrNames base);
enabledServices = filterAttrs (n: v: isEnabled n) cfg.services;
isEnabled = x: config.services.${x}.enable;
ip = "${pkgs.iproute2}/bin/ip";
iptables = "${config.networking.firewall.package}/bin/iptables";
bridgeIp = "169.254.${toString cfg.addressblock}.10";
mkCliExec = service: "exec netns-exec ${netns.${service}.netnsName}";
in {
inherit options;
config = mkIf cfg.enable (mkMerge [
# Base infrastructure
{
networking.dhcpcd.denyInterfaces = [ "nb-br" "nb-veth*" ];
services.tor.client.socksListenAddress = {
addr = bridgeIp;
# Default NixOS values. These must be repeated when redefining this option.
port = 9050;
IsolateDestAddr = true;
};
services.i2pd.proto.sam.address = bridgeIp;
networking.firewall.interfaces.nb-br.allowedTCPPorts = [
config.services.tor.client.socksListenAddress.port
config.services.i2pd.proto.sam.port
];
boot.kernel.sysctl."net.ipv4.ip_forward" = true;
security.wrappers.netns-exec = {
source = config.nix-bitcoin.pkgs.netns-exec;
capabilities = "cap_sys_admin=ep";
owner = cfg.allowedUser;
# Don't authorize the group of `owner`. For normal users, this group is
# `users`, which is shared by all normal users.
group = "root";
permissions = "500";
};
systemd.services = {
# Due to a NixOS bug we can't currently use option `networking.bridges` to
# setup the bridge while `networking.useDHCP` is enabled.
nb-netns-bridge = {
description = "nix-bitcoin netns bridge";
wantedBy = [ "network-setup.service" ];
partOf = [ "network-setup.service" ];
before = [ "network-setup.service" ];
after = [ "network-pre.target" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = ''
${ip} link add name nb-br type bridge
${ip} link set nb-br up
${ip} addr add ${bridgeIp}/24 brd + dev nb-br
${iptables} -w -t nat -A POSTROUTING -s 169.254.${toString cfg.addressblock}.0/24 -j MASQUERADE
'';
preStop = ''
${iptables} -w -t nat -D POSTROUTING -s 169.254.${toString cfg.addressblock}.0/24 -j MASQUERADE
${ip} link del nb-br
'';
};
} //
(let
makeNetnsServices = n: v: let
veth = "nb-veth-${toString v.id}";
peer = "nb-veth-br-${toString v.id}";
inherit (v) netnsName;
nsenter = "${pkgs.util-linux}/bin/nsenter";
allowedNetnsAddresses = map (available: netns.${available}.address) v.availableNetns;
allowedAddresses = concatStringsSep ","
([ "127.0.0.1,${bridgeIp},${v.address}" ] ++ allowedNetnsAddresses);
setup = ''
${ip} netns add ${netnsName}
${ip} link add ${veth} type veth peer name ${peer}
${ip} link set ${veth} netns ${netnsName}
# The peer link is never used directly, so don't auto-assign an IPv6 address
echo 1 > /proc/sys/net/ipv6/conf/${peer}/disable_ipv6
${ip} link set ${peer} up
${ip} link set ${peer} master nb-br
exec ${nsenter} --net=/run/netns/${netnsName} ${script "in-netns" setupInNetns}
'';
setupInNetns = ''
${ip} link set lo up
${ip} addr add ${v.address}/24 dev ${veth}
${ip} link set ${veth} up
${ip} route add default via ${bridgeIp}
${iptables} -w -P INPUT DROP
# allow return traffic to outgoing connections initiated by the service itself
${iptables} -w -A INPUT -m conntrack --ctstate ESTABLISHED -j ACCEPT
${iptables} -w -A INPUT -s ${allowedAddresses} -j ACCEPT
'' + optionalString (config.services.${n}.tor.enforce or false) ''
${iptables} -w -P OUTPUT DROP
${iptables} -w -A OUTPUT -d ${allowedAddresses} -j ACCEPT
'';
script = name: src: pkgs.writers.writeDash name ''
set -e
${src}
'';
in {
"${n}".serviceConfig.NetworkNamespacePath = "/var/run/netns/${netnsName}";
"netns-${n}" = rec {
requires = [ "nb-netns-bridge.service" ];
after = [ "nb-netns-bridge.service" ];
requiredBy = [ "${n}.service" ];
before = requiredBy;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = script "setup" setup;
};
# Link deletion is implicit in netns deletion, but it sometimes only happens
# after `netns delete` finishes. Add an extra `link del` to ensure that
# the link is deleted before the service stops, which is needed for service
# restart to succeed.
preStop = ''
${ip} netns delete ${netnsName}
${ip} link del ${peer} 2> /dev/null || true
'';
};
};
in
foldl (services: n:
services // (makeNetnsServices n netns.${n})
) {} (builtins.attrNames netns)
);
}
# Service-specific config
{
nix-bitcoin.netns-isolation.services = {
bitcoind = {
id = 12;
};
clightning = {
id = 13;
connections = [ "bitcoind" ];
};
lnd = {
id = 14;
connections = [ "bitcoind" ];
};
liquidd = {
id = 15;
connections = [ "bitcoind" ];
};
electrs = {
id = 16;
connections = [ "bitcoind" ];
};
nginx = {
id = 21;
};
lightning-loop = {
id = 22;
connections = [ "lnd" ];
};
nbxplorer = {
id = 23;
connections = [ "bitcoind" ]
++ optional config.services.btcpayserver.lbtc "liquidd";
};
btcpayserver = {
id = 24;
connections = [ "nbxplorer" ]
++ optional (config.services.btcpayserver.lightningBackend == "lnd") "lnd"
++ optional config.services.btcpayserver.lbtc "liquidd";
# communicates with clightning over rpc socket
};
joinmarket = {
id = 25;
connections = [ "bitcoind" ];
};
joinmarket-ob-watcher = {
id = 26;
connections = [ "bitcoind" ];
};
lightning-pool = {
id = 27;
connections = [ "lnd" ];
};
charge-lnd = {
id = 28;
connections = [ "lnd" "electrs" ];
};
rtl = {
id = 29;
connections = let
nodes = config.services.rtl.nodes;
in
optional nodes.lnd.enable "lnd" ++
optional (nodes.lnd.enable && nodes.lnd.loop) "lightning-loop" ++
optional nodes.clightning.enable "clightning";
};
clightning-rest = {
id = 30;
};
fulcrum = {
id = 31;
connections = [ "bitcoind" ];
};
mempool = {
id = 32;
connections = [
"bitcoind"
"nginx"
(if (config.services.mempool.electrumServer == "electrs") then "electrs" else "fulcrum")
];
};
};
services.bitcoind = {
address = netns.bitcoind.address;
rpc.address = netns.bitcoind.address;
rpc.allowip = [
bridgeIp # For operator user
netns.bitcoind.address
] ++ map (n: netns.${n}.address) netns.bitcoind.availableNetns;
};
services.clightning.address = netns.clightning.address;
services.clightning.plugins.clnrest.address = netns.clightning.address;
services.lnd = {
address = netns.lnd.address;
rpcAddress = netns.lnd.address;
restAddress = netns.lnd.address;
};
services.liquidd = {
address = netns.liquidd.address;
rpc.address = netns.liquidd.address;
rpcallowip = [
bridgeIp # For operator user
netns.liquidd.address
] ++ map (n: netns.${n}.address) netns.liquidd.availableNetns;
};
services.electrs.address = netns.electrs.address;
services.fulcrum.address = netns.fulcrum.address;
services.lightning-loop.rpcAddress = netns.lightning-loop.address;
services.nbxplorer.address = netns.nbxplorer.address;
services.btcpayserver.address = netns.btcpayserver.address;
services.joinmarket = mkIf config.services.joinmarket.enable {
payjoinAddress = netns.joinmarket.address;
messagingAddress = netns.joinmarket.address;
cliExec = mkCliExec "joinmarket";
};
systemd.services.joinmarket-yieldgenerator = mkIf config.services.joinmarket.yieldgenerator.enable {
serviceConfig.NetworkNamespacePath = "/var/run/netns/nb-joinmarket";
};
services.joinmarket-ob-watcher.address = netns.joinmarket-ob-watcher.address;
services.lightning-pool.rpcAddress = netns.lightning-pool.address;
services.rtl.address = netns.rtl.address;
services.clightning-rest.address = netns.clightning-rest.address;
services.mempool.address = netns.mempool.address;
services.mempool.frontend.address = netns.nginx.address;
}
]);
}
+2 -2
View File
@@ -6,8 +6,8 @@ with lib;
nix-bitcoin = { nix-bitcoin = {
pkgs = mkOption { pkgs = mkOption {
type = types.attrs; type = types.attrs;
default = (import ../pkgs { inherit pkgs; }).modulesPkgs; default = import ../pkgs { inherit pkgs; };
defaultText = "nix-bitcoin/pkgs.modulesPkgs"; defaultText = "nix-bitcoin/pkgs";
apply = base: apply = base:
let let
final = foldl (prev: overlay: final = foldl (prev: overlay:
-15
View File
@@ -130,11 +130,6 @@ in {
nix-bitcoin.nodeinfo.services = with nodeinfoLib; { nix-bitcoin.nodeinfo.services = with nodeinfoLib; {
bitcoind = mkInfo ""; bitcoind = mkInfo "";
clightning = mkInfo ''
info["nodeid"] = shell("lightning-cli getinfo | jq -r '.id'")
if 'onion_address' in info:
info["id"] = f"{info['nodeid']}@{info['onion_address']}"
'';
lnd = name: cfg: mkInfo ('' lnd = name: cfg: mkInfo (''
info["rest_address"] = "${nbLib.addressWithPort cfg.restAddress cfg.restPort}" info["rest_address"] = "${nbLib.addressWithPort cfg.restAddress cfg.restPort}"
'' + mkIfOnionPort "lnd-rest" (onionPort: '' '' + mkIfOnionPort "lnd-rest" (onionPort: ''
@@ -142,17 +137,7 @@ in {
'') + '' '') + ''
info["nodeid"] = shell("lncli getinfo | jq -r '.identity_pubkey'") info["nodeid"] = shell("lncli getinfo | jq -r '.identity_pubkey'")
'') name cfg; '') name cfg;
clnrest = name: cfg: mkInfoLong {
inherit name cfg;
systemdServiceName = "clightning";
};
clightning-rest = mkInfo "";
electrs = mkInfo ""; electrs = mkInfo "";
fulcrum = mkInfo "";
btcpayserver = mkInfo "";
liquidd = mkInfo "";
joinmarket-ob-watcher = mkInfo "";
rtl = mkInfo "";
mempool = mkInfo ""; mempool = mkInfo "";
mempool-frontend = name: cfg: mkInfoLong { mempool-frontend = name: cfg: mkInfoLong {
inherit name cfg; inherit name cfg;
-145
View File
@@ -1,145 +0,0 @@
{ lib, config, ... }:
with lib;
let
mkRenamedAnnounceTorOption = service:
# use mkRemovedOptionModule because mkRenamedOptionModule fails with an infinite recursion error
mkRemovedOptionModule [ "services" service "announce-tor" ] ''
Use option `nix-bitcoin.onionServices.${service}.public` instead.
'';
mkSplitEnforceTorOption = service:
(mkRemovedOptionModule [ "services" service "enforceTor" ] ''
The option has been split into options `tor.proxy` and `tor.enforce`.
Set `tor.proxy = true` to proxy outgoing connections with Tor.
Set `tor.enforce = true` to only allow connections (incoming and outgoing) through Tor.
'');
mkRenamedEnforceTorOption = service:
(mkRenamedOptionModule [ "services" service "enforceTor" ] [ "services" service "tor" "enforce" ]);
in {
imports = [
(mkRenamedOptionModule [ "services" "bitcoind" "bind" ] [ "services" "bitcoind" "address" ])
(mkRenamedOptionModule [ "services" "bitcoind" "rpcallowip" ] [ "services" "bitcoind" "rpc" "allowip" ])
(mkRenamedOptionModule [ "services" "bitcoind" "rpcthreads" ] [ "services" "bitcoind" "rpc" "threads" ])
(mkRenamedOptionModule [ "services" "clightning" "bind-addr" ] [ "services" "clightning" "address" ])
(mkRenamedOptionModule [ "services" "clightning" "bindport" ] [ "services" "clightning" "port" ])
(mkRenamedOptionModule [ "services" "lnd" "rpclisten" ] [ "services" "lnd" "rpcAddress" ])
(mkRenamedOptionModule [ "services" "lnd" "listen" ] [ "services" "lnd" "address" ])
(mkRenamedOptionModule [ "services" "lnd" "listenPort" ] [ "services" "lnd" "port" ])
(mkRenamedOptionModule [ "services" "btcpayserver" "bind" ] [ "services" "btcpayserver" "address" ])
(mkRenamedOptionModule [ "services" "liquidd" "bind" ] [ "services" "liquidd" "address" ])
(mkRenamedOptionModule [ "services" "liquidd" "rpcbind" ] [ "services" "liquidd" "rpc" "address" ])
# 0.0.70
(mkRenamedOptionModule [ "services" "rtl" "cl-rest" ] [ "services" "clightning-rest" ])
(mkRenamedOptionModule [ "nix-bitcoin" "setup-secrets" ] [ "nix-bitcoin" "setupSecrets" ])
(mkRenamedAnnounceTorOption "clightning")
(mkRenamedAnnounceTorOption "lnd")
# 0.0.53
(mkRemovedOptionModule [ "services" "electrs" "high-memory" ] ''
This option is no longer supported by electrs 0.9.0. Electrs now always uses
bitcoin peer connections for syncing blocks. This performs well on low and high
memory systems.
'')
# 0.0.86
(mkRemovedOptionModule [ "services" "lnd" "restOnionService" "enable" ] ''
Set the following options instead:
services.lnd.lndconnect = {
enable = true;
onion = true;
}
'')
(mkRemovedOptionModule [ "services" "lnd" "lndconnectOnion" ] ''
Set the following options instead:
services.lnd.lndconnect = {
enable = true;
onion = true;
}
'')
(mkRemovedOptionModule [ "services" "clightning-rest" "lndconnectOnion" ] ''
Set the following options instead:
services.clightning-rest.lndconnect = {
enable = true;
onion = true;
}
'')
] ++
# 0.0.59
(map mkSplitEnforceTorOption [
"clightning"
"lightning-loop"
"lightning-pool"
"liquid"
"lnd"
"bitcoind"
]) ++
(map mkRenamedEnforceTorOption [
"btcpayserver"
"rtl"
"electrs"
]) ++
# 0.0.77
[
(mkRemovedOptionModule [ "services" "clightning" "plugins" "commando" ] ''
clightning 0.12.0 ships with a reimplementation of the commando plugin
that is incompatible with the commando module that existed in
nix-bitcoin. The new built-in commando plugin is always enabled. For
information on how to use it, run `lightning-cli help commando` and
`lightning-cli help commando-rune`.
'')
] ++
# 0.0.92
[
(mkRemovedOptionModule [ "services" "spark-wallet" ] ''
Spark Lightning Wallet is unmaintained and incompatible with clightning
23.05. Therefore, the spark-wallet module has been removed from
nix-bitcoin. For a replacement, consider using the rtl (Ride The
Lightning) module or the clightning-rest module in combination with the
Zeus mobile wallet.
'')
]
++
# 0.0.98
[
(mkRemovedOptionModule [ "services" "clightning" "plugins" "clboss" "acknowledgeDeprecation" ] ''
`clboss` is maintained again and has been un-deprecated.
'')
]
++
# 0.0.106
(map (plugin:
mkRemovedOptionModule [ "services" "clightning" "plugins" plugin ] ''
This plugin is no longer maintained.
'')
[ "summary" "helpme" "prometheus" ]
)
++
# 0.0.110
[
(mkRemovedOptionModule [ "services" "joinmarket" "yieldgenerator" "txfee" ] ''
Option `txfee` has been removed in joinmarket 0.9.3:
https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/v0.9.3/docs/release-notes/release-notes-0.9.3.md
'')
];
config = {
# Migrate old clightning-rest datadir from nix-bitcoin versions < 0.0.70
systemd.services.clightning-rest-migrate-datadir = let
inherit (config.services) clightning-rest clightning;
in mkIf config.services.clightning-rest.enable {
requiredBy = [ "clightning-rest.service" ];
before = [ "clightning-rest.service" ];
script = ''
if [[ -e /var/lib/cl-rest/certs ]]; then
mv /var/lib/cl-rest/* '${clightning-rest.dataDir}'
chown -R ${clightning.user}: '${clightning-rest.dataDir}'
rm -r /var/lib/cl-rest
fi
'';
serviceConfig.Type = "oneshot";
};
};
}
+2 -2
View File
@@ -15,10 +15,10 @@ let
description = '' description = ''
This option controls who is allowed to access onion addresses. This option controls who is allowed to access onion addresses.
For example, the following allows user 'myuser' to access bitcoind For example, the following allows user 'myuser' to access bitcoind
and clightning onion addresses: and lnd onion addresses:
```nix ```nix
{ {
"myuser" = [ "bitcoind" "clightning" ]; "myuser" = [ "bitcoind" "lnd" ];
}; };
``` ```
The onion hostnames can then be read from The onion hostnames can then be read from
-9
View File
@@ -104,15 +104,6 @@ in {
# Set sensible defaults for some services # Set sensible defaults for some services
{ {
nix-bitcoin.onionServices = { nix-bitcoin.onionServices = {
btcpayserver = {
externalPort = 80;
};
joinmarket-ob-watcher = {
externalPort = 80;
};
rtl = {
externalPort = 80;
};
mempool-frontend = { mempool-frontend = {
externalPort = 80; externalPort = 80;
}; };
-27
View File
@@ -1,27 +0,0 @@
{ config, lib, pkgs, ... }:
let
cfg = config.services.bitcoind;
secretsDir = config.nix-bitcoin.secretsDir;
in {
services.bitcoind = {
# Make the local bitcoin-cli work with the remote node.
# Without this, bitcoin-cli would try to use the .cookie file in the local
# bitcoind data dir for authorization, which doesn't exist.
extraConfig = ''
rpcuser=${cfg.rpc.users.privileged.name}
'';
};
systemd.services.bitcoind = {
preStart = lib.mkAfter ''
echo "rpcpassword=$(cat ${secretsDir}/bitcoin-rpcpassword-privileged)" >> '${cfg.dataDir}/bitcoin.conf'
'';
postStart = lib.mkForce "";
serviceConfig = {
Type = lib.mkForce "oneshot";
ExecStart = lib.mkForce "${pkgs.coreutils}/bin/true";
RemainAfterExit = true;
};
};
}
-54
View File
@@ -1,54 +0,0 @@
{ lib, config, ... }:
let
defaultTrue = lib.mkDefault true;
defaultEnableTorProxy = {
tor.proxy = defaultTrue;
tor.enforce = defaultTrue;
};
defaultEnforceTor = {
tor.enforce = defaultTrue;
};
in {
services.tor = {
enable = true;
client.enable = true;
};
services = {
# Use Tor as a proxy for outgoing connections
# and restrict all connections to Tor
#
bitcoind = defaultEnableTorProxy;
clightning = defaultEnableTorProxy;
lnd = defaultEnableTorProxy;
lightning-loop = defaultEnableTorProxy;
liquidd = defaultEnableTorProxy;
# TODO-EXTERNAL:
# disable Tor enforcement until btcpayserver can fetch rates over Tor
# btcpayserver = defaultEnableTorProxy;
lightning-pool = defaultEnableTorProxy;
mempool = defaultEnableTorProxy;
# These services don't make outgoing connections
# (or use Tor by default in case of joinmarket)
# but we restrict them to Tor just to be safe.
#
electrs = defaultEnforceTor;
fulcrum = defaultEnforceTor;
nbxplorer = defaultEnforceTor;
rtl = defaultEnforceTor;
joinmarket = defaultEnforceTor;
joinmarket-ob-watcher = defaultEnforceTor;
clightning-rest = defaultEnforceTor;
};
# Add onion services for incoming connections
nix-bitcoin.onionServices = {
bitcoind.enable = defaultTrue;
liquidd.enable = defaultTrue;
electrs.enable = defaultTrue;
fulcrum.enable = defaultTrue;
joinmarket-ob-watcher.enable = defaultTrue;
rtl.enable = defaultTrue;
};
}
-141
View File
@@ -1,141 +0,0 @@
# This preset adds additional hardening settings on top of the
# default ./hardened.nix preset.
# These settings trade even more functionality and performance for increased security.
# This preset enables usbguard. Use `services.usbguard.rules` to whitelist
# select devices.
#
# See madaidan's Linux Hardening Guide for detailed explanations:
# https://madaidans-insecurities.github.io/guides/linux-hardening.html
{
imports = [
# Build on standard hardened preset
./hardened.nix
];
boot.kernel.sysctl = {
# Prevent boot console kernel log information leaks
"kernel.printk" = "3 3 3 3";
# Restrict loading TTY line disciplines to the CAP_SYS_MODULE capability to
# prevent unprivileged attackers from loading vulnerable line disciplines with
# the TIOCSETD ioctl
"dev.tty.ldisc_autoload" = "0";
# The SysRq key exposes a lot of potentially dangerous debugging functionality
# to unprivileged users
"kernel.sysrq" = "4";
# Protect against time-wait assassination by dropping RST packets for sockets
# in the time-wait state
"net.ipv4.tcp_rfc1337" = "1";
# Disable accepting IPv6 router advertisements
"net.ipv6.conf.all.accept_ra" = "0";
"net.ipv6.default.accept_ra" = "0";
# Disable TCP SACK. SACK is commonly exploited and unnecessary for many
# circumstances so it should be disabled if you don't require it
"net.ipv4.tcp_sack" = "0";
"net.ipv4.tcp_dsack" = "0";
# Restrict usage of ptrace to only processes with the CAP_SYS_PTRACE
# capability
"kernel.yama.ptrace_scope" = "2";
# Prevent creating files in potentially attacker-controlled environments such
# as world-writable directories to make data spoofing attacks more difficult
"fs.protected_fifos" = "2";
"fs.protected_regular" = "2";
# Avoid leaking system time with TCP timestamps
"net.ipv4.tcp_timestamps" = "0";
# Disable core dumps
"syskernel.core_pattern" = "|/bin/false";
"fs.suid_dumpable" = "0";
# Only swap when absolutely necessary
"vm.swappiness" = "1";
};
boot.kernelParams = [
# Disable slab merging which significantly increases the difficulty of heap
# exploitation by preventing overwriting objects from merged caches and by
# making it harder to influence slab cache layout
"slab_nomerge"
# Disable vsyscalls as they are obsolete and have been replaced with vDSO.
# vsyscalls are also at fixed addresses in memory, making them a potential
# target for ROP attacks
"vsyscall=none"
# Disable debugfs which exposes a lot of sensitive information about the
# kernel
"debugfs=off"
# Sometimes certain kernel exploits will cause what is known as an "oops".
# This parameter will cause the kernel to panic on such oopses, thereby
# preventing those exploits
"oops=panic"
# Only allow kernel modules that have been signed with a valid key to be
# loaded, which increases security by making it much harder to load a
# malicious kernel module
"module.sig_enforce=1"
# The kernel lockdown LSM can eliminate many methods that user space code
# could abuse to escalate to kernel privileges and extract sensitive
# information. This LSM is necessary to implement a clear security boundary
# between user space and the kernel
"lockdown=confidentiality"
# These parameters prevent information leaks during boot and must be used
# in combination with the kernel.printk
"quiet" "loglevel=0"
];
boot.blacklistedKernelModules = [
# Obscure networking protocols
"dccp"
"sctp"
"rds"
"tipc"
"n-hdlc"
"x25"
"decnet"
"econet"
"af_802154"
"ipx"
"appletalk"
"psnap"
"p8023"
"p8022"
"can"
"atm"
# Various rare filesystems
"jffs2"
"hfsplus"
"squashfs"
"udf"
"cifs"
"nfs"
"nfsv3"
"nfsv4"
"gfs2"
# vivid driver is only useful for testing purposes and has been the cause
# of privilege escalation vulnerabilities
"vivid"
# Disable Bluetooth
"bluetooth"
"btusb"
# Disable webcam
"uvcvideo"
# Disable Thunderbolt and FireWire to prevent DMA attacks
"thunderbolt"
"firewire-core"
];
services.usbguard.enable = true;
}
-15
View File
@@ -1,15 +0,0 @@
{ modulesPath, ... }: {
imports = [
# Source:
# https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/profiles/hardened.nix
(modulesPath + "/profiles/hardened.nix")
];
## Reset some options set by the hardened profile
# Needed for sandboxed builds and services
security.allowUserNamespaces = true;
# The "scudo" allocator is broken on NixOS >= 20.09
environment.memoryAllocator.provider = "libc";
}
-62
View File
@@ -1,62 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
cfg = config.services;
nbLib = config.nix-bitcoin.lib;
operatorName = config.nix-bitcoin.operator.name;
in {
imports = [
../modules.nix
./enable-tor.nix
];
options = {
# Used by ../versioning.nix
nix-bitcoin.secure-node-preset-enabled = {};
};
config = {
networking.firewall.enable = true;
nix-bitcoin.security.dbusHideProcessInformation = true;
# Use doas instead of sudo
security.doas.enable = true;
security.sudo.enable = false;
environment.shellAliases.sudo = "doas";
environment.systemPackages = with pkgs; [
jq
];
# Add a SSH onion service
services.tor.relay.onionServices.sshd = nbLib.mkOnionService { port = 22; };
nix-bitcoin.onionAddresses.access.${operatorName} = [ "sshd" ];
services.bitcoind = {
enable = true;
listen = true;
dbCache = 1000;
};
services.liquidd = {
# Enable `validatepegin` to verify that a transaction sending BTC into
# Liquid exists on Bitcoin. Without it, a malicious liquid federation can
# make the node accept a sidechain that is not fully backed.
validatepegin = true;
listen = true;
};
nix-bitcoin.nodeinfo.enable = true;
services.backups.frequency = "daily";
# operator
nix-bitcoin.operator.enable = true;
users.users.${operatorName} = {
openssh.authorizedKeys.keys = config.users.users.root.openssh.authorizedKeys.keys;
};
};
}
-236
View File
@@ -1,236 +0,0 @@
{ config, pkgs, lib, ... }:
# Create a WireGuard server with a single peer.
# Private/public keys are created via the secrets system.
# Add helper binaries `nix-bitcoin-wg-connect` and optionally `lndconnect-wg`,
# `lnconnect-clnrest-wg`, `lndconnect-clightning-wg`.
# See ../../docs/services.md ("Use Zeus (mobile lightning wallet) via WireGuard")
# for usage instructions.
# This is a rather opinionated implementation that lacks the flexibility offered by
# other nix-bitcoin modules, so ship this as a `preset`.
# Some users will prefer to use `lndconnect` with their existing WireGuard or Tailscale setup.
with lib;
let
options.nix-bitcoin.wireguard = {
subnet = mkOption {
type = types.str;
default = "10.10.0";
description = "The /24 subnet of the wireguard network.";
};
restrictPeer = mkOption {
type = types.bool;
default = true;
description = ''
Prevent the peer from connecting to any addresses except for the WireGuard server address.
'';
};
};
cfg = config.nix-bitcoin.wireguard;
wgSubnet = cfg.subnet;
inherit (config.networking.wireguard.interfaces) wg-nb;
inherit (config.services)
lnd
clightning
clightning-rest;
inherit (clightning.plugins) clnrest;
lndconnect = lnd.enable && lnd.lndconnect.enable;
lnconnect-clnrest = clnrest.enable && clnrest.lnconnect.enable;
lndconnect-clightning = clightning-rest.enable && clightning-rest.lndconnect.enable;
serverAddress = "${wgSubnet}.1";
peerAddress = "${wgSubnet}.2";
secretsDir = config.nix-bitcoin.secretsDir;
wgConnectUser = if config.nix-bitcoin.operator.enable
then config.nix-bitcoin.operator.name
else "root";
# A script that prints a QR code to connect a peer to the server.
# The QR code encodes a wg-quick config that can be imported by the wireguard
# mobile app.
wgConnect = pkgs.writers.writeBashBin "nix-bitcoin-wg-connect" ''
set -euo pipefail
text=
host=
for arg in "$@"; do
case $arg in
--text)
text=1
;;
*)
host=$arg
;;
esac
done
if [[ ! $host ]]; then
# Use lndconnect to fetch the external ip.
# This internally uses https://github.com/GlenDC/go-external-ip, which
# queries a set of external ip providers.
host=$(
${getExe config.nix-bitcoin.pkgs.lndconnect} --url --nocert \
--configfile=/dev/null --adminmacaroonpath=/dev/null \
| sed -nE 's|.*?/(.*?):.*|\1|p'
)
fi
config="[Interface]
PrivateKey = $(cat ${secretsDir}/wg-peer-private-key)
Address = ${peerAddress}/24
[Peer]
PublicKey = $(cat ${secretsDir}/wg-server-public-key)
AllowedIPs = ${wgSubnet}.0/24
Endpoint = $host:${toString wg-nb.listenPort}
PersistentKeepalive = 25
"
if [[ $text ]]; then
echo "$config"
else
echo "$config" | ${getExe pkgs.qrencode} -t UTF8 -o -
fi
'';
in {
inherit options;
config = {
assertions = [
{
# Don't support `netns-isolation` for now to keep things simple
assertion = !(config.nix-bitcoin.netns-isolation.enable or false);
message = "`nix-bitcoin.wireguard` is not compatible with `netns-isolation`.";
}
];
networking.wireguard.interfaces.wg-nb = {
ips = [ "${serverAddress}/24" ];
listenPort = mkDefault 51820;
privateKeyFile = "${secretsDir}/wg-server-private-key";
allowedIPsAsRoutes = false;
peers = [
{
# To use the actual public key from the secrets file, use dummy pubkey
# `peer0` and replace it via `getPubkeyFromFile` (see further below)
# at peer service runtime.
publicKey = "peer0";
allowedIPs = [ "${peerAddress}/32" ];
}
];
};
systemd.services = {
wireguard-wg-nb = rec {
wants = [ "nix-bitcoin-secrets.target" ];
after = wants;
};
# HACK: Modify start/stop scripts of the peer setup service to read
# the pubkey from a secrets file.
wireguard-wg-nb-peer-peer0 = let
getPubkeyFromFile = mkBefore ''
if [[ ! -v inPatchedSrc ]]; then
export inPatchedSrc=1
publicKey=$(cat "${secretsDir}/wg-peer-public-key")
<"''${BASH_SOURCE[0]}" sed "s|\bpeer0\b|$publicKey|g" | ${pkgs.bash}/bin/bash -s
exit
fi
'';
in {
script = getPubkeyFromFile;
postStop = getPubkeyFromFile;
};
};
environment.systemPackages = [
wgConnect
] ++ (optional lndconnect
(pkgs.writers.writeBashBin "lndconnect-wg" ''
exec lndconnect --host "${serverAddress}" --nocert "$@"
'')
) ++ (optional lnconnect-clnrest
(pkgs.writers.writeBashBin "lnconnect-clnrest-wg" ''
exec lnconnect-clnrest --host "${serverAddress}" --nocert "$@"
'')
) ++ (optional lndconnect-clightning
(pkgs.writers.writeBashBin "lndconnect-clightning-wg" ''
exec lndconnect-clightning --host "${serverAddress}" --nocert "$@"
'')
);
networking.firewall = let
restrictPeerRule = "-s ${peerAddress} ! -d ${serverAddress} -j REJECT";
in {
allowedUDPPorts = [ wg-nb.listenPort ];
extraCommands =
optionalString lndconnect ''
iptables -w -A nixos-fw -p tcp -s ${wgSubnet}.0/24 --dport ${toString lnd.restPort} -j nixos-fw-accept
''
+ optionalString lnconnect-clnrest ''
iptables -w -A nixos-fw -p tcp -s ${wgSubnet}.0/24 --dport ${toString clnrest.port} -j nixos-fw-accept
''
+ optionalString lndconnect-clightning ''
iptables -w -A nixos-fw -p tcp -s ${wgSubnet}.0/24 --dport ${toString clightning-rest.port} -j nixos-fw-accept
''
+ optionalString cfg.restrictPeer ''
iptables -w -A nixos-fw ${restrictPeerRule}
iptables -w -A FORWARD ${restrictPeerRule}
'';
extraStopCommands =
# Rules added to chain `nixos-fw` are automatically removed when restarting
# the NixOS firewall service.
mkIf cfg.restrictPeer ''
iptables -w -D FORWARD ${restrictPeerRule} || :
'';
};
# Listen on all addresses, including `serverAddress`.
# This is safe because the listen ports are secured by the firewall.
services.lnd = mkIf lndconnect {
restAddress = "0.0.0.0";
tor.enforce = false;
};
services.clightning.plugins.clnrest.address = mkIf lnconnect-clnrest "0.0.0.0";
# clnrest runs inside `clightning.service`
services.clightning.tor.enforce = mkIf lnconnect-clnrest false;
services.clightning-rest = mkIf lndconnect-clightning {
# clightning-rest always listens on "0.0.0.0"
tor.enforce = false;
};
nix-bitcoin.secrets = {
wg-server-private-key = {};
wg-server-public-key = { user = wgConnectUser; group = "root"; };
wg-peer-private-key = { user = wgConnectUser; group = "root"; };
wg-peer-public-key = {};
};
nix-bitcoin.generateSecretsCmds.wireguard = let
wg = "${pkgs.wireguard-tools}/bin/wg";
in ''
makeWireguardKey() {
local name=$1
local priv=wg-$name-private-key
local pub=wg-$name-public-key
if [[ ! -e $priv ]]; then
${wg} genkey > $priv
fi
if [[ $priv -nt $pub ]]; then
${wg} pubkey < $priv > $pub
fi
}
makeWireguardKey server
makeWireguardKey peer
'';
};
}
-239
View File
@@ -1,239 +0,0 @@
{ config, lib, pkgs, ... }:
with lib;
let
options.services.rtl = {
enable = mkEnableOption "Ride The Lightning, a web interface for lnd and clightning";
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "HTTP server address.";
};
port = mkOption {
type = types.port;
default = 3000;
description = "HTTP server port.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/rtl";
description = "The data directory for RTL.";
};
nodes = {
clightning = {
enable = mkOption {
type = types.bool;
default = false;
description = "Enable the clightning node interface.";
};
extraConfig = mkOption {
type = with types; attrsOf anything;
default = {};
example = {
Settings.userPersona = "MERCHANT";
Settings.logLevel = "DEBUG";
};
description = ''
Extra clightning node configuration.
See here for all available options:
https://github.com/Ride-The-Lightning/RTL/blob/master/.github/docs/Application_configurations.md
'';
};
};
lnd = {
enable = mkOption {
type = types.bool;
default = false;
description = "Enable the lnd node interface.";
};
loop = mkOption {
type = types.bool;
default = false;
description = "Enable swaps with lightning-loop.";
};
extraConfig = mkOption {
type = with types; attrsOf anything;
default = {};
example = {
Settings.userPersona = "MERCHANT";
Settings.logLevel = "DEBUG";
};
description = ''
Extra lnd node configuration.
See here for all available options:
https://github.com/Ride-The-Lightning/RTL/blob/master/.github/docs/Application_configurations.md
'';
};
};
reverseOrder = mkOption {
type = types.bool;
default = false;
description = ''
Reverse the order of nodes shown in the UI.
By default, clightning is shown before lnd.
'';
};
};
nightTheme = mkOption {
type = types.bool;
default = false;
description = "Enable the Night UI Theme.";
};
extraCurrency = mkOption {
type = with types; nullOr str;
default = null;
example = "USD";
description = ''
Currency code (ISO 4217) of the extra currency used for displaying balances.
When set, this option enables online currency rate fetching.
Warning: Rate fetching requires outgoing clearnet connections, so option
{option}`tor.enforce` is automatically disabled.
'';
};
user = mkOption {
type = types.str;
default = "rtl";
description = "The user as which to run RTL.";
};
group = mkOption {
type = types.str;
default = cfg.user;
description = "The group as which to run RTL.";
};
tor.enforce = nbLib.tor.enforce;
};
cfg = config.services.rtl;
nbLib = config.nix-bitcoin.lib;
nbPkgs = config.nix-bitcoin.pkgs;
secretsDir = config.nix-bitcoin.secretsDir;
runePath = "${cfg.dataDir}/clightning-admin-rune";
inherit (nbLib) optionalAttr;
node = { isLnd, index }: {
inherit index;
lnNode = "Node";
lnImplementation = if isLnd then "LND" else "CLT";
Authentication = {
${optionalAttr (isLnd && lndLoopEnabled) "swapMacaroonPath"} = "${lightning-loop.dataDir}/${bitcoind.network}";
${optionalAttr (isLnd) "macaroonPath"} = "${cfg.dataDir}/macaroons";
${optionalAttr (!isLnd) "runePath"} = runePath;
};
Settings = {
userPersona = "OPERATOR";
themeMode = if cfg.nightTheme then "NIGHT" else "DAY";
themeColor = "PURPLE";
${optionalAttr isLnd "channelBackupPath"} = "${cfg.dataDir}/backup/lnd";
logLevel = "INFO";
fiatConversion = cfg.extraCurrency != null;
${optionalAttr (cfg.extraCurrency != null) "currencyUnit"} = cfg.extraCurrency;
${optionalAttr (isLnd && lndLoopEnabled) "swapServerUrl"} =
"https://${nbLib.addressWithPort lightning-loop.restAddress lightning-loop.restPort}";
lnServerUrl = "https://${
if isLnd
then nbLib.addressWithPort lnd.restAddress lnd.restPort
else nbLib.addressWithPort clightning.plugins.clnrest.address clightning.plugins.clnrest.port
}";
};
};
nodes' =
optional cfg.nodes.clightning.enable
(recursiveUpdate (node { isLnd = false; index = 1; }) cfg.nodes.clightning.extraConfig) ++
optional cfg.nodes.lnd.enable
(recursiveUpdate (node { isLnd = true; index = 2; }) cfg.nodes.lnd.extraConfig);
nodes = if cfg.nodes.reverseOrder then reverseList nodes' else nodes';
rtlConfig = {
multiPass = "@multiPass@";
host = cfg.address;
port = cfg.port;
SSO.rtlSSO = 0;
inherit nodes;
};
configFile = builtins.toFile "config" (builtins.toJSON rtlConfig);
inherit (config.services)
bitcoind
lnd
clightning
lightning-loop;
lndLoopEnabled = cfg.nodes.lnd.enable && cfg.nodes.lnd.loop;
in {
inherit options;
config = mkIf cfg.enable {
assertions = [
{ assertion = cfg.nodes.clightning.enable || cfg.nodes.lnd.enable;
message = ''
RTL: At least one of `nodes.lnd.enable` or `nodes.clightning.enable` must be `true`.
'';
}
];
services.lnd.enable = mkIf cfg.nodes.lnd.enable true;
services.lightning-loop.enable = mkIf lndLoopEnabled true;
services.clightning = mkIf cfg.nodes.clightning.enable {
enable = true;
plugins.clnrest.enable = true;
};
systemd.tmpfiles.rules = [
"d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group} - -"
];
services.rtl.tor.enforce = mkIf (cfg.extraCurrency != null) false;
systemd.services.rtl = rec {
wantedBy = [ "multi-user.target" ];
wants = optional cfg.nodes.clightning.enable "clightning.service" ++
optional cfg.nodes.lnd.enable "lnd.service";
after = wants ++ [ "nix-bitcoin-secrets.target" ];
environment.RTL_CONFIG_PATH = cfg.dataDir;
environment.DB_DIRECTORY_PATH = cfg.dataDir;
serviceConfig = nbLib.defaultHardening // {
ExecStartPre = [
(nbLib.script "rtl-setup-config" ''
<${configFile} sed "s|@multiPass@|$(cat ${secretsDir}/rtl-password)|" \
> '${cfg.dataDir}/RTL-Config.json'
'')
]
++ optional cfg.nodes.lnd.enable
# The lnd admin macaroon is not readable by group `lnd`, so copy it
(nbLib.rootScript "rtl-copy-macaroon" ''
install --compare -m 640 -o ${cfg.user} -g ${cfg.group} -D ${lnd.networkDir}/admin.macaroon \
'${cfg.dataDir}/macaroons/admin.macaroon'
'')
++ optional cfg.nodes.clightning.enable
(nbLib.rootScript "rtl-create-clnrest-rune-file" ''
rune=$(cat '${clightning.networkDir}/admin-rune')
install --compare -m 640 -o ${cfg.user} -g ${cfg.group} <(printf 'LIGHTNING_RUNE="%s"\n' "$rune") '${runePath}'
'');
ExecStart = "${nbPkgs.rtl}/bin/rtl";
# Show "rtl" instead of "node" in the journal
SyslogIdentifier = "rtl";
User = cfg.user;
Restart = "on-failure";
RestartSec = "10s";
ReadWritePaths = [ cfg.dataDir ];
} // nbLib.allowedIPAddresses cfg.tor.enforce
// nbLib.nodejs;
};
users.users.${cfg.user} = {
isSystemUser = true;
group = cfg.group;
extraGroups = optional lndLoopEnabled lnd.group;
};
users.groups.${cfg.group} = {};
nix-bitcoin.secrets.rtl-password.user = cfg.user;
nix-bitcoin.generateSecretsCmds.rtl = ''
makePasswordSecret rtl-password
'';
};
}
-8
View File
@@ -35,14 +35,6 @@ let
''; '';
}; };
# Currently, this is used only by ../deployment/nixops.nix
deployment.secretsDir = mkOption {
type = types.path;
description = ''
Directory of local secrets that are transferred to the nix-bitcoin node on deployment
'';
};
secrets = mkOption { secrets = mkOption {
default = {}; default = {};
type = with types; attrsOf (submodule ( type = with types; attrsOf (submodule (

Some files were not shown because too many files have changed in this diff Show More