stream.go raw

   1  package utxostore
   2  
   3  import (
   4  	"bufio"
   5  	"encoding/binary"
   6  	"errors"
   7  	"fmt"
   8  	"io"
   9  	"os"
  10  	"path/filepath"
  11  	"sort"
  12  
  13  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  14  
  15  	"git.smesh.lol/btcd-lite/internal/utxo"
  16  	"git.smesh.lol/btcd-lite/internal/wire"
  17  )
  18  
  19  const entrySize = utxo.EntryEncodeSize
  20  
  21  // cmpOp is the set's own comparison. It used to or the hash comparison with
  22  // the index comparison, and a bitwise or of two -1s is -1, so two outpoints
  23  // that differed in both a hash and an index could order one way here and the
  24  // other way in the set. The merge walks the base with this and the creations
  25  // with the set's comparison, so a disagreement between them puts a creation in
  26  // the wrong place; it takes outpoints that differ in many hash bytes to show
  27  // up, which is why a synthetic chain never did and a node's did.
  28  func cmpOp(a, b wire.OutPoint) int {
  29  	return utxo.CompareOutPoints(a, b)
  30  }
  31  
  32  // keyList is a sorted, deduplicated list of outpoints as 36-byte keys, with
  33  // the file a parallel lookup reads each key's entry from.
  34  //
  35  // i is the index of cur, the key not yet consumed; advance moves to the next.
  36  type keyList struct {
  37  	f    *os.File
  38  	v    *os.File
  39  	n    int
  40  	i    int
  41  	cur  wire.OutPoint
  42  	have bool
  43  }
  44  
  45  func openKeys(path string) (*keyList, error) {
  46  	f, err := os.Open(path)
  47  	if err != nil {
  48  		return nil, err
  49  	}
  50  	fi, err := f.Stat()
  51  	if err != nil {
  52  		f.Close()
  53  		return nil, err
  54  	}
  55  	// i is -1 until advance reads the first key, which is where advance's own
  56  	// increment expects to start.
  57  	k := &keyList{f: f, n: int(fi.Size() / 36), i: -1}
  58  	k.advance()
  59  	return k, nil
  60  }
  61  
  62  // advance moves cur to the next key. The caller consumes the key it already
  63  // held; this leaves the next one in cur.
  64  func (k *keyList) advance() {
  65  	k.i++
  66  	if k.i >= k.n {
  67  		k.have = false
  68  		return
  69  	}
  70  	var b [36]byte
  71  	if _, err := k.f.ReadAt(b[:], int64(k.i)*36); err != nil {
  72  		k.have = false
  73  		return
  74  	}
  75  	copy(k.cur.Hash[:], b[:32])
  76  	k.cur.Index = binary.LittleEndian.Uint32(b[32:36])
  77  	k.have = true
  78  }
  79  
  80  // openValues attaches the entry file that runs parallel to the key file.
  81  func (k *keyList) openValues(path string) error {
  82  	f, err := os.Open(path)
  83  	if err != nil {
  84  		return err
  85  	}
  86  	k.v = f
  87  	return nil
  88  }
  89  
  90  func (k *keyList) close() {
  91  	k.f.Close()
  92  	if k.v != nil {
  93  		k.v.Close()
  94  	}
  95  }
  96  
  97  // entry reads the value file's record for key i, which is the record of the
  98  // key's creation in the diff.
  99  func (k *keyList) entry(i int) (utxo.Entry, bool) {
 100  	if k.v == nil {
 101  		return utxo.Entry{}, false
 102  	}
 103  	buf := make([]byte, entrySize)
 104  	// The entry's offset is the key's record index, shifted to the value file's
 105  	// record size: the two files are parallel by construction, and a bug that
 106  	// read them at different indices would write one key's value under
 107  	// another's, which is the one thing a merge must never do.
 108  	if _, err := k.v.ReadAt(buf, int64(i)*int64(entrySize)); err != nil {
 109  		return utxo.Entry{}, false
 110  	}
 111  	e := utxo.Decode(buf)
 112  	return e, true
 113  }
 114  
 115  // MergeRange writes the set at to from the set at from and the diff of the
 116  // range between them, in one pass each over the base and the diff.
 117  //
 118  // The diff is the end state of the range: its created touches are the
 119  // outpoints the range made and did not spend again, and its spent touches are
 120  // the ones it took from the base. The merge walks the base and both key lists
 121  // in outpoint order and writes the union minus the spends plus the creations.
 122  //
 123  // target, when set, is the name the set was given when the caller wrote it by
 124  // replay; a merge that does not reproduce it says so instead of writing a
 125  // second answer to the same question.
 126  func MergeRange(dir string, from, to uint32, diff utxo.Diff, target chainhash.Hash) (chainhash.Hash, error) {
 127  	return MergeRangeFrom(dir, dir, from, to, diff, target)
 128  }
 129  
 130  // MergeRangeFrom is MergeRange with the snapshot it starts from read somewhere
 131  // else. A chain that continues a shared prefix reads the prefix's snapshot where
 132  // the prefix wrote it and writes its own next to itself, so the largest file in
 133  // the dataset is not copied once per chain.
 134  func MergeRangeFrom(baseDir, dir string, from, to uint32, diff utxo.Diff, target chainhash.Hash) (chainhash.Hash, error) {
 135  	createdPath := filepath.Join(dir, fmt.Sprintf("keys-%09d-%09d.created", from, to))
 136  	spentPath := filepath.Join(dir, fmt.Sprintf("keys-%09d-%09d.spent", from, to))
 137  	if err := checkChain(diff, from); err != nil {
 138  		return chainhash.Hash{}, err
 139  	}
 140  	if err := writeKeys(createdPath, spentPath, diff); err != nil {
 141  		return chainhash.Hash{}, err
 142  	}
 143  	if !keepScratch {
 144  		defer os.Remove(createdPath)
 145  		defer os.Remove(spentPath)
 146  	}
 147  
 148  	created, err := openKeys(createdPath)
 149  	if err != nil {
 150  		return chainhash.Hash{}, err
 151  	}
 152  	defer created.close()
 153  	if !keepScratch {
 154  		defer os.Remove(createdPath + "v")
 155  	}
 156  	if created.v, err = os.Open(createdPath + "v"); err != nil {
 157  		return chainhash.Hash{}, err
 158  	}
 159  	spent, err := openKeys(spentPath)
 160  	if err != nil {
 161  		return chainhash.Hash{}, err
 162  	}
 163  	defer spent.close()
 164  
 165  	base, err := os.Open(filepath.Join(baseDir, SetFile(from)))
 166  	if err != nil {
 167  		return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
 168  	}
 169  	defer base.Close()
 170  
 171  	out, err := os.Create(filepath.Join(dir, SetFile(to)))
 172  	if err != nil {
 173  		return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
 174  	}
 175  	w := bufio.NewWriterSize(out, 1<<20)
 176  	h := newHasher()
 177  	// buf holds the base entry being walked, and cbuf holds a creation's entry.
 178  	// They are separate because writeCreated writes through its buffer: passing
 179  	// buf to it would overwrite the base entry before writeEntry emitted it, and
 180  	// the creation would come out twice while the base entry came out never.
 181  	buf := make([]byte, entrySize)
 182  	cbuf := make([]byte, entrySize)
 183  	baseR := bufio.NewReaderSize(base, 1<<20)
 184  	for {
 185  		_, rerr := io.ReadFull(baseR, buf)
 186  		if errors.Is(rerr, io.EOF) {
 187  			break
 188  		}
 189  		if rerr != nil {
 190  			out.Close()
 191  			return chainhash.Hash{}, fmt.Errorf("utxostore: base %d: %w", from, rerr)
 192  		}
 193  		e := utxo.Decode(buf)
 194  		debugStep(e.OutPoint, created.i, created.cur, created.have, spent.cur, spent.have)
 195  		action := "keep"
 196  		if spent.have && spent.cur == e.OutPoint {
 197  			action = "spend"
 198  		} else if created.have && created.cur == e.OutPoint {
 199  			action = "create-at-base"
 200  		}
 201  		debugWalk(e.OutPoint, created.cur, spent.cur, action)
 202  		// The created list first: a creation below this entry is new and
 203  		// sorts before it, so it is written now.
 204  		for created.have && cmpOp(created.cur, e.OutPoint) < 0 {
 205  			writeCreated(w, h, cbuf, created)
 206  		}
 207  		// A creation that sorts before this entry is written first, whether or
 208  		// not the entry is about to be spent: whether the base entry survives
 209  		// does not change where the creations around it belong.
 210  		if spent.have && spent.cur == e.OutPoint {
 211  			spent.advance()
 212  			// The creations below this entry still come before it. The prefix
 213  			// loop at the top of this iteration wrote the ones below the entry
 214  			// it started on, which is this entry, so they were already written;
 215  			// nothing is written here, and writing them again is how one
 216  			// creation came out twice.
 217  			continue
 218  		}
 219  		if spent.have && cmpOp(spent.cur, e.OutPoint) < 0 {
 220  			out.Close()
 221  			return chainhash.Hash{}, fmt.Errorf("utxostore: the range spends %s, which the set at %d does not hold", spent.cur, from)
 222  		}
 223  		if created.have && created.cur == e.OutPoint {
 224  			// The diff's creation names an outpoint the base holds: the
 225  			// creation is of an output the set already has, and the entry the
 226  			// set holds is the one written. The created list moves on either
 227  			// way, so the same outpoint is not written twice.
 228  			created.advance()
 229  		}
 230  		writeEntry(w, h, buf)
 231  	}
 232  	for created.have {
 233  		writeCreated(w, h, cbuf, created)
 234  	}
 235  	if err := w.Flush(); err != nil {
 236  		out.Close()
 237  		return chainhash.Hash{}, err
 238  	}
 239  	if err := out.Sync(); err != nil {
 240  		out.Close()
 241  		return chainhash.Hash{}, err
 242  	}
 243  	if err := out.Close(); err != nil {
 244  		return chainhash.Hash{}, err
 245  	}
 246  	name := h.Sum()
 247  	if target != (chainhash.Hash{}) && name != target {
 248  		os.Remove(filepath.Join(dir, SetFile(to)))
 249  		return chainhash.Hash{}, fmt.Errorf("utxostore: merging to %d gives %s, the replay wrote %s", to, name, target)
 250  	}
 251  	// A merged snapshot is a snapshot: it goes in the index like one the replay
 252  	// wrote, or a manifest never offers it and a client never fetches it.
 253  	if err := RecordName(dir, to, name); err != nil {
 254  		return chainhash.Hash{}, err
 255  	}
 256  	return name, nil
 257  }
 258  
 259  // writeCreated emits the next created outpoint, which is k.cur, moves the key
 260  // list on, and reads the entry the diff recorded for it.
 261  func writeCreated(w *bufio.Writer, h hashWriter, buf []byte, k *keyList) {
 262  	idx := k.i
 263  	op := k.cur
 264  	debugWrite(op, k.n)
 265  	// The lookup in the value file is advisory: its outpoint never reaches the
 266  	// set. The creation the diff recorded IS this outpoint at THIS height, and
 267  	// the key file's index is the only thing that says which entry belongs to
 268  	// which key. A value file read at a stale index once put a creation at
 269  	// another block's height, and taking the outpoint from it put a creation
 270  	// in another outpoint's place; both are why the entry is built here.
 271  	e, ok := k.entry(idx)
 272  	if !ok {
 273  		debugPairMiss(op, e, idx, ok)
 274  		e = utxo.Entry{OutPoint: op}
 275  	}
 276  	e.OutPoint = op
 277  	debugCreated(idx, e)
 278  	e.Encode(buf)
 279  	writeEntry(w, h, buf)
 280  	k.advance()
 281  }
 282  
 283  // debugPairMiss is a switch the package's tests flip to see a pairing failure
 284  // as it happens.
 285  var debugPairMiss = func(op wire.OutPoint, e utxo.Entry, idx int, ok bool) {}
 286  
 287  // debugCreated is a switch the package's tests flip to see each creation the
 288  // merge writes, with the index it read the entry from.
 289  var debugCreated = func(idx int, e utxo.Entry) {}
 290  
 291  // keepScratch leaves the merge's key files behind for a test that reads them.
 292  var keepScratch = false
 293  
 294  // debugWrite is a switch the package's tests flip to see each creation written,
 295  // with the key count the list had, so a write from the wrong list is visible.
 296  var debugWrite = func(op wire.OutPoint, n int) {}
 297  
 298  // debugWalk is a switch the package's tests flip to see each base entry the
 299  // merge walks, with the cursor positions and what it chose to do.
 300  // debugWrittenOut sees the outpoint a creation was meant to be and the outpoint
 301  // the bytes about to be hashed name, which differ only if the buffer lied.
 302  var debugWrittenOut = func(meant, got wire.OutPoint) {}
 303  
 304  var debugWalk = func(base wire.OutPoint, createdOp wire.OutPoint, spentOp wire.OutPoint, wrote string) {}
 305  
 306  // debugStep is a switch the package's tests flip to see each iteration of the
 307  // merge's walk: which base entry it is on, and where both cursors stand.
 308  var debugStep = func(base wire.OutPoint, createdIdx int, created wire.OutPoint, createdHave bool, spent wire.OutPoint, spentHave bool) {
 309  }
 310  
 311  func writeEntry(w *bufio.Writer, h hashWriter, buf []byte) {
 312  	_, _ = w.Write(buf)
 313  	// The name is the name of the set, not of the writes: the bytes are
 314  	// normalised through the entry type before they are hashed, so a buffer
 315  	// that kept a field from an earlier entry cannot change the name.
 316  	e := utxo.Decode(buf)
 317  	e.Encode(buf)
 318  	_, _ = h.Write(buf)
 319  }
 320  
 321  type hashWriter = interface {
 322  	Write([]byte) (int, error)
 323  }
 324  
 325  // writeKeys writes the diff's net created and net spent outpoints, sorted, and
 326  // a parallel file of the created entries, one record per key and in the same
 327  // order.
 328  func writeKeys(createdPath, spentPath string, diff utxo.Diff) error {
 329  	net := make(map[wire.OutPoint]byte, len(diff.Touches))
 330  	for _, t := range diff.Touches {
 331  		if t.Spent {
 332  			if net[t.OutPoint] == 1 {
 333  				// Created earlier in the range and spent later: gone by the
 334  				// end of it, and neither side of the merge.
 335  				delete(net, t.OutPoint)
 336  				continue
 337  			}
 338  			net[t.OutPoint] = 2
 339  			continue
 340  		}
 341  		net[t.OutPoint] = 1
 342  	}
 343  	values := make(map[wire.OutPoint]utxo.Entry, len(net))
 344  	for _, t := range diff.Touches {
 345  		if !t.Spent && net[t.OutPoint] == 1 {
 346  			values[t.OutPoint] = t.New
 347  		}
 348  	}
 349  	var created, spent []wire.OutPoint
 350  	for op, kind := range net {
 351  		switch kind {
 352  		case 1:
 353  			created = append(created, op)
 354  		case 2:
 355  			spent = append(spent, op)
 356  		}
 357  	}
 358  	// One order for the key list and the walk: the set's own comparison. The
 359  	// merge's walk and writeKeys' sort must sort keys identically, and two
 360  	// comparisons that disagree on one pair of outpoints is exactly how a merge
 361  	// writes a set in an order nothing else produces.
 362  	sortBySet(created)
 363  	sortBySet(spent)
 364  	if err := writeOpList(createdPath, created); err != nil {
 365  		return err
 366  	}
 367  	entries := make([]utxo.Entry, len(created))
 368  	for i, op := range created {
 369  		entries[i] = values[op]
 370  	}
 371  	if err := writeEntryPairs(createdPath+"v", entries, created); err != nil {
 372  		return err
 373  	}
 374  	return writeOpList(spentPath, spent)
 375  }
 376  
 377  // sortBySet sorts outpoints by the set's comparison, so the key files and the
 378  // set it produces cannot disagree about order.
 379  func sortBySet(ops []wire.OutPoint) {
 380  	sort.Slice(ops, func(i, j int) bool {
 381  		return utxo.LessEntry(utxo.Entry{OutPoint: ops[i]}, utxo.Entry{OutPoint: ops[j]})
 382  	})
 383  }
 384  
 385  // writeEntryPairs writes the created entries, one per key, refusing a pair
 386  // whose entry names another outpoint: the key file is index i and the entry
 387  // file is index i, and nothing else is a merge.
 388  func writeEntryPairs(path string, created []utxo.Entry, keys []wire.OutPoint) error {
 389  	f, err := os.Create(path)
 390  	if err != nil {
 391  		return fmt.Errorf("utxostore: %w", err)
 392  	}
 393  	defer f.Close()
 394  	w := bufio.NewWriterSize(f, 1<<20)
 395  	buf := make([]byte, entrySize)
 396  	for i := range created {
 397  		if created[i].OutPoint != keys[i] {
 398  			return fmt.Errorf("utxostore: entry %d is for %s, key %d is %s", i, created[i].OutPoint, i, keys[i])
 399  		}
 400  		created[i].Encode(buf)
 401  		if _, err := w.Write(buf); err != nil {
 402  			return err
 403  		}
 404  	}
 405  	return w.Flush()
 406  }
 407  
 408  func writeOpList(path string, ops []wire.OutPoint) error {
 409  	f, err := os.Create(path)
 410  	if err != nil {
 411  		return fmt.Errorf("utxostore: %w", err)
 412  	}
 413  	defer f.Close()
 414  	w := bufio.NewWriterSize(f, 1<<20)
 415  	var key [36]byte
 416  	for _, op := range ops {
 417  		copy(key[:32], op.Hash[:])
 418  		binary.LittleEndian.PutUint32(key[32:], op.Index)
 419  		if _, err := w.Write(key[:]); err != nil {
 420  			return err
 421  		}
 422  	}
 423  	return w.Flush()
 424  }
 425  
 426  // checkChain refuses a diff whose own touches do not describe a range: a spend
 427  // before the creation of the same outpoint, two spends of one outpoint in the
 428  // range, or two creations, are chains that cannot exist. It is the same rule
 429  // utxo.ApplyRange applies to a range, stated over the sorted touches so the
 430  // merge does not have to hold the base to check it.
 431  func checkChain(diff utxo.Diff, from uint32) error {
 432  	if diff.From != from || diff.To < from {
 433  		return fmt.Errorf("utxostore: diff is %d..%d, the merge is %d", diff.From, diff.To, from)
 434  	}
 435  	ts := append([]utxo.Touch(nil), diff.Touches...)
 436  	sort.SliceStable(ts, func(i, j int) bool {
 437  		if c := cmpOp(ts[i].OutPoint, ts[j].OutPoint); c != 0 {
 438  			return c < 0
 439  		}
 440  		if ts[i].Height != ts[j].Height {
 441  			return ts[i].Height < ts[j].Height
 442  		}
 443  		return !ts[i].Spent && ts[j].Spent
 444  	})
 445  	for i := 1; i < len(ts); i++ {
 446  		if ts[i].OutPoint != ts[i-1].OutPoint || ts[i].Spent != ts[i-1].Spent {
 447  			continue
 448  		}
 449  		if ts[i].Spent {
 450  			return fmt.Errorf("utxostore: outpoint %s spent twice in one range", ts[i].OutPoint)
 451  		}
 452  		return fmt.Errorf("utxostore: outpoint %s created twice in one range", ts[i].OutPoint)
 453  	}
 454  	return nil
 455  }
 456