set.go raw

   1  package utxo
   2  
   3  import (
   4  	"encoding/binary"
   5  	"errors"
   6  	"fmt"
   7  	"sort"
   8  
   9  	"git.smesh.lol/btcd-lite/internal/wire"
  10  )
  11  
  12  // Entry is one unspent output.
  13  type Entry struct {
  14  	OutPoint wire.OutPoint
  15  	Value    int64
  16  	// ScriptHash is the first 8 bytes of the scriptPubKey's SHA-256. It is
  17  	// enough to answer "is this the coin I was told about" and it is what a
  18  	// canonical set needs to keep its entries fixed width.
  19  	ScriptHash [8]byte
  20  	// Height is the height of the block that created the output.
  21  	Height uint32
  22  	// Coinbase marks an output whose spend is delayed by the chain's coinbase
  23  	// maturity, which is a per-chain rule and not always 100: see
  24  	// chains.ExportedChain.CoinbaseMaturity. It records that the rule applies,
  25  	// not a height at which it expires.
  26  	Coinbase bool
  27  }
  28  
  29  // LessEntry orders two entries by outpoint, which is the canonical order.
  30  func LessEntry(a, b Entry) bool { return compareOutPoints(a.OutPoint, b.OutPoint) < 0 }
  31  
  32  // CompareOutPoints is the one outpoint order: hash bytes then index. Everything
  33  // that sorts or merges outpoints uses it, so a merge cannot walk one order and
  34  // sort the other.
  35  func CompareOutPoints(a, b wire.OutPoint) int { return compareOutPoints(a, b) }
  36  
  37  // Less orders entries by outpoint.
  38  func (e Entry) Less(other Entry) bool {
  39  	if c := compareOutPoints(e.OutPoint, other.OutPoint); c != 0 {
  40  		return c < 0
  41  	}
  42  	return false
  43  }
  44  
  45  // compareOutPoints orders outpoints by the hash's bytes, then by index, which is
  46  // the order a canonical set is sorted by.
  47  func compareOutPoints(a, b wire.OutPoint) int {
  48  	for i := range a.Hash {
  49  		switch {
  50  		case a.Hash[i] < b.Hash[i]:
  51  			return -1
  52  		case a.Hash[i] > b.Hash[i]:
  53  			return 1
  54  		}
  55  	}
  56  	switch {
  57  	case a.Index < b.Index:
  58  		return -1
  59  	case a.Index > b.Index:
  60  		return 1
  61  	}
  62  	return 0
  63  }
  64  
  65  const (
  66  	// entryEncodeSize is 36 outpoint, 8 value, 8 script hash, 4 height, 1 flag.
  67  	entryEncodeSize = 57
  68  	flagCoinbase    = 1
  69  	// EntryEncodeSize is the same width, for a caller that writes a set to a
  70  	// fixed-width file.
  71  	EntryEncodeSize = entryEncodeSize
  72  )
  73  
  74  // Encode serializes an entry at fixed width so a canonical set is sorted
  75  // records with no length prefixes.
  76  func (e Entry) Encode(buf []byte) {
  77  	copy(buf[0:32], e.OutPoint.Hash[:])
  78  	binary.LittleEndian.PutUint32(buf[32:36], e.OutPoint.Index)
  79  	binary.LittleEndian.PutUint64(buf[36:44], uint64(e.Value))
  80  	copy(buf[44:52], e.ScriptHash[:])
  81  	binary.LittleEndian.PutUint32(buf[52:56], e.Height)
  82  	buf[56] = 0
  83  	if e.Coinbase {
  84  		buf[56] = flagCoinbase
  85  	}
  86  }
  87  
  88  // Decode reads an entry from buf, which must be entryEncodeSize bytes.
  89  func Decode(buf []byte) Entry {
  90  	var e Entry
  91  	copy(e.OutPoint.Hash[:], buf[0:32])
  92  	e.OutPoint.Index = binary.LittleEndian.Uint32(buf[32:36])
  93  	e.Value = int64(binary.LittleEndian.Uint64(buf[36:44]))
  94  	copy(e.ScriptHash[:], buf[44:52])
  95  	e.Height = binary.LittleEndian.Uint32(buf[52:56])
  96  	e.Coinbase = buf[56]&flagCoinbase != 0
  97  	return e
  98  }
  99  
 100  // Touch is the record of what one block did to one outpoint. The set of touches
 101  // over a range is all a diff needs to describe, and a blocks' touches in input
 102  // then output order are what the set walk applies.
 103  type Touch struct {
 104  	OutPoint wire.OutPoint
 105  	Height   uint32
 106  	// Spent is true when the block spent the outpoint; false when it created it.
 107  	Spent bool
 108  	// New is the entry a creation made. Zero for a spend.
 109  	New Entry
 110  }
 111  
 112  // Range applies touches to a set and returns the new set.
 113  //
 114  // The set is immutable: callers hold it sorted, and a range's result is a new
 115  // slice. The cost is the copy, which is the price of never leaving a set in a
 116  // state that is half a block forward.
 117  func ApplyRange(set []Entry, touches []Touch) ([]Entry, error) {
 118  	out, _, err := applyRange(set, touches)
 119  	return out, err
 120  }
 121  
 122  // applyRange is ApplyRange that also reports how many entries it visited, which
 123  // is what the plot measures as the cost of a rebuild.
 124  func applyRange(set []Entry, touches []Touch) ([]Entry, int, error) {
 125  	// Sort touches by outpoint. A block can spend and create the same
 126  	// outpoint in different blocks, so equal outpoints are expected across a
 127  	// range and are merged below.
 128  	sorted := make([]Touch, len(touches))
 129  	copy(sorted, touches)
 130  	sort.SliceStable(sorted, func(i, j int) bool {
 131  		return compareOutPoints(sorted[i].OutPoint, sorted[j].OutPoint) < 0
 132  	})
 133  	// At most one creation and one spend per outpoint per range. Anything else
 134  	// is a chain that cannot exist, and it is refused here rather than
 135  	// discovered later as an outpoint in two states. Sorted as it now is, that
 136  	// is one pass with no allocation.
 137  	first := make([]int, 0, 0)
 138  	_ = first
 139  	// Per group: whether the set had the outpoint, the entry if so, whether the
 140  	// range created it, and with which creation.
 141  	type groupState struct {
 142  		started  bool
 143  		setEntry Entry
 144  		created  bool
 145  		creation Entry
 146  	}
 147  	groupOf := func(a, b int) (groupState, error) {
 148  		var g groupState
 149  		// A creation and a spend of one outpoint inside a range is the range's
 150  		// own timeline; sorting by height and creation first reproduces it.
 151  		sort.SliceStable(sorted[a:b], func(x, y int) bool {
 152  			s := sorted[a:b]
 153  			if s[x].Height != s[y].Height {
 154  				return s[x].Height < s[y].Height
 155  			}
 156  			return !s[x].Spent && s[y].Spent
 157  		})
 158  		for k := a; k < b; k++ {
 159  			t := sorted[k]
 160  			if t.Spent {
 161  				if !g.started && !g.created {
 162  					return g, fmt.Errorf("utxo: spend of %s at %d is not in the set", t.OutPoint, t.Height)
 163  				}
 164  				g.started, g.created = false, false
 165  				continue
 166  			}
 167  			if g.started || g.created {
 168  				return g, fmt.Errorf("utxo: creation of %s at %d duplicates the set", t.OutPoint, t.Height)
 169  			}
 170  			g.created, g.creation = true, t.New
 171  		}
 172  		return g, nil
 173  	}
 174  	_ = groupOf
 175  	// The result is a fresh slice: a caller that keeps the set it passed in (a
 176  	// diff applied to a checkpoint) must not find it changed afterwards. Copies
 177  	// of runs larger than one entry go in chunks, because a run is the common
 178  	// case and a per-entry append is the cost of the whole rebuild otherwise.
 179  	out := make([]Entry, 0, len(set)+len(sorted))
 180  	i, j := 0, 0
 181  	for i < len(set) || j < len(sorted) {
 182  		if j >= len(sorted) {
 183  			out = append(out, set[i:]...)
 184  			break
 185  		}
 186  		if i < len(set) && compareOutPoints(set[i].OutPoint, sorted[j].OutPoint) < 0 {
 187  			// The set entries below the next touch are copied as a run.
 188  			end := i
 189  			for end < len(set) && compareOutPoints(set[end].OutPoint, sorted[j].OutPoint) < 0 {
 190  				end++
 191  			}
 192  			if end-i > 1 {
 193  				out = append(out, set[i:end]...)
 194  				i = end
 195  				continue
 196  			}
 197  			out = append(out, set[i])
 198  			i++
 199  			continue
 200  		}
 201  		k := j + 1
 202  		for k < len(sorted) && sorted[k].OutPoint == sorted[j].OutPoint {
 203  			k++
 204  		}
 205  		group := sorted[j:k]
 206  		// Order the group the way the range applied it: by height, creation
 207  		// before spend at one height.
 208  		sort.SliceStable(group, func(a, b int) bool {
 209  			if group[a].Height != group[b].Height {
 210  				return group[a].Height < group[b].Height
 211  			}
 212  			return !group[a].Spent && group[b].Spent
 213  		})
 214  		started := i < len(set) && compareOutPoints(set[i].OutPoint, group[0].OutPoint) == 0
 215  		var setEntry Entry
 216  		if started {
 217  			setEntry = set[i]
 218  			i++
 219  		}
 220  		present := started
 221  		var created Entry
 222  		for _, t := range group {
 223  			if t.Spent {
 224  				if !present {
 225  					return nil, 0, fmt.Errorf("utxo: spend of %s at %d is not in the set", t.OutPoint, t.Height)
 226  				}
 227  				present = false
 228  				continue
 229  			}
 230  			if present {
 231  				if started && t.New == setEntry {
 232  					// The same output at the same height: a replay.
 233  					continue
 234  				}
 235  				return nil, 0, fmt.Errorf("utxo: creation of %s at %d duplicates the set", t.OutPoint, t.Height)
 236  			}
 237  			present = true
 238  			created = t.New
 239  		}
 240  		switch {
 241  		case !present:
 242  		case started:
 243  			out = append(out, setEntry)
 244  		default:
 245  			out = append(out, created)
 246  		}
 247  		j = k
 248  	}
 249  	return out, len(set) + len(sorted), nil
 250  }
 251  
 252  // RangeCost applies a range and returns how many entries the merge visited.
 253  // It exists for the plot: the plan's rebuild cost is this number, not the bytes.
 254  func RangeCost(set []Entry, touches []Touch) (int, error) {
 255  	_, visited, err := applyRange(set, touches)
 256  	return visited, err
 257  }
 258  
 259  // Diff is one range's delta: the touches, sorted by outpoint, plus the range.
 260  type Diff struct {
 261  	From    uint32
 262  	To      uint32
 263  	Touches []Touch
 264  }
 265  
 266  // ApplyTo returns a copy of set with the diff applied. It is ApplyRange with
 267  // the range recorded, so a diff and a replayed range cannot disagree.
 268  func (d Diff) ApplyTo(set []Entry) ([]Entry, error) {
 269  	return ApplyRange(set, d.Touches)
 270  }
 271  
 272  // touchEncodeSize is a spend touch (41) or a creation touch (58).
 273  const (
 274  	// A touch is outpoint (36), height (4) and a spent flag (1). A creation
 275  	// carries its value (8), script hash (8), coinbase flag (1) and its own
 276  	// height (4) as well, because the height a creation's entry carries is the
 277  	// height of the block that made it and not the height of every touch in
 278  	// the range.
 279  	spendSize    = 41
 280  	creationSize = 62
 281  )
 282  
 283  // Encode writes a diff: from (4), to (4), count (4), then each touch in
 284  // outpoint order. A spend is outpoint, height, spent flag; a creation is that
 285  // plus value, script hash and coinbase flag. The size is inferred from the flag.
 286  func (d Diff) Encode() []byte {
 287  	buf := make([]byte, 0, 12+len(d.Touches)*creationSize)
 288  	buf = binary.LittleEndian.AppendUint32(buf, d.From)
 289  	buf = binary.LittleEndian.AppendUint32(buf, d.To)
 290  	buf = binary.LittleEndian.AppendUint32(buf, uint32(len(d.Touches)))
 291  	for _, t := range d.Touches {
 292  		buf = append(buf, t.OutPoint.Hash[:]...)
 293  		buf = binary.LittleEndian.AppendUint32(buf, t.OutPoint.Index)
 294  		buf = binary.LittleEndian.AppendUint32(buf, t.Height)
 295  		if t.Spent {
 296  			buf = append(buf, 1)
 297  			continue
 298  		}
 299  		buf = append(buf, 0)
 300  		buf = binary.LittleEndian.AppendUint64(buf, uint64(t.New.Value))
 301  		buf = append(buf, t.New.ScriptHash[:]...)
 302  		if t.New.Coinbase {
 303  			buf = append(buf, 1)
 304  		} else {
 305  			buf = append(buf, 0)
 306  		}
 307  		buf = binary.LittleEndian.AppendUint32(buf, t.New.Height)
 308  	}
 309  	return buf
 310  }
 311  
 312  // ErrShortDiff is a diff that ends before its own count says.
 313  var ErrShortDiff = errors.New("utxo: diff ends before its touch count")
 314  
 315  // DecodeDiff reads a diff written by Encode and requires it to end exactly.
 316  func DecodeDiff(raw []byte) (Diff, error) {
 317  	if len(raw) < 12 {
 318  		return Diff{}, ErrShortDiff
 319  	}
 320  	d := Diff{
 321  		From: binary.LittleEndian.Uint32(raw[0:4]),
 322  		To:   binary.LittleEndian.Uint32(raw[4:8]),
 323  	}
 324  	n := binary.LittleEndian.Uint32(raw[8:12])
 325  	if n > uint32(len(raw)/spendSize) {
 326  		return Diff{}, ErrShortDiff
 327  	}
 328  	d.Touches = make([]Touch, 0, n)
 329  	at := 12
 330  	for i := uint32(0); i < n; i++ {
 331  		if at+spendSize > len(raw) {
 332  			return Diff{}, ErrShortDiff
 333  		}
 334  		var t Touch
 335  		copy(t.OutPoint.Hash[:], raw[at:at+32])
 336  		t.OutPoint.Index = binary.LittleEndian.Uint32(raw[at+32 : at+36])
 337  		t.Height = binary.LittleEndian.Uint32(raw[at+36 : at+40])
 338  		t.Spent = raw[at+40] == 1
 339  		at += spendSize
 340  		if !t.Spent {
 341  			if at+21 > len(raw) {
 342  				return Diff{}, ErrShortDiff
 343  			}
 344  			t.New.Value = int64(binary.LittleEndian.Uint64(raw[at : at+8]))
 345  			copy(t.New.ScriptHash[:], raw[at+8:at+16])
 346  			t.New.Coinbase = raw[at+16] == 1
 347  			t.New.OutPoint = t.OutPoint
 348  			t.New.Height = binary.LittleEndian.Uint32(raw[at+17 : at+21])
 349  			at += 21
 350  		}
 351  		d.Touches = append(d.Touches, t)
 352  	}
 353  	if at != len(raw) {
 354  		return Diff{}, fmt.Errorf("utxo: %d trailing bytes in a diff", len(raw)-at)
 355  	}
 356  	return d, nil
 357  }
 358