1 package domain
2 3 import (
4 "encoding/binary"
5 "errors"
6 "fmt"
7 8 "git.smesh.lol/tinywallet/pkg/script"
9 "git.smesh.lol/tinywallet/pkg/wallet"
10 )
11 12 // Watch limits. A watched script is a contract someone may pay; the list is small on purpose,
13 // because every entry is matched against every filter.
14 const (
15 // MaxWatches bounds how many extra scripts one chain may watch.
16 MaxWatches = 64
17 // MaxWatchScript bounds one watched script.
18 MaxWatchScript = 10000
19 )
20 21 // ErrWatch is a script this chain will not watch.
22 var ErrWatch = errors.New("domain: a watched script is empty or too large")
23 24 // watchKey names one chain's list.
25 func watchKey(name string) string { return "watch/" + name }
26 27 // PutWatches encodes a watch list: a count, then each script length-prefixed.
28 func PutWatches(scripts [][]byte) []byte {
29 out := binary.LittleEndian.AppendUint16(nil, uint16(len(scripts)))
30 31 for _, witness := range scripts {
32 out = binary.LittleEndian.AppendUint16(out, uint16(len(witness)))
33 out = append(out, witness...)
34 }
35 36 return out
37 }
38 39 // ReadWatches decodes a watch list, refusing anything that does not fit its own lengths.
40 func ReadWatches(raw []byte) ([][]byte, error) {
41 if len(raw) < 2 {
42 return nil, fmt.Errorf("domain: a watch list is %d bytes", len(raw))
43 }
44 45 count := int(binary.LittleEndian.Uint16(raw))
46 at := 2
47 48 if count > MaxWatches {
49 return nil, fmt.Errorf("domain: %d watched scripts, the limit is %d", count, MaxWatches)
50 }
51 52 scripts := make([][]byte, 0, count)
53 54 for i := 0; i < count; i++ {
55 if at+2 > len(raw) {
56 return nil, fmt.Errorf("domain: a watch list ends inside a length")
57 }
58 59 length := int(binary.LittleEndian.Uint16(raw[at:]))
60 at += 2
61 62 if at+length > len(raw) {
63 return nil, fmt.Errorf("domain: a watched script runs past the list")
64 }
65 66 scripts = append(scripts, append([]byte(nil), raw[at:at+length]...))
67 at += length
68 }
69 70 if at != len(raw) {
71 return nil, fmt.Errorf("domain: %d trailing bytes after the watch list", len(raw)-at)
72 }
73 74 return scripts, nil
75 }
76 77 // Watch adds a scriptPubKey to the chain's scan set.
78 //
79 // This is the output script, not a witness script: the filters are built over output scripts,
80 // so a P2WSH contract is watched as its 34-byte OP_0 push. WatchHTLC does that wrapping for a
81 // caller that holds the witness script.
82 //
83 // A swap's HTLC is an output the wallet's own addresses never name, so without a watcher the
84 // filters would match a block and the wallet would still not see the contract it is a party to.
85 // Watching is additive and idempotent: the same script twice is one entry.
86 func (d *Domain) Watch(name string, witnessScript []byte) error {
87 if _, err := d.link(name); err != nil {
88 return err
89 }
90 91 if len(witnessScript) == 0 || len(witnessScript) > MaxWatchScript {
92 return ErrWatch
93 }
94 95 watches, err := d.Watches(name)
96 97 if err != nil {
98 return err
99 }
100 101 for _, existing := range watches {
102 if string(existing) == string(witnessScript) {
103 return nil
104 }
105 }
106 107 if len(watches) >= MaxWatches {
108 return fmt.Errorf("domain: %q watches %d scripts, the limit is %d", name, len(watches), MaxWatches)
109 }
110 111 watches = append(watches, append([]byte(nil), witnessScript...))
112 113 return d.store.Put(watchKey(name), PutWatches(watches))
114 }
115 116 // WatchHTLC watches a contract given its witness script, wrapping it in P2WSH.
117 func (d *Domain) WatchHTLC(name string, witnessScript []byte) error {
118 if len(witnessScript) == 0 || len(witnessScript) > MaxWatchScript {
119 return ErrWatch
120 }
121 122 return d.Watch(name, script.P2WSH(witnessScript))
123 }
124 125 // Unwatch forgets one script, for a swap that is settled and needs no further scanning.
126 func (d *Domain) Unwatch(name string, witnessScript []byte) error {
127 if _, err := d.link(name); err != nil {
128 return err
129 }
130 131 watches, err := d.Watches(name)
132 133 if err != nil {
134 return err
135 }
136 137 kept := make([][]byte, 0, len(watches))
138 139 for _, existing := range watches {
140 if string(existing) != string(witnessScript) {
141 kept = append(kept, existing)
142 }
143 }
144 145 return d.store.Put(watchKey(name), PutWatches(kept))
146 }
147 148 // Watches lists the chain's watched scripts.
149 func (d *Domain) Watches(name string) ([][]byte, error) {
150 raw, ok := d.store.Get(watchKey(name))
151 152 if !ok {
153 return nil, nil
154 }
155 156 return ReadWatches(raw)
157 }
158 159 // scanScripts is the script set a scan matches: the wallet's own receive and change addresses
160 // over the lookahead, plus every contract the chain is watching.
161 func (d *Domain) scanScripts(name string, derived *wallet.Wallet, meta Meta, lookahead uint32) ([][]byte, error) {
162 watches, err := d.Watches(name)
163 164 if err != nil {
165 return nil, err
166 }
167 168 return scriptsFor(derived, meta, lookahead, watches)
169 }
170 171 // Rewind makes the next sync rescan from a height.
172 //
173 // A watched script can be added after the block that pays it was already
174 // scanned, and the per-height match markers would otherwise skip that block. The
175 // filters are already in the store, so nothing is downloaded again: dropping the
176 // markers is what makes the block be fetched and read for the new script.
177 func (d *Domain) Rewind(name string, height uint32) error {
178 if _, err := d.link(name); err != nil {
179 return err
180 }
181 182 meta, err := d.meta(name)
183 184 if err != nil {
185 return err
186 }
187 188 if height < meta.FilterFrom {
189 meta.FilterFrom = height
190 191 if err := d.store.Put(metaKey(name), PutMeta(meta)); err != nil {
192 return err
193 }
194 }
195 196 for _, key := range d.store.Keys(matchPrefix(name)) {
197 matched, ok := parseMatchKey(key)
198 199 if ok && matched >= height {
200 if err := d.store.Delete(key); err != nil {
201 return err
202 }
203 }
204 }
205 206 return d.store.Flush()
207 }
208