commit 56a613eabafcd216444ab09dd19840ecf7cde0c8 Author: ai-bot Date: Sat Nov 14 11:52:48 2026 +0000 docs: add Skuld specification and handover diff --git a/docs/spec.md b/docs/spec.md new file mode 100644 index 0000000..985b93c --- /dev/null +++ b/docs/spec.md @@ -0,0 +1,684 @@ +# Skuld — specification and handover + +Skuld is a self-hosted web app that keeps a Bitcoin transaction ledger and computes the +Norwegian tax figures for a tax year: **formue**, **gevinst**, **tap** and **inntekt**. It +replaces a spreadsheet that has one sheet per exchange/wallet plus a main sheet of holdings. + +This document is the reference the coding agent implements against. `docs/TODO.md` is the +ordered work plan; this file is the contract. + +Status: phase 1 scope, agreed with the owner. Phase 2 (PHP + NOSTR) is specified in §12 but is +not part of this plan. + +--- + +## 1. Deliveries + +**Phase 1 — StartOS service package (this plan).** + +- Runs as a StartOS service: one Docker image, one daemon, one SQLite database on the `main` + volume. +- Admin-password protected, single user. +- UI in Norwegian Nynorsk. +- Implemented with the Python standard library only (no third-party packages), like the + author's earlier app VardKey. The HTTP server, the SQLite access, the password hashing and + the CSV export are all standard library. + +**Phase 2 — PHP version on a shared web host (later, not in this plan).** + +Same data model, same tax rules, PHP + SQLite/MySQL, login with NOSTR instead of a password. +See §12. The point of specifying it now is that phase 1 must keep the tax logic out of +Python-only structures: the rules and the schema below are the shared contract. + +--- + +## 2. Language rules + +This app is a deliberate exception to the "everything in the repository is English" rule. + +| Artefact | Language | +| --- | --- | +| Code, identifiers, comments, commit messages | English | +| `README.md`, `AGENTS.md`, `docs/*.md` | English | +| End-user UI text, form labels, validation messages shown to the user | Norwegian Nynorsk | +| `instructions.md` (end-user documentation for the StartOS package) | Norwegian Nynorsk | +| Strings inside `startos/i18n/dictionaries/` (what StartOS shows) | Norwegian Nynorsk | + +Never translate user-facing text to English. Never write code identifiers in Norwegian. + +Formatting: amounts as `1 234 567,89 kr` (space as thousands separator, comma as decimal +separator), dates as `31.12.2025` in the UI, `YYYY-MM-DD` in the database and the API. The +storage layer holds BTC as integer **sats** and NOK as integer **øre**; floating point is never +used for money. The one exception is the display of a BTC price in NOK, which is converted to +øre on input. + +--- + +## 3. Domain rules implemented + +Rules below are what Skuld calculates. Sources in §14. + +### 3.1 Realization (utgangsverdi − inngangsverdi) + +These events are realizations and produce a gain or a loss: + +| Event in Skuld | Proceeds (utgangsverdi) | Cost (inngangsverdi) | +| --- | --- | --- | +| `trade` where BTC leaves the account | NOK received | cost of the consumed lots | +| `spend` (paid for goods/services with BTC) | NOK value of what was bought | cost of the consumed lots | +| `loss` (coins definitively lost) | 0 | cost of the consumed lots | + +Gain = proceeds − cost. Loss = cost − proceeds. Realized in NOK at the transaction date. +Fees follow §3.2. + +### 3.2 Fees (avgift) + +A fee is entered on every transaction as an amount plus a currency (sats or NOK). Applied as: + +| Transaction | Fee in NOK | Fee in sats | +| --- | --- | --- | +| `trade` (buy) | added to the cost of the new lot | reduces the sats received; cost unchanged | +| `trade` (sell), `spend` | subtracted from the proceeds | increases the sats consumed at the same cost | +| `income` | subtracted from the taxable income value | reduces the sats received; income value unchanged | +| `transfer_out` | added to the cost of the destination lot | reduces the sats that arrive | +| `gift_received` | added to the cost of the new lot | reduces the sats received | +| `loss`, `gift_given`, `admin_cost` | no effect beyond being recorded | recorded, sats already leave the account | + +A fee that cannot be documented is not deductible, but Skuld does not try to judge that: it +applies every fee it is given and the owner decides what to enter. + +### 3.3 Internal transfers + +`transfer_out` from account A to account B is **not** a realization. The consumed lots of A are +mirrored as new lots in B, keeping the original acquisition date and cost, plus the transfer +fee. A `transfer_in` row is generated automatically in B (see §7.4). + +### 3.4 Income + +`income` (mining, interest, received as payment, airdrop) is taxable income at the NOK value on +the receipt date. That same value becomes the cost basis of the new lot. Two separate tax +events: income on receipt, and a later realization when the coins are sold. + +### 3.5 Formue (wealth) + +Holdings at 31 December × the year-end rate. Virtual assets are valued at full market value — +there is no valuation discount. The rate Skatteetaten publishes is "kurs per 1.1" of the +following year, so tax year 2025 uses the rate dated 2026-01-01. Skuld seeds the published BTC +rates (§5.3) and lets the owner override any of them. + +### 3.6 Rates and thresholds + +Gain is taxed at 22 %, losses are deductible at 22 %. No minimum threshold, no exemption +method, no uplift factor. The rate is a setting, not a constant. + +Wealth tax is **off by default**: Skuld reports the formue figure and, if the owner switches +`wealth_tax_enabled` on, subtracts a configurable threshold and applies a configurable rate. +Skuld does not claim to know the current thresholds. + +### 3.7 Cost basis method + +Norway does **not** require FIFO for virtual assets, so the method is a setting: +`FIFO` (default), `LIFO`, `HIFO`. In addition the owner may pick specific lots by hand (§5.2). +The method is bound per account and per year: the report uses the method stored in the +settings for that year, and the report page shows which method produced the figures. + +### 3.8 Non-taxable accounts + +An account (`market`) has a `taxable` flag. Accounts for children or other people are entered +with `taxable = 0`: their transactions keep a complete ledger and their coins appear in the +holdings and in the reconciliation rows, but every transaction on them is excluded from the +tax figures. The per-transaction `taxable` flag defaults to the account's flag and can be +overridden per transaction (checkbox in the form, ticked by default). + +### 3.9 Gifts + +- **Gift received** (`gift_received`): not income. The NOK value entered ("Pris") is the cost + basis of the new lot. +- **Gift given** (`gift_given`): the coins and their cost basis leave the ledger. Skuld books + no gain and no deduction for the giver (assumption of continuity for the recipient). See open + question Q1. + +### 3.10 Forvaltningskostnad (admin cost) + +`admin_cost` is recorded, consumes lots when paid in sats, and is shown as its own line. It is +deducted from the taxable base only when the setting `deduct_admin_costs` is on (default off). +See open question Q2. + +--- + +## 4. Data model + +SQLite, one file, on the `main` volume. Schema lives in `database.py` as one versioned +migration list, and the same DDL is reproduced here so phase 2 can reuse it verbatim. + +```sql +CREATE TABLE IF NOT EXISTS schema_version ( + version INTEGER NOT NULL +); + +CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS admin ( + id INTEGER PRIMARY KEY CHECK (id = 1), + username TEXT NOT NULL, + password_hash TEXT NOT NULL, + salt TEXT NOT NULL, + iterations INTEGER NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS sessions ( + token_hash TEXT PRIMARY KEY, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL +); + +-- An account the owner holds coins on: an exchange, a wallet, or a non-taxable +-- account belonging to someone else. +CREATE TABLE IF NOT EXISTS markets ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL CHECK (kind IN ('exchange', 'wallet', 'other')), + taxable INTEGER NOT NULL DEFAULT 1 CHECK (taxable IN (0, 1)), + custody_market_id INTEGER REFERENCES markets(id), + note TEXT NOT NULL DEFAULT '', + sort_order INTEGER NOT NULL DEFAULT 0, + archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1)) +); + +-- NOK per 1 BTC at a year-end date, in ore. date is the 1 January of the year the +-- rate belongs to, e.g. '2026-01-01' is the rate for tax year 2025. +CREATE TABLE IF NOT EXISTS prices ( + asset TEXT NOT NULL DEFAULT 'BTC', + date TEXT NOT NULL, + nok_per_btc_ore INTEGER NOT NULL, + source TEXT NOT NULL DEFAULT '', + PRIMARY KEY (asset, date) +); + +CREATE TABLE IF NOT EXISTS transactions ( + id INTEGER PRIMARY KEY, + date TEXT NOT NULL, + type TEXT NOT NULL CHECK (type IN ( + 'trade', 'income', 'spend', 'loss', + 'transfer_out', 'transfer_in', + 'gift_received', 'gift_given', 'admin_cost')), + market_id INTEGER NOT NULL REFERENCES markets(id), + taxable INTEGER NOT NULL DEFAULT 1 CHECK (taxable IN (0, 1)), + note TEXT NOT NULL DEFAULT '', + -- leg_in = what the account receives, leg_out = what the account gives up. + -- Exactly one of the two columns of a leg is non-null; a leg may be absent. + leg_in_sats INTEGER, + leg_in_ore INTEGER, + leg_out_sats INTEGER, + leg_out_ore INTEGER, + -- NOK value of the BTC leg where no leg carries it: income, spend proceeds, + -- gift received, and (for documentation only) a loss. + value_ore INTEGER, + fee_sats INTEGER NOT NULL DEFAULT 0, + fee_ore INTEGER NOT NULL DEFAULT 0, + to_market_id INTEGER REFERENCES markets(id), + transfer_group TEXT, + generated INTEGER NOT NULL DEFAULT 0 CHECK (generated IN (0, 1)), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + CHECK (leg_in_sats IS NULL OR leg_in_ore IS NULL), + CHECK (leg_out_sats IS NULL OR leg_out_ore IS NULL), + CHECK (leg_in_sats IS NULL OR leg_in_sats > 0), + CHECK (leg_out_sats IS NULL OR leg_out_sats > 0) +); + +-- A lot is a quantity of sats with one acquisition date and one cost basis. +CREATE TABLE IF NOT EXISTS lots ( + id INTEGER PRIMARY KEY, + market_id INTEGER NOT NULL REFERENCES markets(id), + acquired_date TEXT NOT NULL, + origin_tx_id INTEGER REFERENCES transactions(id), + source_lot_id INTEGER REFERENCES lots(id), + origin_seq INTEGER NOT NULL DEFAULT 0, + sats_original INTEGER NOT NULL, + sats_remaining INTEGER NOT NULL, + cost_ore_original INTEGER NOT NULL, + cost_ore_remaining INTEGER NOT NULL, + note TEXT NOT NULL DEFAULT '' +); + +-- Which lots an outgoing transaction consumed. auto = 0 means the owner picked it. +CREATE TABLE IF NOT EXISTS lot_consumptions ( + id INTEGER PRIMARY KEY, + tx_id INTEGER NOT NULL REFERENCES transactions(id) ON DELETE CASCADE, + lot_id INTEGER NOT NULL REFERENCES lots(id), + sats INTEGER NOT NULL, + cost_ore INTEGER NOT NULL, + auto INTEGER NOT NULL DEFAULT 1 CHECK (auto IN (0, 1)) +); + +-- A hand-picked lot selection, stored by origin so it survives a ledger rebuild. +CREATE TABLE IF NOT EXISTS lot_picks ( + id INTEGER PRIMARY KEY, + tx_id INTEGER NOT NULL REFERENCES transactions(id) ON DELETE CASCADE, + origin_tx_id INTEGER NOT NULL, + origin_seq INTEGER NOT NULL DEFAULT 0, + sats INTEGER NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_tx_date ON transactions(date); +CREATE INDEX IF NOT EXISTS idx_tx_market ON transactions(market_id, date); +CREATE INDEX IF NOT EXISTS idx_lot_market ON lots(market_id, acquired_date); +CREATE INDEX IF NOT EXISTS idx_cons_tx ON lot_consumptions(tx_id); +CREATE INDEX IF NOT EXISTS idx_cons_lot ON lot_consumptions(lot_id); +``` + +Notes on the model: + +- `markets` is the spreadsheet's "ark": one row per exchange, wallet or other person's + account. `custody_market_id` is where the coins physically sit when that differs from the + account that owns them (a child's coins on your exchange), which is what the spreadsheet's + `TOT` rows reconcile. +- Amounts are integers. Sats are sats; NOK is øre. +- A transaction's `taxable` flag defaults to its account's flag. + +### 4.1 Settings keys + +| Key | Default | Meaning | +| --- | --- | --- | +| `tax_rate_percent` | `22` | Rate on net gain | +| `lot_method` | `FIFO` | `FIFO`, `LIFO` or `HIFO` | +| `wealth_tax_enabled` | `0` | Whether to compute wealth tax | +| `wealth_tax_threshold_ore` | `0` | Deducted before the wealth tax rate | +| `wealth_tax_rate_percent` | `0` | Wealth tax rate | +| `deduct_admin_costs` | `0` | Deduct `admin_cost` from the taxable base | +| `year_end_price_source` | `Skatteetaten` | Shown in the report, free text | + +--- + +## 5. The lot ledger + +Every incoming quantity of BTC becomes a **lot**: sats, acquisition date, cost basis in øre, +and the account it sits in. Every outgoing quantity consumes sats from one or more lots and +records what it consumed. This is deliberately UTXO-like: the owner can point at the earlier +transactions that a sale or a transfer uses, exactly as they would point at UTXOs. + +### 5.1 Which transactions create lots + +| Transaction | Lot created | +| --- | --- | +| `trade` with `leg_in_sats` | one lot: sats = leg_in_sats − fee_sats, cost = leg_in_ore (the NOK paid) + fee_ore | +| `income` | one lot: sats = leg_in_sats − fee_sats, cost = value_ore − fee_ore | +| `gift_received` | one lot: sats = leg_in_sats − fee_sats, cost = value_ore + fee_ore | +| `transfer_in` | one lot per consumed source part: sats = part − fee_sats, cost = part cost + fee_ore, `acquired_date` and `source_lot_id` from the source lot | + +### 5.2 Which transactions consume lots + +`trade` with `leg_out_sats`, `spend`, `loss`, `transfer_out`, `gift_given`, and `admin_cost` +when it is paid in sats. The sats to consume are `leg_out_sats` plus `fee_sats` where §3.2 says +the fee is paid in sats. + +Consumption order: + +1. Hand-picked lots first (`lot_picks`), in the order the owner listed them, oldest pick first. +2. The remainder from the remaining lots of the same account, by the `lot_method` setting: + - `FIFO`: earliest `acquired_date` first, ties broken by lowest lot id. + - `LIFO`: latest `acquired_date` first, ties broken by highest lot id. + - `HIFO`: highest cost per sat first, ties broken by earliest `acquired_date`. + +If the account does not hold enough sats, the save is rejected with a validation error naming +the shortfall in sats. Skuld never invents coins. + +### 5.3 Partial consumption and rounding + +Consuming `n` of a lot's `sats_remaining` takes +`cost_ore = round(cost_ore_remaining * n / sats_remaining)`, and both remainders are reduced by +that amount, so the last sat consumed always takes exactly what is left. No øre is created or +lost by the ledger. + +### 5.4 Rebuild + +`ledger.rebuild()` recomputes every lot and every auto consumption from scratch: + +1. Delete all rows of `lots` and all rows of `lot_consumptions` where `auto = 1`. +2. Replay the transactions ordered by `(date, id)`. +3. For each transaction, apply §5.1 and §5.2. Hand-picked selections are read from `lot_picks` + and re-resolved by `(origin_tx_id, origin_seq)`. + +`rebuild()` runs after any write that can change the ledger: creating, editing or deleting a +transaction, editing a market's `taxable` flag, or changing `lot_method`. It is idempotent and +must produce identical rows when run twice. + +Seeded rates. `prices` is seeded on first run with the BTC year-end rates Skatteetaten has +published, in øre per BTC: + +| Date (1 January) | Tax year | NOK per BTC | +| --- | --- | --- | +| 2021-01-01 | 2020 | 247 318,91 | +| 2022-01-01 | 2021 | 408 469,55 | +| 2023-01-01 | 2022 | 162 831,43 | +| 2024-01-01 | 2023 | 435 486,47 | +| 2025-01-01 | 2024 | 1 060 374,89 | +| 2026-01-01 | 2025 | 881 206,06 | + +--- + +## 6. The year report + +`GET /api/report?year=YYYY` returns everything below. The UI page `/rapport` renders it and +`/api/report/export.csv?year=YYYY` downloads it. + +### 6.1 Per account (taxable accounts only) + +| Column | Definition | +| --- | --- | +| `name` | account name | +| `share_percent` | this account's sats at year end ÷ total sats at year end of all taxable accounts × 100 | +| `sats` | sats held at 31.12.YYYY | +| `formue_ore` | `sats` × the year-end rate for tax year YYYY | +| `gevinst_ore` | sum of gains from realizations dated in YYYY on this account | +| `tap_ore` | sum of losses from realizations dated in YYYY on this account | +| `brukt_ore` | cost basis consumed by those realizations (inngangsverdi) | +| `gevinst_percent` | `gevinst_ore ÷ brukt_ore` × 100, `0` when `brukt_ore` is 0 | + +### 6.2 Totals and tax + +| Field | Definition | +| --- | --- | +| `formue_ore` | sum over taxable accounts | +| `gevinst_ore`, `tap_ore`, `brukt_ore` | sums over taxable accounts | +| `netto_ore` | `gevinst_ore` − `tap_ore` | +| `inntekt_ore` | sum of `value_ore − fee_ore` of `income` transactions dated in YYYY on taxable accounts | +| `skatt_ore` | `max(netto_ore, 0)` × `tax_rate_percent` | +| `formuesskatt_ore` | only when `wealth_tax_enabled`: `max(formue_ore − wealth_tax_threshold_ore, 0)` × `wealth_tax_rate_percent` | +| `admin_cost_ore` | sum of `admin_cost` on taxable accounts, deducted from `netto_ore` only when `deduct_admin_costs` is on | +| `lot_method` | the method that produced these figures | + +The report also carries a `skattemelding` block with the four figures the owner types into the +tax return: `formue`, `gevinst`, `tap`, `inntekt`, each with the accounts included and a note +that non-taxable accounts are excluded. + +### 6.3 Reconciliation rows and non-taxable accounts + +- `non_taxable`: one row per non-taxable account with `sats` at year end and the year's + `gevinst_ore`/`tap_ore` for information only. Nothing here enters any total. +- `custody_totals`: one row per account that has other accounts' coins in custody, with + `sats` = its own sats + the sats of every account whose `custody_market_id` points at it. + This is the spreadsheet's `TOT` row. + +### 6.4 Worked example (golden test) + +The test suite must assert these numbers. + +Transactions, all on account `Børs_01`: + +| Date | Type | Details | +| --- | --- | --- | +| 2024-01-10 | trade (buy) | 1,0 BTC for 200 000 kr | +| 2024-04-10 | trade (buy) | 1,0 BTC for 500 000 kr | +| 2024-08-10 | trade (buy) | 0,5 BTC for 200 000 kr | +| 2024-11-10 | trade (sell) | 1,0 BTC for 500 000 kr, fee 5 000 kr | + +Proceeds: 500 000 − 5 000 = 495 000 kr. + +| Method | Consumed | Cost | Gevinst | +| --- | --- | --- | --- | +| FIFO | 1,0 BTC from January | 200 000 kr | 295 000 kr | +| LIFO | 0,5 BTC from August + 0,5 BTC from April | 450 000 kr | 45 000 kr | +| HIFO | 1,0 BTC from April (highest cost per BTC) | 500 000 kr | −5 000 kr (loss) | + +Holdings after the sale: 1,5 BTC. With a year-end rate of 700 000 kr/BTC the formue is +1 050 000 kr, and with `tax_rate_percent = 22` the tax on the FIFO gain is 64 900 kr. + +--- + +## 7. User interface + +Nynorsk throughout. One page per task, no client-side framework: plain HTML, one `app.js` that +talks to the JSON API, one `style.css`. Every page is a static file under `static/` that the +server reads from disk; the server renders nothing but JSON. + +### 7.1 Pages + +| Path | Page | Content | +| --- | --- | --- | +| `/login` | Logg inn | Sign in, or create the admin on first run | +| `/` | Hovudark | The main sheet: one row per taxable account, the totals row, the non-taxable accounts, the `TOT` rows. Year selector. "Ny transaksjon" button. | +| `/transaksjonar` | Transaksjonar | Filterable list (year, account, type), edit and delete | +| `/transaksjon` | Transaksjon | The form, new or existing (`?id=`) | +| `/marknader` | Marknader og kontoar | Account admin: name, kind, taxable, custody account, note, order | +| `/rapport` | Skattegrunnlag | The year report, the tax return figures, CSV download | +| `/innstillingar` | Innstillingar | Method, tax rate, wealth tax, prices, admin password | + +### 7.2 The main sheet (`/`) + +Columns, in this order and with these headings: + +| Heading | Source | +| --- | --- | +| (account name) | `markets.name` | +| Behaldning | `share_percent`, shown as a percentage | +| Antall | `sats`, shown in BTC with 8 decimals | +| Formue | `formue_ore` | +| Gevinst | `gevinst_ore`, `-` when zero | +| Tap | `tap_ore`, `-` when zero | +| Brukt | `brukt_ore` | +| Gevinst % | `gevinst_percent` | + +Order of the rows: the totals row first (as in the spreadsheet), then the taxable accounts by +`sort_order`, then a blank line, then one row per non-taxable account showing only `Antall`, +then a blank line, then one `TOT ` row per account that has custody of other accounts' +coins, showing only `Antall`. A legend under the table explains that `TOT` rows are physical +counts for reconciliation and are not part of any total. + +### 7.3 The transaction form + +Field order follows the owner's spreadsheet: **Generelt**, then the type-specific fields, then +**Avgift**, then **Anna**. + +- **Generelt**: Dato (`YYYY-MM-DD`, required), Type (required). +- **Type**: `Handel`, `Inntekt`, `Forbruk`, `Tap`, `Overføring ut`, `Gåve (motteke)`, + `Gåve (gjeven)`, `Forvaltningskostnad`. `Overføring inn` is **not** selectable: it is + generated. A transaction that already exists as a generated `transfer_in` can only be viewed + and deleted together with its `transfer_out`. +- **Skattepliktig transaksjon**: one checkbox, ticked by default, pre-filled from the account's + flag, with the help text "Ta bort krysset for kontoar du fører for andre". +- **Type-specific fields**, each an amount plus a currency selector where the currency is + selectable: + +| Type | Fields | +| --- | --- | +| Handel | Kjøp: Antall, Valuta (sats/NOK). Salg/kostnad: Antall, Valuta (sats/NOK). Exactly one leg must be sats and the other NOK. | +| Inntekt | Inntekt/gevinst: Antall, Valuta (sats). Pris: Antall, Valuta (NOK). | +| Forbruk | Forbruk: Antall, Valuta (sats). Utgangsverdi: Antall, Valuta (NOK). | +| Tap | Tap: Antall, Valuta (sats). Pris: Antall, Valuta (NOK, valfri, berre dokumentasjon). | +| Overføring ut | Sendt: Antall, Valuta (sats). Til: account selector. | +| Gåve (motteke) | Motteke gåve: Antall, Valuta (sats). Pris: Antall, Valuta (NOK). | +| Gåve (gjeven) | Gjeven gåve: Antall, Valuta (sats). | +| Forvaltningskostnad | Kostnad: Antall, Valuta (sats/NOK). | + +- **Avgift**: Antall (valfri) + Valuta (sats/NOK), with a one-line explanation that a buy fee + raises the cost basis and a sell fee lowers the proceeds. +- **Anna**: Marknad (account selector, required), Notat (valfri). +- When the type consumes sats, the form shows a **Parti** (lots) section listing the candidate + lots of the account, each with acquisition date, remaining sats and cost per sat, with the + method's automatic pick pre-selected and the possibility to tick other lots or change the + amounts. A "Bruk automatisk" button restores the method's pick. +- Validation errors are shown inline, in Nynorsk, next to the field they belong to. + +### 7.4 The generated transfer + +Saving a `transfer_out` writes, in one transaction: + +1. the `transfer_out` row, with `transfer_group` set to a new UUID and `to_market_id`; +2. the consumed lots on the source account; +3. the mirrored lots on the destination account; +4. a `transfer_in` row on the destination account with `generated = 1`, the same date, the same + `transfer_group`, `leg_in_sats` = the sats that arrived (after a sats fee), and `taxable` + copied from the `transfer_out`. + +Editing or deleting the `transfer_out` regenerates or deletes the `transfer_in` and rebuilds +the ledger. The `transfer_in` is read-only in the UI. + +### 7.5 Empty state + +With no accounts, `/` shows a short Nynorsk explanation and a link to `/marknader`, and the +first-run flow after creating the admin goes straight to `/marknader`. A year with no +transactions shows the report with zeroes rather than an error. + +--- + +## 8. HTTP API + +All responses are JSON. All `/api/*` routes except the auth routes require a session and the +CSRF header. Errors are `{"error": "", "field": ""}` with +400 for validation, 401 for no session, 404 for unknown id. + +| Method | Path | Purpose | +| --- | --- | --- | +| GET | `/health` | `{"status":"ok"}`, unauthenticated, used by the StartOS readiness check | +| GET | `/api/auth/state` | `{"admin_exists": bool, "authenticated": bool, "username": string|null}` | +| POST | `/api/auth/setup` | Create the first admin: `{username, password}` | +| POST | `/api/auth/login` | `{username, password}` → sets the session cookie | +| POST | `/api/auth/logout` | Clears the session | +| POST | `/api/auth/password` | `{current_password, new_password}` | +| GET | `/api/markets` | List accounts, with `taxable`, `custody_market_id`, sats on hand | +| POST | `/api/markets` | Create | +| PATCH | `/api/markets/{id}` | Update | +| DELETE | `/api/markets/{id}` | Refuse with 400 when the account has transactions | +| GET | `/api/transactions?year=&market_id=&type=` | List, newest first | +| GET | `/api/transactions/{id}` | One transaction, with its consumptions and candidate lots | +| POST | `/api/transactions` | Create, plus `lot_picks` | +| PATCH | `/api/transactions/{id}` | Update, plus `lot_picks` | +| DELETE | `/api/transactions/{id}` | Delete (a `transfer_out` deletes its pair) | +| GET | `/api/lots?market_id=` | Lots with `sats_remaining`, cost per sat, origin transaction | +| GET | `/api/report?year=` | The year report of §6 | +| GET | `/api/report/export.csv?year=` | CSV of the report and the year's transactions | +| GET | `/api/prices` | The rate table | +| PUT | `/api/prices/{date}` | Set or override a rate | +| GET | `/api/settings` | All settings | +| PATCH | `/api/settings` | Update settings, then rebuild the ledger if `lot_method` changed | + +`POST`/`PATCH` accept `lot_picks` as a list of `{origin_tx_id, origin_seq, sats}`. Omitted or +empty means "use the method". + +The CSV export is a plain semicolon-separated file with a UTF-8 BOM so it opens correctly in a +Norwegian Excel: one block of report rows, then one block of the year's transactions with the +consumed cost per transaction. + +--- + +## 9. Authentication and security + +Adapted from the author's VardKey app, which is the reference implementation for this pattern: + +- First run creates the admin: username and a password of at least 12 characters, hashed with + `hashlib.pbkdf2_hmac('sha256', ...)` with a random 16-byte salt and an iteration count stored + in the row, compared with `hmac.compare_digest`. +- The session is a random 32-byte token in an `HttpOnly`, `SameSite=Strict` cookie; only the + SHA-256 hash of the token is stored, with an expiry. Expired rows are deleted on use. +- Every mutating request needs the `X-CSRF-Token` header, which equals the session's CSRF + secret; the check runs before the handler. `static/session.js` patches `window.fetch` to add + the header on every same-origin call. +- Unauthenticated `/api/*` answers 401; every page except `/login` redirects to `/login`. +- The StartOS package adds two actions and one task so the admin can be managed without the + web UI, exactly as VardKey does: `set-admin-password` (generates the password inside the + container and prints it once) and `delete-all-data` (wipes every table except `admin` and + `settings`), plus an init-script task that recommends `set-admin-password` while no admin + exists. Both actions run `maintenance.py` in a `withTemp` subcontainer. +- No wallet secrets. Skuld never asks for a seed phrase, a private key or an xpub. A free-text + guard is **not** copied from VardKey: Skuld has no field where a wallet secret would belong. +- The database is not encrypted. StartOS disk encryption and volume access control are what + protect it. This is stated in `instructions.md`. + +--- + +## 10. StartOS package + +Mirror the shape of the author's VardKey package (`github.com/sondreolav/vardkey`), which is a +conformant package for the same SDK. The coder must fetch that repository and copy the *shape*, +not the domain code. + +| Item | Value | +| --- | --- | +| `package_id` | `skuld` | +| Image | built from this repository's `Dockerfile` (`dockerBuild: {}` in the manifest) | +| Architectures | `x86_64`, `aarch64` | +| Subcontainer | `skuld-sub`, one daemon named `primary`, `python3 app.py` | +| Volume | `main`, mounted writable at `/data` | +| Database | `/data/skuld.sqlite3`, passed in as `DATABASE_PATH` | +| Port | `8080` inside the container, as `PORT`; `utils.ts`, `main.ts` and `interfaces.ts` must name the same number | +| Interface | `ui`, type `ui`, port 8080, `preferredExternalPort: 80` | +| Dependencies | none | +| Health check | readiness check named `primary`, displayed "Web Interface", `checkWebUrl` against `http://127.0.0.1:8080/health` | +| Backups | `sdk.Backups.ofVolumes('main')` | +| Actions | `set-admin-password`, `delete-all-data` | +| Task | recommended `set-admin-password` while no admin exists | +| Icon | `icon.svg` at the repository root, under 40 KiB | + +The image is a slim Python base, the app needs no packages beyond the standard library, and the +Dockerfile declares no `USER` because the `main` volume must be writable without a `chown`. + +--- + +## 11. Out of scope for phase 1 + +Deliberately excluded. Do not add them, and do not add abstraction for them: + +- Any asset other than BTC. The ledger stores sats only. +- Live price feeds, exchange-rate APIs and exchange CSV import. Prices are entered by hand. +- Multiple users, sharing, or per-user data separation. +- Encryption of the database, and any wallet-secret handling. +- Charts, dashboards, projections and tax optimisation. +- NOSTR login and the PHP version (§12). +- Migration of the owner's existing spreadsheet. The owner enters the history by hand, so the + import path is the form, not a file reader. + +--- + +## 12. Phase 2 — PHP version with NOSTR login (later, not in this plan) + +Requirements to keep in mind while building phase 1, so the port is mechanical: + +- The same schema, unchanged, and the same calculation rules. No rule may live only in Python: + the DDL in §4 and the rules in §3, §5 and §6 are the contract. Ship the DDL as a plain + `.sql` file in the repository as well, so the PHP port can apply it directly. +- PHP 8 with PDO. SQLite on the web host if the host allows file writes, otherwise MySQL with + the same column names and types. +- Login with NOSTR instead of a password: the browser signs a challenge with a NIP-07 extension + (or a NIP-46 bunker) and the server verifies the Schnorr signature and binds the session to + the `npub`. All data is scoped by `npub`; the admin password and the `admin`/`sessions` tables + are replaced by an `accounts` table keyed on `npub`. +- Risk to settle before that work starts: PHP has no built-in secp256k1 Schnorr verification. + The options are a maintained PHP library, a PHP extension, or delegating verification. Decide + with a working proof of concept before writing the port. This is the only genuinely uncertain + part of phase 2. + +--- + +## 13. Open questions for the owner + +| Id | Question | What Skuld does until it is answered | +| --- | --- | --- | +| Q1 | Is giving BTC as a gift a realization for the giver, or does the recipient take over the cost basis (continuity)? | No gain and no deduction for the giver; the coins and their cost basis leave the ledger. The recipient's side is out of scope. | +| Q2 | Is `Forvaltningskostnad` deductible, and against what? | Recorded and shown as its own line, not deducted, until `deduct_admin_costs` is switched on. | +| Q3 | Should the loss in `Tap` use the consumed lots' cost basis (as built) or a NOK value the owner enters? | Cost basis from the lots; the entered price is stored as documentation only. | +| Q4 | Are the main-sheet columns `Brukt` and `Gevinst %` read as §6.1 defines them (cost basis consumed in the year, and gain ÷ that cost)? | As defined in §6.1; the owner corrects the definitions if the reading is wrong. | + +--- + +## 14. Sources + +- Skatteetaten, Virtuelle eiendeler (kryptovaluta med mer): + https://www.skatteetaten.no/person/skatt/hjelp-til-riktig-skatt/aksjer-og-verdipapirer/om/virtuell-valuta/ +- Skatteetaten, Formue — rapportere, fylle ut og dokumentere (year-end rates): + https://www.skatteetaten.no/person/skatt/hjelp-til-riktig-skatt/aksjer-og-verdipapirer/om/virtuell-valuta/formue/ +- Skatteetaten, Salg av virtuelle eiendeler: + https://www.skatteetaten.no/person/skatt/hjelp-til-riktig-skatt/aksjer-og-verdipapirer/om/virtuell-valuta/salg/ +- Kryptoforalle, Krypto i skattemeldingen (22 %, no FIFO requirement, fees, currency effects): + https://kryptoforalle.no/skatt/skattemelding +- StartOS packaging guide: https://docs.start9.com/packaging +- StartOS Hello World wrapper (package skeleton): + https://github.com/Start9Labs/hello-world-startos +- VardKey (same author; reference for the StartOS package shape and the admin password): + https://github.com/sondreolav/vardkey