dossier.go raw
1 package verify
2
3 import (
4 "encoding/hex"
5 "encoding/json"
6 "errors"
7 "fmt"
8 )
9
10 // Dossier is everything a verdict is decided from, in one JSON document: the signed terms, the
11 // counterparty's transactions, and the per-source facts a page fetched. The page gathers facts
12 // because a browser owns the network; this package decides, because the decision must be the same
13 // whether it runs in a page or a test.
14 type Dossier struct {
15 Terms TermsJSON `json:"terms"`
16 Legs []LegJSON `json:"legs"`
17 Need int `json:"need"`
18 Sources []SourceJSON `json:"sources"`
19 }
20
21 // TermsJSON is the signed terms with binary fields in hex.
22 type TermsJSON struct {
23 HashLock string `json:"hash_lock"`
24 TimeoutBTC uint32 `json:"timeout_btc"`
25 TimeoutXBT uint32 `json:"timeout_xbt"`
26 AmountBTC uint64 `json:"amount_btc"`
27 AmountXBT uint64 `json:"amount_xbt"`
28 FeeBTC uint64 `json:"fee_btc"`
29 FeeXBT uint64 `json:"fee_xbt"`
30 ClaimerBTC string `json:"claimer_btc"`
31 RefunderBTC string `json:"refunder_btc"`
32 ClaimerXBT string `json:"claimer_xbt"`
33 RefunderXBT string `json:"refunder_xbt"`
34 MinTimeoutGap uint32 `json:"min_timeout_gap"`
35 }
36
37 // LegJSON is one leg as supplied.
38 type LegJSON struct {
39 Chain string `json:"chain"`
40 Funding string `json:"funding"`
41 Refund string `json:"refund"`
42 Claim string `json:"claim"`
43 Timeout uint32 `json:"timeout"`
44 Amount uint64 `json:"amount"`
45 Fee uint64 `json:"fee"`
46 HashLock string `json:"hash_lock"`
47 Claimer string `json:"claimer"`
48 Refunder string `json:"refunder"`
49 ChangeScripts []string `json:"change_scripts"`
50 }
51
52 // SourceJSON is one indexer's answers, keyed by display txid.
53 type SourceJSON struct {
54 Name string `json:"name"`
55 Facts map[string]FactJSON `json:"facts"`
56 }
57
58 // FactJSON is one indexer's answer about one transaction.
59 type FactJSON struct {
60 Found bool `json:"found"`
61 Hex string `json:"hex"`
62 Height int64 `json:"height"`
63 Confirmations int64 `json:"confirmations"`
64 }
65
66 // AdjudicateJSON is the entry point the page uses: JSON in, report JSON out.
67 func AdjudicateJSON(body []byte) ([]byte, error) {
68 var dossier Dossier
69
70 if err := json.Unmarshal(body, &dossier); err != nil {
71 return nil, fmt.Errorf("verify: the dossier is not JSON: %w", err)
72 }
73
74 report, err := Adjudicate(dossier)
75
76 if err != nil {
77 return nil, err
78 }
79
80 return json.Marshal(report)
81 }
82
83 // Adjudicate runs the whole verdict: external agreement over the supplied facts, then every local
84 // commitment check.
85 func Adjudicate(d Dossier) (Report, error) {
86 var report Report
87
88 terms, legs, err := d.parse()
89
90 if err != nil {
91 return report, err
92 }
93
94 report.SourcesUsed = make([]string, 0, len(d.Sources))
95 report.Quorum = d.Need
96
97 for _, source := range d.Sources {
98 report.SourcesUsed = append(report.SourcesUsed, source.Name)
99 }
100
101 report.Independence.Warnings = append(report.Independence.Warnings,
102 "independence was not established: this verdict was decided from facts supplied by the page")
103
104 // One source is what the forked chain has today. That is a warning, not a refusal: the facts
105 // are still hash-verified, and saying so plainly is more useful than pretending a quorum
106 // exists where it does not.
107 if len(d.Sources) < 2 {
108 report.LocalWarn("source_independence", fmt.Sprintf(
109 "%d source(s): existence is hash-verified, but agreement between independent sources is not possible",
110 len(d.Sources)))
111 } else {
112 report.Local("source_independence", "the facts came from independent sources", nil)
113 }
114
115 // Every transaction the verdict depends on must exist, at an agreed height, with bytes that
116 // hash to its id.
117 for _, leg := range legs {
118 for _, part := range []struct {
119 label string
120 raw []byte
121 }{
122 {"funding", leg.Funding},
123 {"refund", leg.Refund},
124 {"claim", leg.Claim},
125 } {
126 if len(part.raw) == 0 {
127 report.External(leg.Chain+"_"+part.label+"_exists",
128 "the "+part.label+" transaction was supplied", nil,
129 fmt.Errorf("%w: no %s transaction", ErrUnverifiable, part.label))
130
131 continue
132 }
133
134 txid, err := TxidOf(part.raw)
135
136 if err != nil {
137 report.External(leg.Chain+"_"+part.label+"_exists",
138 "the "+part.label+" transaction decodes", nil, err)
139
140 continue
141 }
142
143 agreed, sources, err := agreement(txid, d.Sources, d.Need)
144 detail := fmt.Sprintf("%s %s", leg.Chain, part.label)
145
146 if len(agreed) > 0 {
147 detail += fmt.Sprintf(" found at height %d", agreed[0])
148 }
149
150 report.External(leg.Chain+"_"+part.label+"_exists", detail, sources, err)
151
152 if err == nil {
153 report.Agreement = len(sources)
154 }
155 }
156 }
157
158 terms.Verify(&report, legs)
159
160 return report, nil
161 }
162
163 func agreement(txid [32]byte, sources []SourceJSON, need int) ([]int64, []string, error) {
164 var heights []int64
165 var names []string
166 absent := 0
167
168 for _, source := range sources {
169 fact, ok := source.Facts[Hash(txid)]
170
171 if !ok {
172 continue
173 }
174
175 if !fact.Found {
176 absent++
177 continue
178 }
179
180 raw, err := hex.DecodeString(fact.Hex)
181
182 if err != nil {
183 return nil, nil, fmt.Errorf("%w: %s returned non-hex bytes", ErrDisagree, source.Name)
184 }
185
186 got, err := TxidOf(raw)
187
188 if err != nil || got != txid {
189 return nil, nil, fmt.Errorf("%w: %s returned bytes that are not %s",
190 ErrDisagree, source.Name, Hash(txid))
191 }
192
193 heights = append(heights, fact.Height)
194 names = append(names, source.Name)
195 }
196
197 if need < 2 {
198 // A single source cannot prove independence; it can still prove the bytes it returned
199 // are the transaction that was asked for. The caller was told so by the report.
200 if len(names) == 0 {
201 return nil, names, fmt.Errorf("%w: no source found %s", ErrUnverifiable, Hash(txid))
202 }
203
204 heights = heights[:1]
205 return heights, names, nil
206 }
207
208 // Absence only contradicts someone who claims to have found it. When nobody found it, the
209 // answer is that the sample did not contain it, which is unverifiable rather than a conflict.
210 if absent > 0 && len(names) > 0 {
211 return nil, names, fmt.Errorf("%w: %s found by %v but not by %d other source(s)",
212 ErrDisagree, Hash(txid), names, absent)
213 }
214
215 if absent > 0 {
216 return nil, names, fmt.Errorf("%w: %d of %d sources did not find %s",
217 ErrUnverifiable, absent, len(sources), Hash(txid))
218 }
219
220 if len(names) < need {
221 return nil, names, fmt.Errorf("%w: %d of %d sources found %s, %d needed",
222 ErrUnverifiable, len(names), len(sources), Hash(txid), need)
223 }
224
225 for i := 1; i < len(heights); i++ {
226 if heights[i] != heights[0] {
227 return nil, names, fmt.Errorf("%w: sources disagree on the height of %s",
228 ErrDisagree, Hash(txid))
229 }
230 }
231
232 return heights, names, nil
233 }
234
235 func (d Dossier) parse() (Terms, []Leg, error) {
236 hashLock, err := parseHash(d.Terms.HashLock)
237
238 if err != nil {
239 return Terms{}, nil, fmt.Errorf("verify: hash lock: %w", err)
240 }
241
242 terms := Terms{
243 HashLock: hashLock, TimeoutBTC: d.Terms.TimeoutBTC, TimeoutXBT: d.Terms.TimeoutXBT,
244 AmountBTC: d.Terms.AmountBTC, AmountXBT: d.Terms.AmountXBT,
245 FeeBTC: d.Terms.FeeBTC, FeeXBT: d.Terms.FeeXBT,
246 MinTimeoutGap: d.Terms.MinTimeoutGap,
247 }
248
249 for _, field := range []struct {
250 name string
251 text string
252 dst *[]byte
253 }{
254 {"claimer_btc", d.Terms.ClaimerBTC, &terms.ClaimerBTC},
255 {"refunder_btc", d.Terms.RefunderBTC, &terms.RefunderBTC},
256 {"claimer_xbt", d.Terms.ClaimerXBT, &terms.ClaimerXBT},
257 {"refunder_xbt", d.Terms.RefunderXBT, &terms.RefunderXBT},
258 } {
259 raw, err := hex.DecodeString(field.text)
260
261 if err != nil || len(raw) != 33 {
262 return Terms{}, nil, fmt.Errorf("verify: %s: a 33-byte compressed key is required", field.name)
263 }
264
265 *field.dst = raw
266 }
267
268 legs := make([]Leg, 0, len(d.Legs))
269
270 for i, leg := range d.Legs {
271 funding, err := hex.DecodeString(leg.Funding)
272
273 if err != nil {
274 return Terms{}, nil, fmt.Errorf("verify: leg %d funding: %w", i, err)
275 }
276
277 refund, err := hex.DecodeString(leg.Refund)
278
279 if err != nil {
280 return Terms{}, nil, fmt.Errorf("verify: leg %d refund: %w", i, err)
281 }
282
283 claim, err := hex.DecodeString(leg.Claim)
284
285 if err != nil {
286 return Terms{}, nil, fmt.Errorf("verify: leg %d claim: %w", i, err)
287 }
288
289 legHash, err := parseHash(leg.HashLock)
290
291 if err != nil {
292 return Terms{}, nil, fmt.Errorf("verify: leg %d hash lock: %w", i, err)
293 }
294
295 claimer, err := hex.DecodeString(leg.Claimer)
296
297 if err != nil {
298 return Terms{}, nil, fmt.Errorf("verify: leg %d claimer: %w", i, err)
299 }
300
301 refunder, err := hex.DecodeString(leg.Refunder)
302
303 if err != nil {
304 return Terms{}, nil, fmt.Errorf("verify: leg %d refunder: %w", i, err)
305 }
306
307 change := make([][]byte, 0, len(leg.ChangeScripts))
308
309 for _, text := range leg.ChangeScripts {
310 script, err := hex.DecodeString(text)
311
312 if err != nil {
313 return Terms{}, nil, fmt.Errorf("verify: leg %d change script: %w", i, err)
314 }
315
316 change = append(change, script)
317 }
318
319 legs = append(legs, Leg{
320 Chain: leg.Chain, Funding: funding, Refund: refund, Claim: claim,
321 Timeout: leg.Timeout, Amount: leg.Amount, Fee: leg.Fee, HashLock: legHash,
322 Claimer: claimer, Refunder: refunder, ChangeScripts: change,
323 })
324 }
325
326 if len(legs) != 2 {
327 return Terms{}, nil, errors.New("verify: a swap has exactly two legs")
328 }
329
330 return terms, legs, nil
331 }
332
333 func parseHash(text string) ([32]byte, error) {
334 var out [32]byte
335
336 raw, err := hex.DecodeString(text)
337
338 if err != nil {
339 return out, err
340 }
341
342 if len(raw) != 32 {
343 return out, fmt.Errorf("%d bytes", len(raw))
344 }
345
346 copy(out[:], raw)
347
348 return out, nil
349 }
350