Balances, nonces, and actually charging for a transaction.
Everything before this namespace computed a price and charged nobody.
settle returns the transaction to APPLY: the sender's own tx-data, plus
the ownership stamps, plus the datoms that debit the sender, advance the
nonce, and record the fee. One transaction.
Splitting them would be a divergence bug waiting for a crash: a node that applied the effects and died before the debit would carry a different balance than its peers forever, and the app-hash comparison would find it one block later with no way to say which half was right. Making the fee part of the same transaction means there is no window.
It also means a REFUSED transaction still produces a transaction: the fee and the nonce bump, without the sender's effects. A refusal that wrote nothing would leave the nonce unspent, and a transaction that can be retried for free after being refused is a free retry loop.
n+1 exactly. Monotonic-but-gappy is enough to stop a replay and is simpler
to implement, but sequential buys two things worth the strictness: a
mempool can order an account's pending transactions without guessing, and an
account cannot burn its own nonce space by jumping to a large value.
The nonce lives on the account entity, so it advances in the same transaction as the fee -- there is no separate replay table to keep consistent with the balance.
There is nothing to take. This deliberately leaves cheap spam from empty accounts to the layer that can actually stop it: the mempool drops a transaction whose sender cannot cover the base fee, before it reaches consensus. Doing it here would mean pretending to charge an account with a zero balance, which is bookkeeping theatre.
The cost an attacker still imposes is one signature verification at the
network edge. That is the cheapest check we have, and it is why
urd.consensus.auth refuses an unknown author before any crypto runs.
Balances, nonces, and actually charging for a transaction. Everything before this namespace computed a price and charged nobody. ## The charge is tx-data, not a side effect `settle` returns the transaction to APPLY: the sender's own tx-data, plus the ownership stamps, plus the datoms that debit the sender, advance the nonce, and record the fee. One transaction. Splitting them would be a divergence bug waiting for a crash: a node that applied the effects and died before the debit would carry a different balance than its peers forever, and the app-hash comparison would find it one block later with no way to say which half was right. Making the fee part of the same transaction means there is no window. It also means a REFUSED transaction still produces a transaction: the fee and the nonce bump, without the sender's effects. A refusal that wrote nothing would leave the nonce unspent, and a transaction that can be retried for free after being refused is a free retry loop. ## Nonces are sequential, not merely increasing `n+1` exactly. Monotonic-but-gappy is enough to stop a replay and is simpler to implement, but sequential buys two things worth the strictness: a mempool can order an account's pending transactions without guessing, and an account cannot burn its own nonce space by jumping to a large value. The nonce lives on the account entity, so it advances in the same transaction as the fee -- there is no separate replay table to keep consistent with the balance. ## An account that cannot pay is refused and charged nothing There is nothing to take. This deliberately leaves cheap spam from empty accounts to the layer that can actually stop it: the mempool drops a transaction whose sender cannot cover the base fee, before it reaches consensus. Doing it here would mean pretending to charge an account with a zero balance, which is bookkeeping theatre. The cost an attacker still imposes is one signature verification at the network edge. That is the cheapest check we have, and it is why `urd.consensus.auth` refuses an unknown author before any crypto runs.
Who may write what: the transaction boundary.
A transaction is admitted when three things hold, in this order:
AUTHORSHIP an Ed25519 signature over the tx-data, by the key that claims
to have sent it.
SCOPE every datom it PRODUCES is in the sender's own attribute
namespace, or is a system attribute the sender is allowed to
write.
COST it fits the budget, priced by skuld.ledger.cost.
A public key owns the attribute namespace that is its own hex:
:5f3a...c1/first-name 64 hex characters, then the attribute
which makes ownership self-evident from the attribute alone -- no registry, no lookup, no allocation step, and no way for two users to be assigned the same namespace.
A shorter namespace is far nicer to read, and it is exactly wrong here. The namespace is not a display name, it is a CAPABILITY: whoever can produce a key whose namespace matches yours can write your data. Truncating to 10 hex characters leaves 40 bits, and finding a second key with a chosen 40-bit prefix is around 2^40 keygens -- hours of ordinary compute, targeted at a specific victim. At the full 32 bytes the same attack is 2^256 and the question does not arise.
Verified against datahike: a 64-character keyword namespace reads, prints, round-trips through the reader, installs, transacts and queries.
This is the part that is easy to get wrong, because the obvious implementation -- walk the tx-data the sender submitted and look at the attributes it names -- is bypassable by any operation that does not name what it touches. Two are reachable in datahike today, and the second is the one that settles the design:
[:db/retractEntity 42] names NO attribute, and produces one retraction per attribute the entity has, including other users'. Measured: retracting an entity carrying two users' attributes produced a retraction datom in each.
:db/isComponent cascade WORSE. Retracting an entity cascades into its
component children, so a caller can destroy
datoms on an entity it never named, belonging
to a user it never named. Measured: Alice
retracting her OWN entity produced
[:<bob>/secret "bobs-data" false].
Both are closed by the same move: run d/with and check what came OUT. That
is also the call skuld.ledger.cost/price already makes, so the authorization
decision and the price come from ONE speculative transaction rather than two.
The mutation matters here. Swapping this for the naive submitted-form check
leaves every other test in authz-test passing -- including "a transaction
cannot write another user's attribute" -- and fails only these two. That is
why the naive version is tempting: it looks correct against the case anyone
would think to write.
[:my/fn args] resolving to a :db/fn on an entity would expand to
arbitrary tx-data and is the surface I expected to matter. It is currently
unreachable: datahike.db.transaction resolves it (transaction.cljc:1415)
but :db/fn is defined in no datahike schema, cannot be installed under
:schema-flexibility :write, and cannot be defined at all because the db
namespace is reserved. An inline [:db.fn/call (fn ...)] is separately
impossible over the wire, since the signature covers canonical CBOR of the
tx-data and a function object has no CBOR encoding.
Recorded rather than dropped, because reading the call site alone suggests the opposite. If datahike completes the feature this becomes live immediately -- and this namespace already covers it, since an expansion is exactly a produced datom.
Scope is per-ATTRIBUTE, never per-entity. Writing :<my-key>/note onto an
entity someone else created is allowed, and an entity can carry attributes
from many keys at once. That is deliberate -- it is what lets one user
annotate another's data without permission -- but it means "who owns entity
42" has no answer, and code that assumes otherwise is assuming something
this layer never promised.
Anything whose namespace is not a 64-character hex string is a system
attribute: :db/ident, :kontor.account/path, the ledger's own schema.
These are READABLE by everyone -- reads are not gated here at all. The
separation needs no registry: a hex namespace and an alphabetic one cannot
collide, so a user key can never name a system attribute however it is
constructed.
:system-writers below is part of THIS namespace's scope-violations, which
the live write path does not use. skuld.boundary/admit routes through
ownership/violations instead, and that refuses a protocol attribute before
ownership or any writer set is consulted -- so under the live boundary no
key writes :urd.account/* or :urd.stake/*, configured writer or not.
Genesis installs schema by transacting directly, not through a boundary.
Who may write what: the transaction boundary.
## The rule
A transaction is admitted when three things hold, in this order:
AUTHORSHIP an Ed25519 signature over the tx-data, by the key that claims
to have sent it.
SCOPE every datom it PRODUCES is in the sender's own attribute
namespace, or is a system attribute the sender is allowed to
write.
COST it fits the budget, priced by `skuld.ledger.cost`.
A public key owns the attribute namespace that is its own hex:
:5f3a...c1/first-name 64 hex characters, then the attribute
which makes ownership self-evident from the attribute alone -- no registry,
no lookup, no allocation step, and no way for two users to be assigned the
same namespace.
## Why the whole key and not a prefix
A shorter namespace is far nicer to read, and it is exactly wrong here. The
namespace is not a display name, it is a CAPABILITY: whoever can produce a
key whose namespace matches yours can write your data. Truncating to 10 hex
characters leaves 40 bits, and finding a second key with a chosen 40-bit
prefix is around 2^40 keygens -- hours of ordinary compute, targeted at a
specific victim. At the full 32 bytes the same attack is 2^256 and the
question does not arise.
Verified against datahike: a 64-character keyword namespace reads, prints,
round-trips through the reader, installs, transacts and queries.
## Why the check reads produced datoms, not submitted forms
This is the part that is easy to get wrong, because the obvious
implementation -- walk the tx-data the sender submitted and look at the
attributes it names -- is bypassable by any operation that does not name
what it touches. Two are reachable in datahike today, and the second is the
one that settles the design:
[:db/retractEntity 42] names NO attribute, and produces one retraction
per attribute the entity has, including other
users'. Measured: retracting an entity carrying
two users' attributes produced a retraction
datom in each.
:db/isComponent cascade WORSE. Retracting an entity cascades into its
component children, so a caller can destroy
datoms on an entity it never named, belonging
to a user it never named. Measured: Alice
retracting her OWN entity produced
`[:<bob>/secret "bobs-data" false]`.
Both are closed by the same move: run `d/with` and check what came OUT. That
is also the call `skuld.ledger.cost/price` already makes, so the authorization
decision and the price come from ONE speculative transaction rather than two.
The mutation matters here. Swapping this for the naive submitted-form check
leaves every other test in `authz-test` passing -- including "a transaction
cannot write another user's attribute" -- and fails only these two. That is
why the naive version is tempting: it looks correct against the case anyone
would think to write.
## Stored transaction functions: not a hole today
`[:my/fn args]` resolving to a `:db/fn` on an entity would expand to
arbitrary tx-data and is the surface I expected to matter. It is currently
unreachable: `datahike.db.transaction` resolves it (transaction.cljc:1415)
but `:db/fn` is defined in no datahike schema, cannot be installed under
`:schema-flexibility :write`, and cannot be defined at all because the `db`
namespace is reserved. An inline `[:db.fn/call (fn ...)]` is separately
impossible over the wire, since the signature covers canonical CBOR of the
tx-data and a function object has no CBOR encoding.
Recorded rather than dropped, because reading the call site alone suggests
the opposite. If datahike completes the feature this becomes live
immediately -- and this namespace already covers it, since an expansion is
exactly a produced datom.
## What entity ownership is not
Scope is per-ATTRIBUTE, never per-entity. Writing `:<my-key>/note` onto an
entity someone else created is allowed, and an entity can carry attributes
from many keys at once. That is deliberate -- it is what lets one user
annotate another's data without permission -- but it means "who owns entity
42" has no answer, and code that assumes otherwise is assuming something
this layer never promised.
## System attributes
Anything whose namespace is not a 64-character hex string is a system
attribute: `:db/ident`, `:kontor.account/path`, the ledger's own schema.
These are READABLE by everyone -- reads are not gated here at all. The
separation needs no registry: a hex namespace and an alphabetic one cannot
collide, so a user key can never name a system attribute however it is
constructed.
`:system-writers` below is part of THIS namespace's `scope-violations`, which
the live write path does not use. `skuld.boundary/admit` routes through
`ownership/violations` instead, and that refuses a protocol attribute before
ownership or any writer set is consulted -- so under the live boundary no
key writes `:urd.account/*` or `:urd.stake/*`, configured writer or not.
Genesis installs schema by transacting directly, not through a boundary.A datahike database per validator, kept in step by consensus over real sockets.
Everything else in this repository is a test. This is the thing the tests are about: N processes' worth of validators, each with its OWN file-backed datahike database, talking Tendermint over kabel websockets with Ed25519 identities, and nothing anywhere coordinating the databases. If they agree at the end it is because consensus made them agree.
:backend :memory, so datahike's commit graph is
genuinely on disk and a restart would find it.skuld.ledger.cost prices every committed transaction against the database it
lands in, and the run reports the totals. It does not REFUSE anything here,
and that is deliberate: refusing needs a rejected vertex to be recorded as
consumed, or it is retried forever, and the ledger's marks are keyed to
transactions that actually happened. Wiring that properly is a change to the
ledger's bookkeeping rather than a flag on this demo. Pricing is honest
without it, and it is the half that answers "what would this have cost".
clj -M -m skuld.ledger.cluster ; 4 validators, 20 seconds
clj -M -m skuld.ledger.cluster 5 30 48000 ; n, seconds, base port
A datahike database per validator, kept in step by consensus over real
sockets.
Everything else in this repository is a test. This is the thing the tests are
about: N processes' worth of validators, each with its OWN file-backed
datahike database, talking Tendermint over kabel websockets with Ed25519
identities, and nothing anywhere coordinating the databases. If they agree at
the end it is because consensus made them agree.
## What it exercises that the test suite does not
- **Tendermint over kabel.** The kabel integration tests run round-robin; the
conformance suite runs Tendermint over the in-process router. This is the
first configuration where a BFT algorithm's own topic vocabulary has to
survive the real pubsub registration path.
- **Real file stores**, not `:backend :memory`, so datahike's commit graph is
genuinely on disk and a restart would find it.
- **Wall-clock timers under real network latency**, which is where the
simulator's logical ticks stop being a model of anything.
## Cost is reported, not enforced
`skuld.ledger.cost` prices every committed transaction against the database it
lands in, and the run reports the totals. It does not REFUSE anything here,
and that is deliberate: refusing needs a rejected vertex to be recorded as
consumed, or it is retried forever, and the ledger's `marks` are keyed to
transactions that actually happened. Wiring that properly is a change to the
ledger's bookkeeping rather than a flag on this demo. Pricing is honest
without it, and it is the half that answers "what would this have cost".
## Running it
clj -M -m skuld.ledger.cluster ; 4 validators, 20 seconds
clj -M -m skuld.ledger.cluster 5 30 48000 ; n, seconds, base portTransaction costs for the datalog ledger.
Consensus decides ORDER. It does not decide how much work a transaction is, and it must not: the state machine is a pure function with no database, so it cannot know what a transaction will actually do. This namespace prices the work, at the one place that can — where the agreed prefix meets the database.
The obvious design is to charge for the transaction as written: count its forms, or its bytes, and reject anything too big. That is unsound here, and measurably so:
[[:db/retractEntity 42]]
is twenty-three characters and produced FOUR datoms in the probe that motivated this namespace, on an entity with four attributes. On an entity with ten thousand attributes it is still twenty-three characters. The work is a function of the DATABASE, not of the text, and the gap between them is unbounded — which is exactly the shape of an attack: bounded fee, unbounded work.
The same holds for upserts that resolve to a retraction plus an addition, for
cardinality-many replacement, and for :db/fn transaction functions, which
can expand to anything at all.
d/with applies a transaction to a database VALUE and returns the datoms it
would produce, without committing anything. So the real cost is available
before the decision to pay it:
price -> run `d/with`, count the datoms it really produces
afford? -> compare against what is left in the budget
apply -> commit only if it fits
It is deterministic. Every honest validator holds the identical committed
prefix — that is what consensus just established — so every validator calls
d/with on the identical database value with the identical transaction, gets
the identical datoms, computes the identical cost, and makes the identical
accept/reject decision. Cost enforcement therefore adds no new agreement
problem; it rides entirely on the agreement urd already provides.
This is the same seam argument that puts signature verification at the network edge and konserve's async API at the store: the pure core stays pure, and the thing that needs the world happens where the world is.
Its :base fee, and nothing else. It is CONSUMED — recorded as seen, with no
datoms written — rather than left to be retried forever. A transaction that
could be retried for free after being refused for cost is a free retry loop,
which is the thing a budget exists to prevent.
Note the asymmetry that makes this sound: pricing a transaction is cheap
(d/with on an immutable value, discarded), while applying it is not. An
attacker pays the base fee to make us do the cheap half.
Transaction costs for the datalog ledger.
Consensus decides ORDER. It does not decide how much work a transaction is,
and it must not: the state machine is a pure function with no database, so it
cannot know what a transaction will actually do. This namespace prices the
work, at the one place that can — where the agreed prefix meets the database.
## Why cost cannot be estimated from the transaction
The obvious design is to charge for the transaction as written: count its
forms, or its bytes, and reject anything too big. That is unsound here, and
measurably so:
[[:db/retractEntity 42]]
is twenty-three characters and produced FOUR datoms in the probe that
motivated this namespace, on an entity with four attributes. On an entity
with ten thousand attributes it is still twenty-three characters. The work is
a function of the DATABASE, not of the text, and the gap between them is
unbounded — which is exactly the shape of an attack: bounded fee, unbounded
work.
The same holds for upserts that resolve to a retraction plus an addition, for
cardinality-many replacement, and for `:db/fn` transaction functions, which
can expand to anything at all.
## What we do instead: measure, then decide
`d/with` applies a transaction to a database VALUE and returns the datoms it
would produce, without committing anything. So the real cost is available
before the decision to pay it:
price -> run `d/with`, count the datoms it really produces
afford? -> compare against what is left in the budget
apply -> commit only if it fits
## Why this is safe across validators
It is deterministic. Every honest validator holds the identical committed
prefix — that is what consensus just established — so every validator calls
`d/with` on the identical database value with the identical transaction, gets
the identical datoms, computes the identical cost, and makes the identical
accept/reject decision. Cost enforcement therefore adds no new agreement
problem; it rides entirely on the agreement urd already provides.
This is the same seam argument that puts signature verification at the network
edge and konserve's async API at the store: the pure core stays pure, and the
thing that needs the world happens where the world is.
## What a rejected transaction costs
Its `:base` fee, and nothing else. It is CONSUMED — recorded as seen, with no
datoms written — rather than left to be retried forever. A transaction that
could be retried for free after being refused for cost is a free retry loop,
which is the thing a budget exists to prevent.
Note the asymmetry that makes this sound: pricing a transaction is cheap
(`d/with` on an immutable value, discarded), while applying it is not. An
attacker pays the base fee to make us do the cheap half.A ledger: urd's committed prefix, applied to a datahike database.
This is the consumer the effect protocol was designed against, and it is worth saying what it does NOT need. There is no reconciliation layer, no undo log, no shadow copy of the committed sequence. Three effects map onto three datahike calls:
commit -> transact! extend the prefix
revert -> force-branch! move the branch pointer back
resync -> force-branch! state the prefix wholesale, after a restart
node/revert's docstring claims reverting is cheap on a copy-on-write
substrate because the blocks are immutable and still in the store, so a
rollback is a pointer move. datahike is that substrate: force-branch!
writes a new head record naming an older db value and every index node it
refers to is still there. There is no per-datom undo, and nothing is
rewritten in place.
This is the half of the design that Bitcoin pays for and Bullshark does not. btcd's two-phase reorg machinery exists because its UTXO set is a destructively mutated map; at the header layer, where every quantity is a fold over the ancestor path, its undo log is empty. Here the whole database is at the header layer.
A ledger is handed the same vertex more than once in normal operation: Raft
and SCP both announce their committed prefix on restart, a resync restates
it, and a catching-up node may re-learn a height it already had. So each
vertex carries its id in :tx-meta and a vertex already applied is skipped.
That also makes the mapping RECOVERABLE. :tx-meta becomes attributes on the
tx entity, so [?tx :urd/vertex ?id] is an ordinary query, and
branch-history walks the commit graph -- so after a process restart the
ledger rebuilds vertex -> commit-id from the database rather than from
memory it no longer has. A ledger that could only revert within one process
lifetime would be a ledger that cannot revert.
force-branch! warns that existing connections see stale state and must be
released and reconnected. A caller cannot be expected to know that a revert
invalidated the connection it is holding, so the ledger owns it: db hands
out a value, never the connection, and the revert path releases and
reconnects before returning.
A ledger: urd's committed prefix, applied to a datahike database.
This is the consumer the effect protocol was designed against, and it is
worth saying what it does NOT need. There is no reconciliation layer, no
undo log, no shadow copy of the committed sequence. Three effects map onto
three datahike calls:
commit -> transact! extend the prefix
revert -> force-branch! move the branch pointer back
resync -> force-branch! state the prefix wholesale, after a restart
## Why the revert is cheap
`node/revert`'s docstring claims reverting is cheap on a copy-on-write
substrate because the blocks are immutable and still in the store, so a
rollback is a pointer move. datahike is that substrate: `force-branch!`
writes a new head record naming an older db value and every index node it
refers to is still there. There is no per-datom undo, and nothing is
rewritten in place.
This is the half of the design that Bitcoin pays for and Bullshark does not.
btcd's two-phase reorg machinery exists because its UTXO set is a
destructively mutated map; at the header layer, where every quantity is a
fold over the ancestor path, its undo log is empty. Here the whole database
is at the header layer.
## Idempotence, and why it is not optional
A ledger is handed the same vertex more than once in normal operation: Raft
and SCP both announce their committed prefix on restart, a `resync` restates
it, and a catching-up node may re-learn a height it already had. So each
vertex carries its id in `:tx-meta` and a vertex already applied is skipped.
That also makes the mapping RECOVERABLE. `:tx-meta` becomes attributes on the
tx entity, so `[?tx :urd/vertex ?id]` is an ordinary query, and
`branch-history` walks the commit graph -- so after a process restart the
ledger rebuilds vertex -> commit-id from the database rather than from
memory it no longer has. A ledger that could only revert within one process
lifetime would be a ledger that cannot revert.
## The connection is owned here
`force-branch!` warns that existing connections see stale state and must be
released and reconnected. A caller cannot be expected to know that a revert
invalidated the connection it is holding, so the ledger owns it: `db` hands
out a value, never the connection, and the revert path releases and
reconnects before returning.Row-level ownership, so a shared schema can have per-row owners.
skuld.ledger.authz scopes writes by the attribute's namespace: a key owns
:<its-hex>/anything. That is self-evident from the attribute alone — no
lookup, no registry, no allocation — and it is the right answer for data
whose SHAPE belongs to its owner: a profile, a note, a document.
It cannot express a shared schema. Every user posting to a ledger writes the
same :kontor.transaction/narration, and under attribute-namespace scoping
that is a system attribute, so an ordinary key is refused. Measured: an
unmodified kontor.book/entry-tx-data posting had ALL 20 of its datoms
refused. A ledger nobody can post to is not a ledger.
So ownership moves onto the ROW: an entity carries :urd/owner, and writing
a system attribute on it requires being that owner.
Storing the 64-character hex on every entity works and is the obvious encoding. It is the wrong one, for a reason that only shows up under key rotation.
Rotating a key that owns 300 rows:
owner as a ref to a key entity 3 datoms, cost 1,415
owner as a hex string on each row 601 datoms, cost 84,537
The ref is O(1) in rows owned; the string is O(rows). And encoding the key
in the ATTRIBUTE NAMESPACE — the first design — is worse than either: the
attribute keyword itself changes, so rotation rewrites every datom under a
new attribute and breaks every external reference to :<oldkey>/foo. That
is a migration, not a transaction.
The ref is also cheaper per write: ~103 against ~164 per entity, since a reference is an integer and the hex is 64 bytes.
Requiring the client to mark every entity it creates is invasive and, for an
existing library, impossible: kontor's builder emits four entities per
posting and knows nothing about urd. stamp adds the owner at the boundary
instead. It is a deterministic function of the signed tx-data, so every
validator derives the same stamped transaction — the signature covers what
the client sent, and the stamp is part of applying it.
:urd/owner is itself a system attribute, so the rule "writing a system
attribute requires owning the row" already means only the current owner can
change it. Transfer falls out; theft does not.
Row-level ownership, so a shared schema can have per-row owners.
## Why attribute namespaces are not enough
`skuld.ledger.authz` scopes writes by the attribute's namespace: a key owns
`:<its-hex>/anything`. That is self-evident from the attribute alone — no
lookup, no registry, no allocation — and it is the right answer for data
whose SHAPE belongs to its owner: a profile, a note, a document.
It cannot express a shared schema. Every user posting to a ledger writes the
same `:kontor.transaction/narration`, and under attribute-namespace scoping
that is a system attribute, so an ordinary key is refused. Measured: an
unmodified `kontor.book/entry-tx-data` posting had ALL 20 of its datoms
refused. A ledger nobody can post to is not a ledger.
So ownership moves onto the ROW: an entity carries `:urd/owner`, and writing
a system attribute on it requires being that owner.
## Why the owner is a ref and not the key itself
Storing the 64-character hex on every entity works and is the obvious
encoding. It is the wrong one, for a reason that only shows up under key
rotation.
Rotating a key that owns 300 rows:
owner as a ref to a key entity 3 datoms, cost 1,415
owner as a hex string on each row 601 datoms, cost 84,537
The ref is O(1) in rows owned; the string is O(rows). And encoding the key
in the ATTRIBUTE NAMESPACE — the first design — is worse than either: the
attribute keyword itself changes, so rotation rewrites every datom under a
new attribute and breaks every external reference to `:<oldkey>/foo`. That
is a migration, not a transaction.
The ref is also cheaper per write: ~103 against ~164 per entity, since a
reference is an integer and the hex is 64 bytes.
## Why the boundary stamps ownership, not the client
Requiring the client to mark every entity it creates is invasive and, for an
existing library, impossible: kontor's builder emits four entities per
posting and knows nothing about urd. `stamp` adds the owner at the boundary
instead. It is a deterministic function of the signed tx-data, so every
validator derives the same stamped transaction — the signature covers what
the client sent, and the stamp is part of applying it.
## Transfer is not a special case
`:urd/owner` is itself a system attribute, so the rule "writing a system
attribute requires owning the row" already means only the current owner can
change it. Transfer falls out; theft does not.Exact rationals, for the quantities where they are safe.
Clojure has exact rationals natively, and the Cosmos SDK carries a documented 3-ulp margin-of-error hack whose comment says outright that the problem would vanish given arbitrary-precision rationals. That makes exact arithmetic look like free correctness.
It is free only for BOUNDED, NON-ACCUMULATED quantities. Adding rationals multiplies denominators, so anything summed over time grows without bound. Measured on a cumulative reward ratio, the reduced denominator grew linearly at roughly 26 bits per period:
10 periods 294 bits
100 periods 2,748 bits 400 periods 10,363 bits
which is a multi-megabyte integer after a million blocks, stored, hashed into the app-hash and compared every block.
So: commission rates, slash fractions and tax rates -- fixed, small, never
accumulated -- are exact rationals here. The cumulative reward ratio is
fixed-point in skuld.ledger.stake, and that is a deliberate choice rather
than an inherited limitation.
hasch/edn-hash has no PHashCoercion for clojure.lang.Ratio, so any
value containing one raises rather than hashing. That does not affect
persistence -- 1/10 prints and reads back exactly -- nor the app-hash,
which covers stored datoms and sees the printed string. It does mean a
Ratio must never reach a digest directly, which is a real constraint on
where these values may travel, discovered by a three-JVM determinism run
that could not hash its own state.
Exact rationals, for the quantities where they are safe.
## Where they are safe, and where they are not
Clojure has exact rationals natively, and the Cosmos SDK carries a
documented 3-ulp margin-of-error hack whose comment says outright that the
problem would vanish given arbitrary-precision rationals. That makes exact
arithmetic look like free correctness.
It is free only for BOUNDED, NON-ACCUMULATED quantities. Adding rationals
multiplies denominators, so anything summed over time grows without bound.
Measured on a cumulative reward ratio, the reduced denominator grew linearly
at roughly 26 bits per period:
10 periods 294 bits
100 periods 2,748 bits
400 periods 10,363 bits
which is a multi-megabyte integer after a million blocks, stored, hashed
into the app-hash and compared every block.
So: commission rates, slash fractions and tax rates -- fixed, small, never
accumulated -- are exact rationals here. The cumulative reward ratio is
fixed-point in `skuld.ledger.stake`, and that is a deliberate choice rather
than an inherited limitation.
## They cannot be hashed directly
`hasch/edn-hash` has no `PHashCoercion` for `clojure.lang.Ratio`, so any
value containing one raises rather than hashing. That does not affect
persistence -- `1/10` prints and reads back exactly -- nor the app-hash,
which covers stored datoms and sees the printed string. It does mean a
Ratio must never reach a digest directly, which is a real constraint on
where these values may travel, discovered by a three-JVM determinism run
that could not hash its own state.Bonded proof-of-stake: delegation, rewards, unbonding, slashing.
Pure functions over a plain map. urd's consensus layer already takes a WEIGHTED validator set and already decomposes changes into TRIGGER/TRANSITION/ACTIVATION; this namespace is the economic layer that computes those weights, and nothing here touches the network or a database.
A delegation stores SHARES, never a token amount. It exists for exactly one
reason: a slash becomes validator.tokens -= x -- one write -- instead of
a loop over every delegator. The exchange rate tokens/shares falls, and
every delegation is diluted without being touched.
This is the same trick as the reward ratio below, and both are the answer to the same question: how do you charge or credit N delegators in O(1)?
F1 accumulates cum(n) = SUM over periods of rewards_p / tokens_p, and the
obvious Clojure move is an exact Ratio -- no truncation, no rounding, and
the Cosmos SDK carries a documented 3-ulp fudge factor precisely because it
could not have that.
Measured, it is catastrophic. Adding rationals multiplies denominators, and the reduced denominator grows LINEARLY in the number of periods at about 26 bits each:
10 periods 294 bits 1 ms
100 periods 2,748 bits 57 ms 400 periods 10,363 bits 365 ms
A million blocks is a multi-megabyte integer that has to be stored, hashed into the app-hash and compared every block, with superlinear arithmetic on top. Fixed-point is load-bearing, not a limitation of Go.
So: cum-ratio is an integer numerator over a constant ratio-scale.
Exact rationals are still used where the quantity is BOUNDED and not
accumulated -- commission and slash fractions -- where they cost nothing and
remove a rounding decision.
Every division here truncates DOWN when paying out. Paying a fraction too
much is a solvency hole; paying a fraction too little leaves dust in the
pool. The dust is then routed explicitly to the community pool rather than
discarded, which is what lets solvent? be an equality rather than an
inequality -- see check-solvency.
Two rules, and they are the whole security property:
an entry created AT OR AFTER the infraction height is slashable -- stake that was bonded when the offence happened cannot outrun the consequence, however fast its owner exits.
a MATURE entry is exempt -- the tokens are already paid out and gone.
Which is why max-evidence-age must not exceed unbonding-time. Cosmos
matches them by convention and validates nothing; validate-params refuses
the mismatch here, because a chain that accepts evidence older than its
unbonding period cannot punish what the evidence proves.
Bonded proof-of-stake: delegation, rewards, unbonding, slashing.
Pure functions over a plain map. urd's consensus layer already takes a
WEIGHTED validator set and already decomposes changes into
TRIGGER/TRANSITION/ACTIVATION; this namespace is the economic layer that
computes those weights, and nothing here touches the network or a database.
## Shares, and why they are not tokens
A delegation stores SHARES, never a token amount. It exists for exactly one
reason: a slash becomes `validator.tokens -= x` -- one write -- instead of
a loop over every delegator. The exchange rate `tokens/shares` falls, and
every delegation is diluted without being touched.
This is the same trick as the reward ratio below, and both are the answer to
the same question: how do you charge or credit N delegators in O(1)?
## The reward ratio is FIXED-POINT, and that is not a compromise
F1 accumulates `cum(n) = SUM over periods of rewards_p / tokens_p`, and the
obvious Clojure move is an exact `Ratio` -- no truncation, no rounding, and
the Cosmos SDK carries a documented 3-ulp fudge factor precisely because it
could not have that.
Measured, it is catastrophic. Adding rationals multiplies denominators, and
the reduced denominator grows LINEARLY in the number of periods at about 26
bits each:
10 periods 294 bits 1 ms
100 periods 2,748 bits 57 ms
400 periods 10,363 bits 365 ms
A million blocks is a multi-megabyte integer that has to be stored, hashed
into the app-hash and compared every block, with superlinear arithmetic on
top. Fixed-point is load-bearing, not a limitation of Go.
So: `cum-ratio` is an integer numerator over a constant `ratio-scale`.
Exact rationals are still used where the quantity is BOUNDED and not
accumulated -- commission and slash fractions -- where they cost nothing and
remove a rounding decision.
## Truncation always favours the pool, and the remainder is not lost
Every division here truncates DOWN when paying out. Paying a fraction too
much is a solvency hole; paying a fraction too little leaves dust in the
pool. The dust is then routed explicitly to the community pool rather than
discarded, which is what lets `solvent?` be an equality rather than an
inequality -- see `check-solvency`.
## What makes unbonding safe
Two rules, and they are the whole security property:
an entry created AT OR AFTER the infraction height is slashable -- stake
that was bonded when the offence happened cannot outrun the consequence,
however fast its owner exits.
a MATURE entry is exempt -- the tokens are already paid out and gone.
Which is why `max-evidence-age` must not exceed `unbonding-time`. Cosmos
matches them by convention and validates nothing; `validate-params` refuses
the mismatch here, because a chain that accepts evidence older than its
unbonding period cannot punish what the evidence proves.Who pays for state that persists, and how much.
The obvious design is a deposit: lock tokens when data is written, refund them when it is deleted. It is what I prototyped, and it has a problem -- a refund is a payment, so a transaction that frees a lot of data has a NEGATIVE fee, and a transaction that pays its sender is a minting attack unless refunds are bounded by a per-owner deposit ledger.
NEAR does not have that problem because it does not have refunds. Storage is a POST-CONDITION on the account:
balance >= bytes-used x rate
There is no deposit account, no refund receipt, no release action. Freeing
bytes lowers bytes-used, which lowers the requirement, which makes tokens
spendable again -- automatically, exactly, in the same transaction. The
whole mechanism is one integer per account and one comparison.
Gas is burnt and prices the WORK of writing or deleting; deleting genuinely
costs gas. Storage prices RESIDENCY and is never spent. Measured on NEAR at
100KB the ratio is about 3000:1 -- the burn to delete is ~0.01% of the stake
it releases, which is what makes cleanup rational rather than something you
pay twice for. skuld.ledger.cost is the first meter; this is the second.
The question every design has to answer is which account a datom's bytes count against, and NEAR gets it wrong in a way that is instructive. Its trie is account-partitioned, so bytes are charged to the account whose subtree the data lives in -- the CONTRACT, not the writer. A fungible-token contract therefore pays the storage stake for every user's balance row, and one user can grow it until the contract can no longer be written to at all. NEP-145 exists to work around this at the application layer: contracts make each user pre-pay, track it manually, and refuse to serve the unregistered.
Datoms carry provenance, so we can do at the protocol layer what NEAR needs a standard for:
a datom whose ATTRIBUTE is in a key's namespace counts against that key, wherever the datom sits. Annotating someone else's row with your own attribute is charged to you, which is the correct answer and the one NEAR cannot express.
a datom on a SHARED-SCHEMA attribute counts against the row's owner, since the attribute names no one and the row does.
Neither costs a lookup we do not already perform: the namespace is in the
attribute, and the row owner is what skuld.ledger.ownership reads anyway.
NEAR needed FOUR protocol upgrades to fix byte-counting bugs, plus a
hard-coded per-account correction table shipped for mainnet. An
incrementally-maintained counter diverges from the recomputable truth; the
only question is whether a test finds out or a chain halt does. recompute
and audit exist for that, and are meant to be run in tests and by
operators, not merely to exist.
Who pays for state that persists, and how much.
## An invariant, not an escrow
The obvious design is a deposit: lock tokens when data is written, refund
them when it is deleted. It is what I prototyped, and it has a problem --
a refund is a payment, so a transaction that frees a lot of data has a
NEGATIVE fee, and a transaction that pays its sender is a minting attack
unless refunds are bounded by a per-owner deposit ledger.
NEAR does not have that problem because it does not have refunds. Storage
is a POST-CONDITION on the account:
balance >= bytes-used x rate
There is no deposit account, no refund receipt, no release action. Freeing
bytes lowers `bytes-used`, which lowers the requirement, which makes tokens
spendable again -- automatically, exactly, in the same transaction. The
whole mechanism is one integer per account and one comparison.
## Two meters, three orders of magnitude apart
Gas is burnt and prices the WORK of writing or deleting; deleting genuinely
costs gas. Storage prices RESIDENCY and is never spent. Measured on NEAR at
100KB the ratio is about 3000:1 -- the burn to delete is ~0.01% of the stake
it releases, which is what makes cleanup rational rather than something you
pay twice for. `skuld.ledger.cost` is the first meter; this is the second.
## Attribution: namespace first, row owner second
The question every design has to answer is which account a datom's bytes
count against, and NEAR gets it wrong in a way that is instructive. Its trie
is account-partitioned, so bytes are charged to the account whose subtree
the data lives in -- the CONTRACT, not the writer. A fungible-token contract
therefore pays the storage stake for every user's balance row, and one user
can grow it until the contract can no longer be written to at all. NEP-145
exists to work around this at the application layer: contracts make each
user pre-pay, track it manually, and refuse to serve the unregistered.
Datoms carry provenance, so we can do at the protocol layer what NEAR needs
a standard for:
a datom whose ATTRIBUTE is in a key's namespace counts against that key,
wherever the datom sits. Annotating someone else's row with your own
attribute is charged to you, which is the correct answer and the one
NEAR cannot express.
a datom on a SHARED-SCHEMA attribute counts against the row's owner, since
the attribute names no one and the row does.
Neither costs a lookup we do not already perform: the namespace is in the
attribute, and the row owner is what `skuld.ledger.ownership` reads anyway.
## The counter will drift, so measure it
NEAR needed FOUR protocol upgrades to fix byte-counting bugs, plus a
hard-coded per-account correction table shipped for mainnet. An
incrementally-maintained counter diverges from the recomputable truth; the
only question is whether a test finds out or a chain halt does. `recompute`
and `audit` exist for that, and are meant to be run in tests and by
operators, not merely to exist.cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |