package utxostore_test import ( "encoding/binary" "os" "sort" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/utxo" utxostore "git.smesh.lol/btcd-lite/internal/utxo/store" "git.smesh.lol/btcd-lite/internal/wire" ) func sortLikeStore(set []utxo.Entry) { sort.Slice(set, func(i, j int) bool { return utxo.LessEntry(set[i], set[j]) }) } // benchSet builds an in-memory set of n entries keyed like real outpoints. func benchSet(n int) []utxo.Entry { set := make([]utxo.Entry, n) for i := 0; i < n; i++ { var h [32]byte binary.BigEndian.PutUint64(h[0:8], uint64(i)*0x9E3779B97F4A7C15) binary.BigEndian.PutUint64(h[24:32], uint64(i)) set[i] = utxo.Entry{OutPoint: wire.OutPoint{Hash: h}, Value: int64(i), Height: uint32(i % 1000)} } // The generator is not monotonic in the hash's byte order, so sort it the // way the store's sets are sorted. sortLikeStore(set) return set } // TestDiskMergeRate measures what the plan's rebuild figure rests on: the // bytes a diff merge streams, and the rate it streams them at from disk. // // The numbers go into docs/PLAN.md, not into an assertion: a 70 million entry // set is not a test fixture, so the probe runs a slice of it and reports the // rate per entry. func TestDiskMergeRate(t *testing.T) { if testing.Short() { t.Skip("long") } // The probe writes to the real disk when BTCD_LITE_PROBE_DIR names a // directory on it: a temp directory on tmpfs measures memory, and the // number the plan needs is a disk's. dir := t.TempDir() if d := os.Getenv("BTCD_LITE_PROBE_DIR"); d != "" { dir = d } set := benchSet(2_000_000) if _, err := utxostore.WriteSet(dir, 0, set); err != nil { t.Fatal(err) } if _, err := utxostore.Promote(dir, 0); err != nil { t.Fatal(err) } // A diff that touches one outpoint in a thousand, half spent from the set // and half created. var ts []utxo.Touch for i := 0; i < len(set); i += 1000 { ts = append(ts, utxo.Touch{OutPoint: set[i].OutPoint, Height: 1, Spent: true}) } for i := 0; i < len(set)/1000; i++ { var h [32]byte binary.BigEndian.PutUint64(h[0:8], uint64(i)*0x2545F4914F6CDD1D) binary.BigEndian.PutUint64(h[24:32], ^uint64(i)) op := wire.OutPoint{Hash: h} ts = append(ts, utxo.Touch{OutPoint: op, Height: 1, New: utxo.Entry{OutPoint: op, Value: 1, Height: 1}}) } if _, err := utxostore.CutRange(dir, 0, 1, ts); err != nil { t.Fatal(err) } start := timeNow() d, err := utxostore.LoadDiff(dir, 0, 1) if err != nil { t.Fatal(err) } name, err := utxostore.MergeRange(dir, 0, 1, d, chainhash.Hash{}) if err != nil { t.Fatal(err) } elapsed := timeSince(start) t.Logf("merged %d entries and %d touches from disk in %s: %.1f M entries/s, %.0f MB/s; result %s", len(set), len(ts), elapsed.Round(millisecond), float64(len(set)+len(ts))/elapsed.Seconds()/1e6, float64(len(set)+len(ts))*utxo.EntryEncodeSize/elapsed.Seconds()/1e6, name) }