sources.go raw

   1  package verify
   2  
   3  import (
   4  	"context"
   5  	"crypto/sha256"
   6  	"errors"
   7  	"fmt"
   8  	"sort"
   9  	"strings"
  10  
  11  	"git.smesh.lol/nostrino/pkg/btcwire"
  12  
  13  	"git.smesh.lol/tinywallet/pkg/tx"
  14  )
  15  
  16  // ErrUnverifiable marks a fact that could not be established: nothing was contradicted, but
  17  // nothing was proven either.
  18  var ErrUnverifiable = errors.New("verify: the fact could not be verified")
  19  
  20  // ErrDisagree is returned when the sources do not agree. It is never softened into a warning:
  21  // disagreement about whether a transaction exists is what an attacker buys with a fake chain.
  22  var ErrDisagree = errors.New("verify: the sources disagree")
  23  
  24  // Tip is one source's view of the chain head.
  25  type Tip struct {
  26  	Height int64
  27  	Hash   [32]byte
  28  }
  29  
  30  // TxFact is one source's answer about one transaction.
  31  type TxFact struct {
  32  	// Found says whether the source claims the transaction exists.
  33  	Found bool
  34  	// Raw is the complete transaction as the source returned it. It is required for a positive
  35  	// answer: a lookup that cannot be hashed back to the txid is worthless.
  36  	Raw []byte
  37  	// Height is the block the transaction is in, or zero.
  38  	Height int64
  39  	// Confirmations is the depth the source claims at the time it answered.
  40  	Confirmations int64
  41  }
  42  
  43  // Source is one independent indexer. Implementations must not be the venue's own gateway.
  44  type Source interface {
  45  	// Name identifies the operator, not the proxy in front of it.
  46  	Name() string
  47  	// Tx asks about one transaction.
  48  	Tx(ctx context.Context, txid [32]byte) (TxFact, error)
  49  	// Tip asks for the chain head.
  50  	Tip(ctx context.Context) (Tip, error)
  51  	// FeeEstimate asks for a fee rate in satoshis per virtual byte.
  52  	FeeEstimate(ctx context.Context) (int64, error)
  53  }
  54  
  55  // Quorum is the source set and how many must agree.
  56  type Quorum struct {
  57  	Sources []Source
  58  	Need    int
  59  }
  60  
  61  // Facts asks the sources and enforces agreement.
  62  type Facts struct {
  63  	quorum Quorum
  64  }
  65  
  66  // NewFacts builds the external engine. A need below one is refused: a single source is not a
  67  // quorum, and defaulting to one silently would defeat the package.
  68  func NewFacts(sources []Source, need int) (*Facts, error) {
  69  	if len(sources) < 2 {
  70  		return nil, errors.New("verify: at least two independent sources are required")
  71  	}
  72  
  73  	if need < 2 {
  74  		return nil, fmt.Errorf("verify: a quorum of %d is not independent", need)
  75  	}
  76  
  77  	if need > len(sources) {
  78  		return nil, fmt.Errorf("verify: a quorum of %d needs %d sources", need, len(sources))
  79  	}
  80  
  81  	names := map[string]bool{}
  82  
  83  	for _, source := range sources {
  84  		name := strings.TrimSpace(source.Name())
  85  
  86  		if name == "" {
  87  			return nil, errors.New("verify: a source has no name")
  88  		}
  89  
  90  		if names[name] {
  91  			return nil, fmt.Errorf("verify: source %q is configured twice", name)
  92  		}
  93  
  94  		names[name] = true
  95  	}
  96  
  97  	return &Facts{quorum: Quorum{Sources: sources, Need: need}}, nil
  98  }
  99  
 100  // Sources lists the configured source names.
 101  func (f *Facts) Sources() []string {
 102  	out := make([]string, 0, len(f.quorum.Sources))
 103  
 104  	for _, source := range f.quorum.Sources {
 105  		out = append(out, source.Name())
 106  	}
 107  
 108  	sort.Strings(out)
 109  
 110  	return out
 111  }
 112  
 113  // TxidOf returns the txid of a serialized transaction, computed here rather than trusted from the
 114  // source. A witness serialization hashes to the same txid as its non-witness form.
 115  func TxidOf(raw []byte) ([32]byte, error) {
 116  	parsed, err := tx.Decode(raw)
 117  
 118  	if err != nil {
 119  		return [32]byte{}, fmt.Errorf("verify: the transaction does not decode: %w", err)
 120  	}
 121  
 122  	id, err := parsed.TxID()
 123  
 124  	if err != nil {
 125  		return [32]byte{}, fmt.Errorf("verify: the transaction has no id: %w", err)
 126  	}
 127  
 128  	return id, nil
 129  }
 130  
 131  // TxAnswer is an agreed transaction fact.
 132  type TxAnswer struct {
 133  	TxID          [32]byte
 134  	Found         bool
 135  	Height        int64
 136  	Confirmations int64
 137  	// Sources that agreed, and those that disagreed, by name.
 138  	Agreed  []string
 139  	Dissent []string
 140  	// Verified says the bytes hashed back to the requested txid.
 141  	Verified bool
 142  }
 143  
 144  // Tx asks every source and returns the answer only if a quorum of them agree and every positive
 145  // answer's bytes hash to the requested txid.
 146  func (f *Facts) Tx(ctx context.Context, txid [32]byte) (TxAnswer, error) {
 147  	type answer struct {
 148  		name string
 149  		fact TxFact
 150  		err  error
 151  	}
 152  
 153  	answers := make([]answer, 0, len(f.quorum.Sources))
 154  
 155  	for _, source := range f.quorum.Sources {
 156  		fact, err := source.Tx(ctx, txid)
 157  		answers = append(answers, answer{name: source.Name(), fact: fact, err: err})
 158  	}
 159  
 160  	// A positive answer whose bytes do not hash to the txid is a lie about which transaction
 161  	// it is, and it poisons the whole answer rather than counting as dissent.
 162  	found := make([]string, 0, len(answers))
 163  	absent := make([]string, 0, len(answers))
 164  	heights := map[int64][]string{}
 165  	var raw []byte
 166  
 167  	for _, a := range answers {
 168  		if a.err != nil {
 169  			continue
 170  		}
 171  
 172  		if !a.fact.Found {
 173  			absent = append(absent, a.name)
 174  			continue
 175  		}
 176  
 177  		if len(a.fact.Raw) == 0 {
 178  			return TxAnswer{}, fmt.Errorf("%w: %s returned no transaction bytes", ErrUnverifiable, a.name)
 179  		}
 180  
 181  		if got, err := TxidOf(a.fact.Raw); err != nil || got != txid {
 182  			return TxAnswer{}, fmt.Errorf("%w: %s returned bytes that are not %s",
 183  				ErrDisagree, a.name, Hash(txid))
 184  		}
 185  
 186  		found = append(found, a.name)
 187  		heights[a.fact.Height] = append(heights[a.fact.Height], a.name)
 188  
 189  		if raw == nil {
 190  			raw = a.fact.Raw
 191  		}
 192  	}
 193  
 194  	if len(found) == 0 && len(absent) == 0 {
 195  		return TxAnswer{}, fmt.Errorf("%w: no source answered for %s", ErrUnverifiable, Hash(txid))
 196  	}
 197  
 198  	// A split answer is disagreement, whatever the majority: one source contradicting another
 199  	// about whether a transaction exists is the attack, not a shortfall of evidence.
 200  	if len(found) > 0 && len(absent) > 0 {
 201  		return TxAnswer{}, fmt.Errorf("%w: %s found by %v but absent from %v",
 202  			ErrDisagree, Hash(txid), found, absent)
 203  	}
 204  
 205  	if len(found) >= len(absent) {
 206  		if len(found) < f.quorum.Need {
 207  			return TxAnswer{}, fmt.Errorf("%w: %d of %d sources found %s, %d needed",
 208  				ErrUnverifiable, len(found), len(answers), Hash(txid), f.quorum.Need)
 209  		}
 210  
 211  		if len(heights) > 1 {
 212  			return TxAnswer{}, fmt.Errorf("%w: sources put %s at different heights %v",
 213  				ErrDisagree, Hash(txid), heights)
 214  		}
 215  
 216  		answer := TxAnswer{TxID: txid, Found: true, Agreed: found, Verified: true}
 217  
 218  		for height := range heights {
 219  			answer.Height = height
 220  		}
 221  
 222  		// Confirmations are the smallest the sources claim, because a deeper claim than the
 223  		// chain supports is the kind that unlocks a refund early.
 224  		for _, a := range answers {
 225  			if a.err == nil && a.fact.Found && a.fact.Confirmations > 0 &&
 226  				(answer.Confirmations == 0 || a.fact.Confirmations < answer.Confirmations) {
 227  				answer.Confirmations = a.fact.Confirmations
 228  			}
 229  		}
 230  
 231  		return answer, nil
 232  	}
 233  
 234  	// The majority says absent. That is a fact about the sample, not about the chain.
 235  	return TxAnswer{}, fmt.Errorf("%w: %d of %d sources did not find %s",
 236  		ErrUnverifiable, len(absent), len(answers), Hash(txid))
 237  }
 238  
 239  // Absence records what a negative answer covered.
 240  type Absence struct {
 241  	TxID [32]byte
 242  	// Sources that answered at all, and how many of them found nothing.
 243  	Answered int
 244  	Absent   int
 245  	// LooksIndependent is the cross-source check at the time of the answer.
 246  	LooksIndependent bool
 247  	// Detail is one line the UI can show.
 248  	Detail string
 249  }
 250  
 251  // Lookup is the user-facing form: it returns the answer, or an absence record, or an error that
 252  // must block.
 253  func (f *Facts) Lookup(ctx context.Context, txid [32]byte) (TxAnswer, Absence, error) {
 254  	answer, err := f.Tx(ctx, txid)
 255  
 256  	if err == nil {
 257  		return answer, Absence{}, nil
 258  	}
 259  
 260  	if !errors.Is(err, ErrUnverifiable) {
 261  		return TxAnswer{}, Absence{}, err
 262  	}
 263  
 264  	independence, indErr := f.Independence(ctx)
 265  	absence := Absence{
 266  		TxID:     txid,
 267  		Answered: len(f.quorum.Sources),
 268  		Detail: fmt.Sprintf("%s was not found by the sampled sources; that is a probability, not proof",
 269  			Hash(txid)),
 270  	}
 271  
 272  	if indErr == nil {
 273  		absence.LooksIndependent = independence.DistinctTips >= 2
 274  	}
 275  
 276  	return TxAnswer{}, absence, err
 277  }
 278  
 279  // Independence is the check that the sources are not one backend behind several names.
 280  type Independence struct {
 281  	Tips []Tip
 282  	// DistinctTips counts different tip hashes, which is the cheapest sign of separate chains
 283  	// of information.
 284  	DistinctTips int
 285  	// SameHeight is how many sources report the same height.
 286  	SameHeight int
 287  	Warnings   []string
 288  }
 289  
 290  // Independence compares the sources' chain heads and fee estimates.
 291  func (f *Facts) Independence(ctx context.Context) (Independence, error) {
 292  	out := Independence{}
 293  	hashes := map[[32]byte]bool{}
 294  	heights := map[int64]int{}
 295  
 296  	for _, source := range f.quorum.Sources {
 297  		tip, err := source.Tip(ctx)
 298  
 299  		if err != nil {
 300  			out.Warnings = append(out.Warnings, source.Name()+": no tip: "+err.Error())
 301  			continue
 302  		}
 303  
 304  		out.Tips = append(out.Tips, tip)
 305  		hashes[tip.Hash] = true
 306  		heights[tip.Height]++
 307  	}
 308  
 309  	out.DistinctTips = len(hashes)
 310  
 311  	for height, count := range heights {
 312  		if count > out.SameHeight {
 313  			out.SameHeight = count
 314  			_ = height
 315  		}
 316  	}
 317  
 318  	// A shared tip hash is the expected state on one chain: honest nodes at the same height name
 319  	// the same block. What would be suspicious is every source agreeing on everything, including
 320  	// the numbers that differ between independent mempools, so height and fee are checked together
 321  	// by the caller and reported here as a heuristic only.
 322  	if len(out.Tips) >= 2 && out.DistinctTips == 1 {
 323  		out.Warnings = append(out.Warnings,
 324  			"every source reports the same tip hash, which is normal on one chain and is not evidence of a shared backend")
 325  	}
 326  
 327  	return out, nil
 328  }
 329  
 330  // FeeAnswer is an agreed fee rate.
 331  type FeeAnswer struct {
 332  	Rate   int64
 333  	Agreed []string
 334  }
 335  
 336  // Fee asks the sources for a fee rate and requires agreement within tolerance.
 337  func (f *Facts) Fee(ctx context.Context, tolerance int64) (FeeAnswer, error) {
 338  	type estimate struct {
 339  		name string
 340  		rate int64
 341  		err  error
 342  	}
 343  
 344  	var estimates []estimate
 345  
 346  	for _, source := range f.quorum.Sources {
 347  		rate, err := source.FeeEstimate(ctx)
 348  		estimates = append(estimates, estimate{name: source.Name(), rate: rate, err: err})
 349  	}
 350  
 351  	var agreed []string
 352  	var low, high int64
 353  
 354  	for _, e := range estimates {
 355  		if e.err != nil || e.rate <= 0 {
 356  			continue
 357  		}
 358  
 359  		if len(agreed) == 0 {
 360  			low, high = e.rate, e.rate
 361  		}
 362  
 363  		if e.rate < low {
 364  			low = e.rate
 365  		}
 366  
 367  		if e.rate > high {
 368  			high = e.rate
 369  		}
 370  
 371  		agreed = append(agreed, e.name)
 372  	}
 373  
 374  	if len(agreed) < f.quorum.Need {
 375  		return FeeAnswer{}, fmt.Errorf("%w: %d of %d sources gave a fee rate", ErrUnverifiable,
 376  			len(agreed), len(estimates))
 377  	}
 378  
 379  	if high-low > tolerance {
 380  		return FeeAnswer{}, fmt.Errorf("%w: fee rates span %d..%d sat/vB", ErrDisagree, low, high)
 381  	}
 382  
 383  	return FeeAnswer{Rate: (low + high) / 2, Agreed: agreed}, nil
 384  }
 385  
 386  // DoubleSHA256 is exported for adapters that must hash a transaction themselves.
 387  func DoubleSHA256(b []byte) [32]byte {
 388  	first := sha256.Sum256(b)
 389  	return sha256.Sum256(first[:])
 390  }
 391  
 392  var _ = btcwire.BlockHeaderSize
 393