package verify import ( "context" "crypto/sha256" "errors" "fmt" "sort" "strings" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/tinywallet/pkg/tx" ) // ErrUnverifiable marks a fact that could not be established: nothing was contradicted, but // nothing was proven either. var ErrUnverifiable = errors.New("verify: the fact could not be verified") // ErrDisagree is returned when the sources do not agree. It is never softened into a warning: // disagreement about whether a transaction exists is what an attacker buys with a fake chain. var ErrDisagree = errors.New("verify: the sources disagree") // Tip is one source's view of the chain head. type Tip struct { Height int64 Hash [32]byte } // TxFact is one source's answer about one transaction. type TxFact struct { // Found says whether the source claims the transaction exists. Found bool // Raw is the complete transaction as the source returned it. It is required for a positive // answer: a lookup that cannot be hashed back to the txid is worthless. Raw []byte // Height is the block the transaction is in, or zero. Height int64 // Confirmations is the depth the source claims at the time it answered. Confirmations int64 } // Source is one independent indexer. Implementations must not be the venue's own gateway. type Source interface { // Name identifies the operator, not the proxy in front of it. Name() string // Tx asks about one transaction. Tx(ctx context.Context, txid [32]byte) (TxFact, error) // Tip asks for the chain head. Tip(ctx context.Context) (Tip, error) // FeeEstimate asks for a fee rate in satoshis per virtual byte. FeeEstimate(ctx context.Context) (int64, error) } // Quorum is the source set and how many must agree. type Quorum struct { Sources []Source Need int } // Facts asks the sources and enforces agreement. type Facts struct { quorum Quorum } // NewFacts builds the external engine. A need below one is refused: a single source is not a // quorum, and defaulting to one silently would defeat the package. func NewFacts(sources []Source, need int) (*Facts, error) { if len(sources) < 2 { return nil, errors.New("verify: at least two independent sources are required") } if need < 2 { return nil, fmt.Errorf("verify: a quorum of %d is not independent", need) } if need > len(sources) { return nil, fmt.Errorf("verify: a quorum of %d needs %d sources", need, len(sources)) } names := map[string]bool{} for _, source := range sources { name := strings.TrimSpace(source.Name()) if name == "" { return nil, errors.New("verify: a source has no name") } if names[name] { return nil, fmt.Errorf("verify: source %q is configured twice", name) } names[name] = true } return &Facts{quorum: Quorum{Sources: sources, Need: need}}, nil } // Sources lists the configured source names. func (f *Facts) Sources() []string { out := make([]string, 0, len(f.quorum.Sources)) for _, source := range f.quorum.Sources { out = append(out, source.Name()) } sort.Strings(out) return out } // TxidOf returns the txid of a serialized transaction, computed here rather than trusted from the // source. A witness serialization hashes to the same txid as its non-witness form. func TxidOf(raw []byte) ([32]byte, error) { parsed, err := tx.Decode(raw) if err != nil { return [32]byte{}, fmt.Errorf("verify: the transaction does not decode: %w", err) } id, err := parsed.TxID() if err != nil { return [32]byte{}, fmt.Errorf("verify: the transaction has no id: %w", err) } return id, nil } // TxAnswer is an agreed transaction fact. type TxAnswer struct { TxID [32]byte Found bool Height int64 Confirmations int64 // Sources that agreed, and those that disagreed, by name. Agreed []string Dissent []string // Verified says the bytes hashed back to the requested txid. Verified bool } // Tx asks every source and returns the answer only if a quorum of them agree and every positive // answer's bytes hash to the requested txid. func (f *Facts) Tx(ctx context.Context, txid [32]byte) (TxAnswer, error) { type answer struct { name string fact TxFact err error } answers := make([]answer, 0, len(f.quorum.Sources)) for _, source := range f.quorum.Sources { fact, err := source.Tx(ctx, txid) answers = append(answers, answer{name: source.Name(), fact: fact, err: err}) } // A positive answer whose bytes do not hash to the txid is a lie about which transaction // it is, and it poisons the whole answer rather than counting as dissent. found := make([]string, 0, len(answers)) absent := make([]string, 0, len(answers)) heights := map[int64][]string{} var raw []byte for _, a := range answers { if a.err != nil { continue } if !a.fact.Found { absent = append(absent, a.name) continue } if len(a.fact.Raw) == 0 { return TxAnswer{}, fmt.Errorf("%w: %s returned no transaction bytes", ErrUnverifiable, a.name) } if got, err := TxidOf(a.fact.Raw); err != nil || got != txid { return TxAnswer{}, fmt.Errorf("%w: %s returned bytes that are not %s", ErrDisagree, a.name, Hash(txid)) } found = append(found, a.name) heights[a.fact.Height] = append(heights[a.fact.Height], a.name) if raw == nil { raw = a.fact.Raw } } if len(found) == 0 && len(absent) == 0 { return TxAnswer{}, fmt.Errorf("%w: no source answered for %s", ErrUnverifiable, Hash(txid)) } // A split answer is disagreement, whatever the majority: one source contradicting another // about whether a transaction exists is the attack, not a shortfall of evidence. if len(found) > 0 && len(absent) > 0 { return TxAnswer{}, fmt.Errorf("%w: %s found by %v but absent from %v", ErrDisagree, Hash(txid), found, absent) } if len(found) >= len(absent) { if len(found) < f.quorum.Need { return TxAnswer{}, fmt.Errorf("%w: %d of %d sources found %s, %d needed", ErrUnverifiable, len(found), len(answers), Hash(txid), f.quorum.Need) } if len(heights) > 1 { return TxAnswer{}, fmt.Errorf("%w: sources put %s at different heights %v", ErrDisagree, Hash(txid), heights) } answer := TxAnswer{TxID: txid, Found: true, Agreed: found, Verified: true} for height := range heights { answer.Height = height } // Confirmations are the smallest the sources claim, because a deeper claim than the // chain supports is the kind that unlocks a refund early. for _, a := range answers { if a.err == nil && a.fact.Found && a.fact.Confirmations > 0 && (answer.Confirmations == 0 || a.fact.Confirmations < answer.Confirmations) { answer.Confirmations = a.fact.Confirmations } } return answer, nil } // The majority says absent. That is a fact about the sample, not about the chain. return TxAnswer{}, fmt.Errorf("%w: %d of %d sources did not find %s", ErrUnverifiable, len(absent), len(answers), Hash(txid)) } // Absence records what a negative answer covered. type Absence struct { TxID [32]byte // Sources that answered at all, and how many of them found nothing. Answered int Absent int // LooksIndependent is the cross-source check at the time of the answer. LooksIndependent bool // Detail is one line the UI can show. Detail string } // Lookup is the user-facing form: it returns the answer, or an absence record, or an error that // must block. func (f *Facts) Lookup(ctx context.Context, txid [32]byte) (TxAnswer, Absence, error) { answer, err := f.Tx(ctx, txid) if err == nil { return answer, Absence{}, nil } if !errors.Is(err, ErrUnverifiable) { return TxAnswer{}, Absence{}, err } independence, indErr := f.Independence(ctx) absence := Absence{ TxID: txid, Answered: len(f.quorum.Sources), Detail: fmt.Sprintf("%s was not found by the sampled sources; that is a probability, not proof", Hash(txid)), } if indErr == nil { absence.LooksIndependent = independence.DistinctTips >= 2 } return TxAnswer{}, absence, err } // Independence is the check that the sources are not one backend behind several names. type Independence struct { Tips []Tip // DistinctTips counts different tip hashes, which is the cheapest sign of separate chains // of information. DistinctTips int // SameHeight is how many sources report the same height. SameHeight int Warnings []string } // Independence compares the sources' chain heads and fee estimates. func (f *Facts) Independence(ctx context.Context) (Independence, error) { out := Independence{} hashes := map[[32]byte]bool{} heights := map[int64]int{} for _, source := range f.quorum.Sources { tip, err := source.Tip(ctx) if err != nil { out.Warnings = append(out.Warnings, source.Name()+": no tip: "+err.Error()) continue } out.Tips = append(out.Tips, tip) hashes[tip.Hash] = true heights[tip.Height]++ } out.DistinctTips = len(hashes) for height, count := range heights { if count > out.SameHeight { out.SameHeight = count _ = height } } // A shared tip hash is the expected state on one chain: honest nodes at the same height name // the same block. What would be suspicious is every source agreeing on everything, including // the numbers that differ between independent mempools, so height and fee are checked together // by the caller and reported here as a heuristic only. if len(out.Tips) >= 2 && out.DistinctTips == 1 { out.Warnings = append(out.Warnings, "every source reports the same tip hash, which is normal on one chain and is not evidence of a shared backend") } return out, nil } // FeeAnswer is an agreed fee rate. type FeeAnswer struct { Rate int64 Agreed []string } // Fee asks the sources for a fee rate and requires agreement within tolerance. func (f *Facts) Fee(ctx context.Context, tolerance int64) (FeeAnswer, error) { type estimate struct { name string rate int64 err error } var estimates []estimate for _, source := range f.quorum.Sources { rate, err := source.FeeEstimate(ctx) estimates = append(estimates, estimate{name: source.Name(), rate: rate, err: err}) } var agreed []string var low, high int64 for _, e := range estimates { if e.err != nil || e.rate <= 0 { continue } if len(agreed) == 0 { low, high = e.rate, e.rate } if e.rate < low { low = e.rate } if e.rate > high { high = e.rate } agreed = append(agreed, e.name) } if len(agreed) < f.quorum.Need { return FeeAnswer{}, fmt.Errorf("%w: %d of %d sources gave a fee rate", ErrUnverifiable, len(agreed), len(estimates)) } if high-low > tolerance { return FeeAnswer{}, fmt.Errorf("%w: fee rates span %d..%d sat/vB", ErrDisagree, low, high) } return FeeAnswer{Rate: (low + high) / 2, Agreed: agreed}, nil } // DoubleSHA256 is exported for adapters that must hash a transaction themselves. func DoubleSHA256(b []byte) [32]byte { first := sha256.Sum256(b) return sha256.Sum256(first[:]) } var _ = btcwire.BlockHeaderSize