44 KiB
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
mainvolume. - 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; the10^8conversion 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,50and is stored as123450ø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.2025in the UI,YYYY-MM-DDin 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 itNOK 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. The fee_ore column stays in the schema and is always 0:
no client sends it, and it never enters a kroner balance (§3.11).
| 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
Sendtis exactly what arrives: the generatedtransfer_inin B getsleg_in_satsequal 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_inrow 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 is paid from the bank account of §3.11. It is
recorded as one row with market_id = the bank and leg_out_ore = the amount: the kroner leave
the bank, and the bank's balance drops by them. The owner enters the amount once, in kroner; the
server fills the account.
It consumes no lots, changes no holdings, and takes no fee. It is shown as its own line in the
report, in the CSV and on /transaksjonar.
Because the kroner leave the bank, the bank must hold them: a cost that overdraws the bank is refused like any other payment (§3.11). Kroner reach the bank through a withdrawal from an account (§3.11).
Its own taxable flag, ticked by default, decides whether the year's cost counts. The report
carries the year's sum of the kroner that left the bank as admin_cost_ore. It is subtracted
from netto_ore only when the setting deduct_admin_costs is on, which is off by default.
See open question Q2.
3.11 Kroner on an account, and the bank
A market can hold kroner as well as sats. The kroner balance of an account is derived and never stored: the kroner that came in minus the kroner that went out, over that account's own transactions, as of a date.
- A leg carries one currency (§4), so the kroner of an account are exactly
leg_in_ore(in) andleg_out_ore(out) of its transactions.value_oreis not a balance movement — it is the NOK value of a BTC leg — andfee_oreis always 0 (§3.2), so neither enters the balance. - A
tradebuy therefore lowers the balance by the kroner paid and atradesell raises it by the kroner received.income,spend,gift_receivedandgift_givendo not move it. - Nothing new is stored for this: it is a sum over rows that already exist.
The bank. One account is the bank: the row Bank in markets, kind = 'other',
taxable = 0, archived = 1, seeded on first run like the rates and named by the setting
bank_market_id. It is where the kroner outside the exchanges stand: a withdrawal from an
account lands on it, and a deposit into an account or a cost (§3.10) leaves it. It can never go
negative.
- The bank is left out of the account admin, out of the main sheet and out of the report's
account rows, since it holds no sats and is nobody's holding. Its name is shown in the
transaction list, where a cost reads
Bankin theKontocolumn. - Only two things may name the bank: a
Forvaltningskostnad(§3.10), and atransfer_outwhose amount is in kroner, where the bank is one of the two sides (below). Nothing else may. - The bank's kroner balance is derived like any other account's, so where the money outside the exchanges stands is always visible, and it can never be negative.
- §3.8's exclusion of a non-taxable account does not apply to the bank: a cost counts from its
own
taxableflag, which is ticked by default (§3.10).
Sats move between the real accounts with a transfer_out, which carries either sats or kroner,
never both:
transfer_outwithleg_out_sats: exactly as today (§3.3). Both sides are real accounts,Tilis required, and the bank may not be named.transfer_outwithleg_out_ore: kroner, and then the bank is one of the two sides: the account the transaction belongs to is the bank (a deposit into an exchange) orTilis the bank (a withdrawal out of it). Kroner never move between two real accounts. The generatedtransfer_inon the other side getsleg_in_oreequal to the sent amount, no lot is involved, and nothing is realized: kroner are kroner. Both sides are stored, so where the money went is visible in the list.Tilis always required: kroner never leave the ledger silently.
A transfer_out is refused when the source account does not hold enough of the currency as of
the transaction date: the lot ledger refuses sats and names the shortfall in sats (§5.2), and the
derived balance refuses kroner and names the shortfall in kroner. Skuld never invents coins or
kroner. A trade buy is refused as well: buying with kroner the account does not hold is the same
kind of mistake as selling coins it does not hold, and the remedy is to record where the kroner
came from, that is a deposit from the bank.
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.
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')),
-- The app always fills this: for admin_cost it is the bank (section 3.11). The
-- column stays nullable so that a database written before section 3.11 applies.
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:
marketsis the spreadsheet's "ark": one row per exchange, wallet or other person's account.custody_market_idis 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'sTOTrows reconcile.- Amounts are integers. Sats are sats; NOK is øre.
- A transaction's
taxableflag defaults to its account's flag.admin_costhas 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 |
bank_market_id |
the seeded bank | The markets row that pays the costs (§3.11) |
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), and a
transfer_out that carries kroner instead of sats (§3.11) consumes nothing either.
Consumption order:
- Hand-picked lots first (
lot_picks), in the order the owner listed them, oldest pick first. - The remainder from the remaining lots of the same account, by the
lot_methodsetting:FIFO: earliestacquired_datefirst, ties broken by lowest lot id.LIFO: latestacquired_datefirst, ties broken by highest lot id.HIFO: highest cost per sat first, ties broken by earliestacquired_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:
- Delete all rows of
lotsand all rows oflot_consumptionswhereauto = 1. - Replay the transactions ordered by
(date, id). - For each transaction, apply §5.1 and §5.2. Hand-picked selections are read from
lot_picksand 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 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 withsatsat year end and the year'sgevinst_ore/tap_orefor information only. Nothing here enters any total.custody_totals: one row per account that has other accounts' coins in custody, withsats= its own sats + the sats of every account whosecustody_market_idpoints at it. This is the spreadsheet'sTOTrow.
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 <name> 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 innis not selectable: it is generated. A transaction that already exists as a generatedtransfer_incan only be viewed and deleted together with itstransfer_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/kr). Til: account selector, always required. With sats both sides are real accounts; with kroner the bank is one of the two sides (§3.11), chosen here or as the account. |
| 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 account is the bank (§3.11), which the server fills in. |
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_outandgift_given(§3.2). - Anna: Marknad (account selector, required except for
admin_cost, where the field is hidden and the account is stored as null). The bank is offered here for atransfer_outwhose amount is in kroner (§3.11), and nowhere else. Notat (valfri). - Bitcoin pris: not a field, a figure the app works out and shows. For
trade,income,spend,lossandgift_receivedit is the kroner price of one whole BTC in the transaction:nok_ore × 10^8 ÷ sats, wherenok_oreis the kroner amount of the transaction andsatsthe 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 atransfer_outand itstransfer_init 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 asBitcoin prisin the transaction list (§7.6) and in the lot table of the form. It is empty forgift_givenandadmin_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:
- the
transfer_outrow, withtransfer_groupset to a new UUID andto_market_id; - the consumed lots on the source account;
- the mirrored lots on the destination account;
- a
transfer_inrow on the destination account withgenerated = 1, the same date, the sametransfer_group,leg_in_sats= the sent amount (never reduced by the fee),fee_satsandfee_ore= 0, andtaxablecopied from thetransfer_out.
When the amount is in kroner instead, step 2 consumes no lots and step 3 mirrors none: the
transfer_in on the other side gets leg_in_ore equal to the sent kroner, and that other side is
the bank (§3.11).
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 prisis the price of §7.3, in whole kroner, empty when the type has none. It sits betweenTil kontoandInn. A transfer shows the price of the lots it used.Inn,UtandAvgiftcarry the unit of the amount they show:1 500 000 satsor1 000 kr.Inngangsverdiis the cost basis the transaction consumed, in whole kroner.- A generated
transfer_inis marked(laga automatisk)and has neither Endre nor Slett. KontoshowsBankforadmin_cost, whose account is the bank (§3.11).
8. HTTP API
All responses are JSON. All /api/* routes except the auth routes require a session and the
CSRF header. Errors are {"error": "<nynorsk message>", "field": "<field name or null>"} 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 |
| 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 the accounts, with taxable, custody_market_id, sats on hand, kroner_ore and bank, which marks the bank so the form can offer it only where §3.11 allows it |
| 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 server stores the bank of §3.11 and the
matching leg_in_ore itself.
For a transfer_out, exactly one of leg_out_sats and leg_out_ore is sent, and to_market_id
is always required. With sats both sides are real accounts; with kroner the bank of §3.11 is
either the market_id or the to_market_id.
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 withhmac.compare_digest. - The session is a random 32-byte token in an
HttpOnly,SameSite=Strictcookie; 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-Tokenheader, which equals the session's CSRF secret; the check runs before the handler.static/session.jspatcheswindow.fetchto add the header on every same-origin call. - Unauthenticated
/api/*answers 401; every page except/loginredirects 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) anddelete-all-data(wipes every table exceptadminandsettings), plus an init-script task that recommendsset-admin-passwordwhile no admin exists. Both actions runmaintenance.pyin awithTempsubcontainer. - 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
.sqlfile 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 bynpub; the admin password and theadmin/sessionstables are replaced by anaccountstable keyed onnpub. - 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 in kroner as its own line on the bank account (§3.11), and not deducted until deduct_admin_costs is switched on, which is off by default. |
| 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