package utxostore import ( "sort" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/utxo" "git.smesh.lol/btcd-lite/internal/wire" ) // twoOps are the two outpoints whose order the memory sort and the key file // disagreed on: a and b sort one way by their stored bytes and the other way // when the hash is read from its end. func twoOps(t *testing.T) (wire.OutPoint, wire.OutPoint) { t.Helper() ha, err := chainhash.NewHashFromStr("2d5f4dd2d318e94886272c591c58d3386b4396d83b68e669b673cbe9a9eb1a0a") if err != nil { t.Fatal(err) } hb, err := chainhash.NewHashFromStr("439733ee21a83b5e6e8b2743846345b2d690624868141df4879d046fe1d67e20") if err != nil { t.Fatal(err) } return wire.OutPoint{Hash: *ha, Index: 1}, wire.OutPoint{Hash: *hb, Index: 0} } // TestOneOrderForOutpoints: the merge's comparison and the set's comparison are // one order, and the key lists are sorted by that order and not by the other. // // This is the defect that took real chain keys to find: writeKeys sorted keys // with a comparison that differed from the set's on a pair of outpoints, the // merge walked the base with one order and read keys in the other, and the set // it wrote came out with the right entries in an order nothing else produced. func TestOneOrderForOutpoints(t *testing.T) { t.Run("key lists use the set's order", func(t *testing.T) { var ops []wire.OutPoint for i := uint32(0); i < 500; i++ { var h chainhash.Hash h[0] = byte(i >> 8) h[1] = byte(i) h[31] = byte(255 - i%7) ops = append(ops, wire.OutPoint{Hash: h, Index: i % 3}) } sortBySet(ops) for i := 1; i < len(ops); i++ { if !utxo.LessEntry(utxo.Entry{OutPoint: ops[i-1]}, utxo.Entry{OutPoint: ops[i]}) { t.Fatalf("the key list is out of the set's order at %d", i) } } }) t.Run("the two comparisons agree on the pair", testPairOrder) } func testPairOrder(t *testing.T) { a, b := twoOps(t) byMerge := cmpOp(a, b) bySet := 0 if utxo.LessEntry(utxo.Entry{OutPoint: a}, utxo.Entry{OutPoint: b}) { bySet = -1 } else if utxo.LessEntry(utxo.Entry{OutPoint: b}, utxo.Entry{OutPoint: a}) { bySet = 1 } if byMerge != bySet { // Report both readings so the fix is a decision and not a guess. ra, rb := reverse(a.Hash), reverse(b.Hash) t.Fatalf("the merge compares a to b as %d, the set as %d; bytes order %x vs %x, read from the end %x vs %x", byMerge, bySet, a.Hash[:4], b.Hash[:4], ra[:4], rb[:4]) } // And the order is the one the set uses everywhere: a sorts first here. if bySet >= 0 { t.Fatalf("a does not sort before b") } // A sort of the pair agrees with the comparison. pair := []wire.OutPoint{b, a} sort.Slice(pair, func(i, j int) bool { return cmpOp(pair[i], pair[j]) < 0 }) if pair[0] != a { t.Fatal("sorting the pair does not put a first") } } func reverse(h chainhash.Hash) chainhash.Hash { var out chainhash.Hash for i := 0; i < 32; i++ { out[i] = h[31-i] } return out }