Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions cmd/ingestor/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,10 @@ func (s *Store) applyAccountWrite(ctx context.Context, cmd account.Command, l ac
if err := applyLinkWrite(ctx, tx, cmd, l, nowMs); err != nil {
return err
}
case account.OpStationSet:
if err := applyStationEdit(ctx, tx, cmd, l, nowMs); err != nil {
return err
}
default:
return account.ErrInvalidCommand
}
Expand Down
11 changes: 10 additions & 1 deletion cmd/ingestor/accounts_links.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ var (
func isLinkOutcome(err error) bool {
for _, e := range []error{errTooManyLinks, errTooManyAcctLinks, errTooManyNodeLinks, errTooManyLinkedNodes, errNotLinkable,
errAlreadyOwner, errNodeFull, errNodeRate, errNotVerifiedOwner, errCannotObject, errTooManyObjections, errAlreadyObjected,
errObjectionNotOpen, errLinkNotActive, errRelinkTooSoon} {
errObjectionNotOpen, errLinkNotActive, errRelinkTooSoon, errNotAnOwner, errNoPosition, errTooManyEdits} {
if errors.Is(err, e) {
return true
}
Expand Down Expand Up @@ -192,6 +192,15 @@ func (s *Store) proveLink(ctx context.Context, proofID, pubkey, hash string, l a
VALUES (?, ?, ?, 'verified', 'manual', 'active', ?, ?, ?)`, linkID, aid, pubkey, proofID, hash, nowMs); err != nil {
return "", err
}
if ownID != "" {
// Open objections follow the owner to the new link (review
// PR#1095 F1): proving the node by advert does not settle them, so
// they keep forcing review and an uphold removes the active link.
if _, err := tx.ExecContext(ctx, `UPDATE link_objections SET link_id = ? WHERE link_id = ? AND status = 'open'`,
linkID, ownID); err != nil {
return "", err
}
}
if err := noticeOtherOwners(ctx, tx, pubkey, aid, notice{kind: account.NoticeCoOwnerAdded, linkID: linkID, tier: account.TierVerified}, nowMs); err != nil {
return "", err
}
Expand Down
212 changes: 212 additions & 0 deletions cmd/ingestor/accounts_station.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
package main

// Station data through owner links (#1018 M2d) — the writer side. The rules
// shared with the server are in internal/channelregistry/account
// (station.go).
//
// applyStationEdit runs inside the account write's transaction (the account
// and its session generation are checked): it finds the sender's active
// link to the node, stores the edit as node_antenna_claims rows with
// account_id, link_id and via = 'link', and decides them:
// - review (probation or an open objection): one row, the whole edit,
// proven and flagged, waiting for the administrator;
// - otherwise the edit is approved at once ('auto'; a clear-only edit
// 'owner'), except new free text: the edit with its free text kept at
// what is in force is approved, and the whole edit waits for review as
// a second row (account.ReviewClaimID), which the administrator's
// approval puts in force through the claim queue as any proven claim.
//
// Last write wins by edit time: the approved row takes a part only when no
// row in force for that part has a later (created_at, request_id); an edit
// that takes no part is superseded at once. A direct advert claim is not
// touched by any of this.

import (
"context"
"database/sql"
"errors"
"strings"

"github.com/meshcore-analyzer/channelregistry/account"
"github.com/meshcore-analyzer/channelregistry/antennaclaim"
)

// User-facing outcomes of a station edit.
var (
errNotAnOwner = errors.New("you are not an owner of this node")
errNoPosition = errors.New("this node has no position yet, so its station data cannot be placed: let it send an advert with its position first")
errTooManyEdits = errors.New("this node has had too many station changes today, please try again tomorrow")
)

// applyStationEdit applies OpStationSet inside tx. A replayed command (its
// request id is stored) adds nothing.
func applyStationEdit(ctx context.Context, tx *sql.Tx, cmd account.Command, l account.Limits, nowMs int64) error {
e, pk, id := *cmd.Station, cmd.PubKey, cmd.RequestID
var n int
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM node_antenna_claims WHERE request_id = ?`, id).Scan(&n); err != nil {
return err
}
if n > 0 {
return nil
}
var linkID string
err := tx.QueryRowContext(ctx, `SELECT link_id FROM account_node_links WHERE account_id = ? AND pubkey = ? AND status = 'active'`,
cmd.AccountID, pk).Scan(&linkID)
if err == sql.ErrNoRows {
return errNotAnOwner
}
if err != nil {
return err
}
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM node_antenna_claims WHERE pubkey = ? AND via = 'link' AND created_at > ?`,
pk, nowMs-dayMs).Scan(&n); err != nil {
return err
}
if n >= account.MaxStationEditsPerNodePerDay {
return errTooManyEdits
}
// The node's position now is where the values stand: the public reads
// serve them only there, and withhold them once the node moves away
// (staleMoveM), as for an advert claim's proof position.
var lat, lon sql.NullFloat64
if err := tx.QueryRowContext(ctx, `SELECT lat, lon FROM nodes WHERE public_key = ?`, pk).Scan(&lat, &lon); err != nil && err != sql.ErrNoRows {
return err
}
if !lat.Valid || !lon.Valid || (lat.Float64 == 0 && lon.Float64 == 0) {
if !e.ClearOnly() {
return errNoPosition
}
lat, lon = sql.NullFloat64{}, sql.NullFloat64{}
}
review, err := mustReview(ctx, tx, linkID, l, nowMs)
if err != nil {
return err
}
at := cmd.CreatedAt
if at <= 0 {
at = nowMs
}
row := linkRow{pk: pk, account: cmd.AccountID, link: linkID, at: at, lat: lat, lon: lon}
if review {
return row.insert(ctx, tx, id, e, antennaclaim.StatusProven, nowMs)
}
structured, held, err := holdFreeText(ctx, tx, pk, e)
if err != nil {
return err
}
if err := row.insert(ctx, tx, id, structured, antennaclaim.StatusApproved, nowMs); err != nil {
return err
}
if err := putInForceByEditTime(ctx, tx, pk, id, at, nowMs); err != nil {
return err
}
if held {
return row.insert(ctx, tx, account.ReviewClaimID(id), e, antennaclaim.StatusProven, nowMs)
}
return nil
}

// mustReview: the link is on probation or has an open objection.
func mustReview(ctx context.Context, tx *sql.Tx, linkID string, l account.Limits, nowMs int64) (bool, error) {
var probation, objected bool
if l.Probation > 0 {
if err := tx.QueryRowContext(ctx, account.ProbationSQL, linkID, nowMs, l.Probation.Milliseconds()).Scan(&probation); err != nil {
return false, err
}
}
if err := tx.QueryRowContext(ctx, account.ObjectedSQL, linkID).Scan(&objected); err != nil {
return false, err
}
return probation || objected, nil
}

// holdFreeText returns e with its free text (contactPublic, a hardware
// model under "other") kept at what is in force for the node, and whether
// e changed any of it: that part waits for the administrator. Removing free
// text is no risk and applies at once.
func holdFreeText(ctx context.Context, tx *sql.Tx, pk string, e antennaclaim.Edit) (antennaclaim.Edit, bool, error) {
if e.Details == nil {
return e, false, nil
}
var contact, model sql.NullString
err := tx.QueryRowContext(ctx, `SELECT contact_public, hardware_model FROM node_antenna_claims
WHERE pubkey = ? AND status = 'approved' AND details_op = 'set' AND details_in_force = 1`, pk).Scan(&contact, &model)
if err != nil && err != sql.ErrNoRows {
return e, false, err
}
d := *e.Details
held := false
if d.ContactPublic != "" && d.ContactPublic != contact.String {
d.ContactPublic, held = contact.String, true
}
if d.HardwareModel != "" && d.HardwareModel != model.String {
d.HardwareModel, held = model.String, true
}
if !held {
return e, false, nil
}
e.Details = &d
return e, true, nil
}

// linkRow is what every row of one link edit shares.
type linkRow struct {
pk, account, link string
at int64
lat, lon sql.NullFloat64
}

// insert stores e as row id in status: approved ('owner' for a clear-only
// edit, else 'auto') or proven, flagged for the administrator's review.
// Its edit time is both created_at and proven_at, so the claim queue's
// rule for an administrator's approval (antennaclaim.NewerApprovedQuery,
// by proven_at) orders it with every other edit.
func (r linkRow) insert(ctx context.Context, tx *sql.Tx, id string, e antennaclaim.Edit, status string, nowMs int64) error {
review := status == antennaclaim.StatusProven
if err := insertClaimRow(ctx, tx, id, r.pk, "", e, review, r.at, r.at); err != nil {
return err
}
var approvedBy sql.NullString
var reviewedAt sql.NullInt64
if !review {
by := antennaclaim.ApprovedByAuto
if e.ClearOnly() {
by = antennaclaim.ApprovedByOwner
}
approvedBy, reviewedAt = sql.NullString{String: by, Valid: true}, sql.NullInt64{Int64: nowMs, Valid: true}
}
_, err := tx.ExecContext(ctx, `UPDATE node_antenna_claims SET status = ?, proven_at = ?, proof_lat = ?, proof_lon = ?,
reviewed_at = ?, approved_by = ?, via = 'link', account_id = ?, link_id = ? WHERE request_id = ?`,
status, r.at, r.lat, r.lon, reviewedAt, approvedBy, r.account, r.link, id)
return err
}

// putInForceByEditTime runs after approved row id (edit time at) was
// stored: it takes each part it carries unless a row in force for that part
// was edited later (created_at as proven_at, then request_id), retires that
// part from the other rows, and supersedes the rows left with nothing in
// force, itself included.
func putInForceByEditTime(ctx context.Context, tx *sql.Tx, pk, id string, at, nowMs int64) error {
const newer = `SELECT EXISTS(SELECT 1 FROM node_antenna_claims WHERE pubkey = ?1 AND status = 'approved' AND request_id != ?2
AND %s = 1 AND (proven_at > ?3 OR (proven_at = ?3 AND request_id > ?2)))`
var newerHeight, newerDetails bool
if err := tx.QueryRowContext(ctx, strings.Replace(newer, "%s", "height_in_force", 1), pk, id, at).Scan(&newerHeight); err != nil {
return err
}
if err := tx.QueryRowContext(ctx, strings.Replace(newer, "%s", "details_in_force", 1), pk, id, at).Scan(&newerDetails); err != nil {
return err
}
var takesHeight, takesDetails bool
if err := tx.QueryRowContext(ctx, `UPDATE node_antenna_claims
SET height_in_force = (height_op IS NOT NULL AND NOT ?), details_in_force = (details_op IS NOT NULL AND NOT ?)
WHERE request_id = ? RETURNING height_in_force, details_in_force`, newerHeight, newerDetails, id).Scan(&takesHeight, &takesDetails); err != nil {
return err
}
if !takesHeight && !takesDetails {
if _, err := tx.ExecContext(ctx, `UPDATE node_antenna_claims SET status = 'superseded' WHERE request_id = ?`, id); err != nil {
return err
}
return dropContacts(ctx, tx, id)
}
return retireOthers(ctx, tx, pk, id, takesHeight, takesDetails, nowMs)
}
Loading
Loading