package verify import ( "encoding/hex" "encoding/json" "errors" "fmt" ) // Dossier is everything a verdict is decided from, in one JSON document: the signed terms, the // counterparty's transactions, and the per-source facts a page fetched. The page gathers facts // because a browser owns the network; this package decides, because the decision must be the same // whether it runs in a page or a test. type Dossier struct { Terms TermsJSON `json:"terms"` Legs []LegJSON `json:"legs"` Need int `json:"need"` Sources []SourceJSON `json:"sources"` } // TermsJSON is the signed terms with binary fields in hex. type TermsJSON struct { HashLock string `json:"hash_lock"` TimeoutBTC uint32 `json:"timeout_btc"` TimeoutXBT uint32 `json:"timeout_xbt"` AmountBTC uint64 `json:"amount_btc"` AmountXBT uint64 `json:"amount_xbt"` FeeBTC uint64 `json:"fee_btc"` FeeXBT uint64 `json:"fee_xbt"` ClaimerBTC string `json:"claimer_btc"` RefunderBTC string `json:"refunder_btc"` ClaimerXBT string `json:"claimer_xbt"` RefunderXBT string `json:"refunder_xbt"` MinTimeoutGap uint32 `json:"min_timeout_gap"` } // LegJSON is one leg as supplied. type LegJSON struct { Chain string `json:"chain"` Funding string `json:"funding"` Refund string `json:"refund"` Claim string `json:"claim"` Timeout uint32 `json:"timeout"` Amount uint64 `json:"amount"` Fee uint64 `json:"fee"` HashLock string `json:"hash_lock"` Claimer string `json:"claimer"` Refunder string `json:"refunder"` ChangeScripts []string `json:"change_scripts"` } // SourceJSON is one indexer's answers, keyed by display txid. type SourceJSON struct { Name string `json:"name"` Facts map[string]FactJSON `json:"facts"` } // FactJSON is one indexer's answer about one transaction. type FactJSON struct { Found bool `json:"found"` Hex string `json:"hex"` Height int64 `json:"height"` Confirmations int64 `json:"confirmations"` } // AdjudicateJSON is the entry point the page uses: JSON in, report JSON out. func AdjudicateJSON(body []byte) ([]byte, error) { var dossier Dossier if err := json.Unmarshal(body, &dossier); err != nil { return nil, fmt.Errorf("verify: the dossier is not JSON: %w", err) } report, err := Adjudicate(dossier) if err != nil { return nil, err } return json.Marshal(report) } // Adjudicate runs the whole verdict: external agreement over the supplied facts, then every local // commitment check. func Adjudicate(d Dossier) (Report, error) { var report Report terms, legs, err := d.parse() if err != nil { return report, err } report.SourcesUsed = make([]string, 0, len(d.Sources)) report.Quorum = d.Need for _, source := range d.Sources { report.SourcesUsed = append(report.SourcesUsed, source.Name) } report.Independence.Warnings = append(report.Independence.Warnings, "independence was not established: this verdict was decided from facts supplied by the page") // One source is what the forked chain has today. That is a warning, not a refusal: the facts // are still hash-verified, and saying so plainly is more useful than pretending a quorum // exists where it does not. if len(d.Sources) < 2 { report.LocalWarn("source_independence", fmt.Sprintf( "%d source(s): existence is hash-verified, but agreement between independent sources is not possible", len(d.Sources))) } else { report.Local("source_independence", "the facts came from independent sources", nil) } // Every transaction the verdict depends on must exist, at an agreed height, with bytes that // hash to its id. for _, leg := range legs { for _, part := range []struct { label string raw []byte }{ {"funding", leg.Funding}, {"refund", leg.Refund}, {"claim", leg.Claim}, } { if len(part.raw) == 0 { report.External(leg.Chain+"_"+part.label+"_exists", "the "+part.label+" transaction was supplied", nil, fmt.Errorf("%w: no %s transaction", ErrUnverifiable, part.label)) continue } txid, err := TxidOf(part.raw) if err != nil { report.External(leg.Chain+"_"+part.label+"_exists", "the "+part.label+" transaction decodes", nil, err) continue } agreed, sources, err := agreement(txid, d.Sources, d.Need) detail := fmt.Sprintf("%s %s", leg.Chain, part.label) if len(agreed) > 0 { detail += fmt.Sprintf(" found at height %d", agreed[0]) } report.External(leg.Chain+"_"+part.label+"_exists", detail, sources, err) if err == nil { report.Agreement = len(sources) } } } terms.Verify(&report, legs) return report, nil } func agreement(txid [32]byte, sources []SourceJSON, need int) ([]int64, []string, error) { var heights []int64 var names []string absent := 0 for _, source := range sources { fact, ok := source.Facts[Hash(txid)] if !ok { continue } if !fact.Found { absent++ continue } raw, err := hex.DecodeString(fact.Hex) if err != nil { return nil, nil, fmt.Errorf("%w: %s returned non-hex bytes", ErrDisagree, source.Name) } got, err := TxidOf(raw) if err != nil || got != txid { return nil, nil, fmt.Errorf("%w: %s returned bytes that are not %s", ErrDisagree, source.Name, Hash(txid)) } heights = append(heights, fact.Height) names = append(names, source.Name) } if need < 2 { // A single source cannot prove independence; it can still prove the bytes it returned // are the transaction that was asked for. The caller was told so by the report. if len(names) == 0 { return nil, names, fmt.Errorf("%w: no source found %s", ErrUnverifiable, Hash(txid)) } heights = heights[:1] return heights, names, nil } // Absence only contradicts someone who claims to have found it. When nobody found it, the // answer is that the sample did not contain it, which is unverifiable rather than a conflict. if absent > 0 && len(names) > 0 { return nil, names, fmt.Errorf("%w: %s found by %v but not by %d other source(s)", ErrDisagree, Hash(txid), names, absent) } if absent > 0 { return nil, names, fmt.Errorf("%w: %d of %d sources did not find %s", ErrUnverifiable, absent, len(sources), Hash(txid)) } if len(names) < need { return nil, names, fmt.Errorf("%w: %d of %d sources found %s, %d needed", ErrUnverifiable, len(names), len(sources), Hash(txid), need) } for i := 1; i < len(heights); i++ { if heights[i] != heights[0] { return nil, names, fmt.Errorf("%w: sources disagree on the height of %s", ErrDisagree, Hash(txid)) } } return heights, names, nil } func (d Dossier) parse() (Terms, []Leg, error) { hashLock, err := parseHash(d.Terms.HashLock) if err != nil { return Terms{}, nil, fmt.Errorf("verify: hash lock: %w", err) } terms := Terms{ HashLock: hashLock, TimeoutBTC: d.Terms.TimeoutBTC, TimeoutXBT: d.Terms.TimeoutXBT, AmountBTC: d.Terms.AmountBTC, AmountXBT: d.Terms.AmountXBT, FeeBTC: d.Terms.FeeBTC, FeeXBT: d.Terms.FeeXBT, MinTimeoutGap: d.Terms.MinTimeoutGap, } for _, field := range []struct { name string text string dst *[]byte }{ {"claimer_btc", d.Terms.ClaimerBTC, &terms.ClaimerBTC}, {"refunder_btc", d.Terms.RefunderBTC, &terms.RefunderBTC}, {"claimer_xbt", d.Terms.ClaimerXBT, &terms.ClaimerXBT}, {"refunder_xbt", d.Terms.RefunderXBT, &terms.RefunderXBT}, } { raw, err := hex.DecodeString(field.text) if err != nil || len(raw) != 33 { return Terms{}, nil, fmt.Errorf("verify: %s: a 33-byte compressed key is required", field.name) } *field.dst = raw } legs := make([]Leg, 0, len(d.Legs)) for i, leg := range d.Legs { funding, err := hex.DecodeString(leg.Funding) if err != nil { return Terms{}, nil, fmt.Errorf("verify: leg %d funding: %w", i, err) } refund, err := hex.DecodeString(leg.Refund) if err != nil { return Terms{}, nil, fmt.Errorf("verify: leg %d refund: %w", i, err) } claim, err := hex.DecodeString(leg.Claim) if err != nil { return Terms{}, nil, fmt.Errorf("verify: leg %d claim: %w", i, err) } legHash, err := parseHash(leg.HashLock) if err != nil { return Terms{}, nil, fmt.Errorf("verify: leg %d hash lock: %w", i, err) } claimer, err := hex.DecodeString(leg.Claimer) if err != nil { return Terms{}, nil, fmt.Errorf("verify: leg %d claimer: %w", i, err) } refunder, err := hex.DecodeString(leg.Refunder) if err != nil { return Terms{}, nil, fmt.Errorf("verify: leg %d refunder: %w", i, err) } change := make([][]byte, 0, len(leg.ChangeScripts)) for _, text := range leg.ChangeScripts { script, err := hex.DecodeString(text) if err != nil { return Terms{}, nil, fmt.Errorf("verify: leg %d change script: %w", i, err) } change = append(change, script) } legs = append(legs, Leg{ Chain: leg.Chain, Funding: funding, Refund: refund, Claim: claim, Timeout: leg.Timeout, Amount: leg.Amount, Fee: leg.Fee, HashLock: legHash, Claimer: claimer, Refunder: refunder, ChangeScripts: change, }) } if len(legs) != 2 { return Terms{}, nil, errors.New("verify: a swap has exactly two legs") } return terms, legs, nil } func parseHash(text string) ([32]byte, error) { var out [32]byte raw, err := hex.DecodeString(text) if err != nil { return out, err } if len(raw) != 32 { return out, fmt.Errorf("%d bytes", len(raw)) } copy(out[:], raw) return out, nil }