# 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. Display and storage rules, in one place, because they are easy to get wrong: - **BTC is always shown in sats, never in BTC.** A quantity is a whole number with a space as the thousands separator: `1 500 000 sats`. No decimals, ever. The stored value is integer sats; the `10^8` conversion to BTC exists only inside the arithmetic that works out a price or a formue. - **NOK is always shown in whole kroner.** A displayed amount is a whole number with a space as the thousands separator and the unit `kr`: `1 000 000 kr`. No decimals, ever. - The stored value is integer **øre** and every calculation uses øre, so nothing is lost. The rounding happens only when a figure is written out, and it rounds halves up. - Decimals are accepted **only in an input field**: a NOK amount may be typed as `1 234,50` and is stored as `123450` øre. When a form is filled from a stored transaction, an input shows the exact stored value, decimals included, so that opening and saving a form cannot silently drop øre. A sats input takes whole sats and rejects a decimal. - Floating point is never used for money. - Dates: `31.12.2025` in the UI, `YYYY-MM-DD` in the database and the API. - The year-end rate is the one figure that is neither an amount nor a quantity. It is shown as `1 060 375 kr per BTC`, and the settings table heads it `NOK per BTC`. It is the rate of §3.5, not the price of a transaction; §7.3 defines the transaction price, which the UI calls **Bitcoin pris**. --- ## 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 in **sats only**. A kroner cost is not a fee in Skuld: the owner folds it into the inngangsverdi or the utgangsverdi of the transaction, that is into the amount they type, and Skuld never derives one from the other. | Transaction | Fee in sats | | --- | --- | | `trade` (buy) | reduces the sats received; the cost is unchanged, so the price per sat rises | | `trade` (sell), `spend` | increases the sats consumed at the same cost | | `income` | reduces the sats received; the income value is unchanged | | `transfer_out` | taken on top of what is sent: it increases the sats consumed at the source and never reduces what arrives | | `loss`, `gift_given` | recorded only, the sats already leave the account | The fee of a `transfer_out` is shown on the `transfer_out` alone. The generated `transfer_in` carries no fee at all (§3.3). `gift_received` and `admin_cost` take no fee. The fee section of the form is shown only for `trade`, `income`, `spend`, `loss`, `transfer_out` and `gift_given`, and a fee sent for any other type is rejected. 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. - What the owner types as `Sendt` is exactly what arrives: the generated `transfer_in` in B gets `leg_in_sats` equal to the sent amount, and no fee is ever subtracted from it. - A fee in sats is taken on top, at A. A loses the sent sats plus the fee, B gains the sent sats, and the fee sats leave the ledger altogether. - The lots of A that the transfer consumed are mirrored as lots of B, keeping the acquisition date and the cost per sat, so the bitcoin price of B's new lots is the price of the lots A gave up. - The mirrored lots cover exactly the sent amount. The share of the cost that belongs to the fee sats leaves the ledger with them: Skuld books no gain and no loss for a fee. - A `transfer_in` row is generated automatically in B and carries no fee (§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 a cost in **kroner** that stands on its own. It is not attached to any account (`market_id` is null), it consumes no lots, it changes no holdings, and it takes no fee. It is recorded with a date and a kroner amount, and it is shown as its own line in the report, in the CSV and on `/transaksjonar`. The report carries the year's sum as `admin_cost_ore`. It is subtracted from `netto_ore` 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')), -- Null only for admin_cost, which stands on its own (section 3.10). market_id INTEGER 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, -- Kept for compatibility and always 0: a fee is entered in sats only, and a -- kroner cost is folded into a leg by the owner (section 3.2). 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), -- admin_cost stands on its own, and two types take no fee (section 3.2). CHECK (type = 'admin_cost' OR market_id IS NOT NULL), CHECK (type NOT IN ('gift_received', 'admin_cost') OR (fee_sats = 0 AND fee_ore = 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. `admin_cost` has no account, so its flag comes from the form and defaults to ticked. ### 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 = the kroner that left the account (`leg_out_ore`, or `leg_in_ore` when the kroner is on the other side) | | `income` | one lot: sats = leg_in_sats − fee_sats, cost = value_ore | | `gift_received` | one lot: sats = leg_in_sats − fee_sats, cost = value_ore | | `transfer_in` | one lot per consumed source part, together covering exactly the sent amount: sats = that part's share of `leg_out_sats`, cost = the same share of the part's cost, `acquired_date` and `source_lot_id` from the source lot. The sats of the fee and their cost are not mirrored. | ### 5.2 Which transactions consume lots `trade` with `leg_out_sats`, `spend`, `loss`, `transfer_out` and `gift_given`. The sats to consume are `leg_out_sats`, plus `fee_sats` for `trade`, `spend` and `transfer_out`, where §3.2 says the fee is taken on top. `admin_cost` consumes nothing: it stands on its own (§3.10). 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 the kroner of the year's `admin_cost` transactions that are ticked as taxable; subtracted 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) | `sats`, a whole number with spaces as thousands separators | | 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/kr, sats preselected). Salg/kostnad: Antall, Valuta (sats/kr, kr preselected). Exactly one leg must be sats and the other kroner. | | Inntekt | Inntekt/gevinst: Antall, Valuta (sats). Pris: Antall, Valuta (kr). | | Forbruk | Forbruk: Antall, Valuta (sats). Utgangsverdi: Antall, Valuta (kr). | | Tap | Tap: Antall, Valuta (sats). Pris: Antall, Valuta (kr), required. | | Overføring ut | Sendt: Antall, Valuta (sats). Til: account selector. | | Gåve (motteke) | Motteke gåve: Antall, Valuta (sats). Pris: Antall, Valuta (kr). | | Gåve (gjeven) | Gjeven gåve: Antall, Valuta (sats). | | Forvaltningskostnad | Kostnad: Antall, Valuta (kr). No account and no fee: the Marknad and Avgift sections are hidden and the row is stored with `market_id` null. | A field whose currency is not a choice shows the unit as plain text instead of a selector: `sats` for every sats amount and `kr` for every kroner amount. Only `Kjøp` and `Salg/kostnad` on Handel get a selector, because they are the only two that can be either. - **Avgift**: Antall (valfri) + Valuta (sats, shown as plain text), with a one-line explanation that a fee raises the cost basis of a buy and is taken on top of what a transfer sends. A kroner cost is not a fee: the owner folds it into the amount they type. Shown only for `trade`, `income`, `spend`, `loss`, `transfer_out` and `gift_given` (§3.2). - **Anna**: Marknad (account selector, required except for `admin_cost`, where the field is hidden and the account is stored as null), Notat (valfri). - **Bitcoin pris**: not a field, a figure the app works out and shows. For `trade`, `income`, `spend`, `loss` and `gift_received` it is the kroner price of one whole BTC in the transaction: `nok_ore × 10^8 ÷ sats`, where `nok_ore` is the kroner amount of the transaction and `sats` the sats amount, and the fee is left out. A buy of 1 000 sats for 10 kr gives 10 × 10^8 ÷ 1 000 = **1 000 000 kr** per BTC. For a `transfer_out` and its `transfer_in` it is the price of the lots the transfer used: the total cost of those lots × 10^8 ÷ their total sats, so the two sides of a transfer show the same price. It is shown as `Bitcoin pris` in the transaction list (§7.6) and in the lot table of the form. It is empty for `gift_given` and `admin_cost`, which have no sats and kroner pair. - 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 sent amount (never reduced by the fee), `fee_sats` and `fee_ore` = 0, and `taxable` copied from the `transfer_out`. The `transfer_in` shows its own fields in the form, read-only: `Motteke` in sats and the account it landed on, with no Avgift section, because the fee belongs to 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. ### 7.6 The transaction list (`/transaksjonar`) Columns, in this order: Dato, Type, Konto, Til konto, Bitcoin pris, Inn, Ut, Avgift, Inngangsverdi, Skattepliktig, and then the row's actions. - `Bitcoin pris` is the price of §7.3, in whole kroner, empty when the type has none. It sits between `Til konto` and `Inn`. A transfer shows the price of the lots it used. - `Inn`, `Ut` and `Avgift` carry the unit of the amount they show: `1 500 000 sats` or `1 000 kr`. - `Inngangsverdi` is the cost basis the transaction consumed, in whole kroner. - A generated `transfer_in` is marked `(laga automatisk)` and has neither Endre nor Slett. - `Konto` is empty for `admin_cost`, which has no account. --- ## 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 API takes sats as a whole number: `1500000` or `"1 500 000"`. A decimal number of BTC is rejected. A kroner amount may carry two decimals, as the storage is øre. A fee is sent as `fee_sats` only: `fee_ore` is never sent by a client and stays 0 in the database. For `admin_cost`, the amount is sent as `leg_out_ore`, `market_id` must be absent or null, `lot_picks` are rejected, and a fee is rejected; the account is not required and not looked up. Every transaction object carries `btc_price_ore`: the price of §7.3 in øre per whole BTC, or null when the type has no price. For a `transfer_out` it is worked out from the consumed lots (`cost_ore` and `consumed_sats`), and for a `transfer_in` from its own mirrored lots (`lot_cost_ore` and `lot_sats`), so the two sides agree. The lot objects carry `btc_price_ore` for the same unit, worked out from the lot's remaining cost and sats. 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 and the transaction's bitcoin price. Kroner are written as whole kroner and BTC quantities as whole sats, the same as the UI. --- ## 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? And which rate converts the sats to kroner? | Recorded and shown as its own line in sats, never attached to an account, not deducted until `deduct_admin_costs` is switched on; when it is on, the sats are converted at the year-end rate for the tax year. | | Q3 | Should the loss in `Tap` use the consumed lots' cost basis (as built) or the kroner value the owner types in `Pris`? | Cost basis from the lots. `Pris` is required by the form and stored with the row, but it does not enter the figure. | | 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