package block import ( "encoding/binary" "testing" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // TestForkBlockHashesWithItsOwnHeader: a forked block's identity is not the double SHA-256 of its // first 80 bytes. The parser must dispatch on the version flag, hash the whole 164-byte header // with the fork's construction, and start reading transactions after it. func TestForkBlockHashesWithItsOwnHeader(t *testing.T) { tx := make([]byte, 0, 64) tx = append(tx, 2, 0, 0, 0) // version tx = append(tx, 1) // one input tx = append(tx, make([]byte, 32)...) // prevout hash tx = append(tx, 0xff, 0xff, 0xff, 0xff) // prevout index tx = append(tx, 0) // empty script tx = append(tx, 0xff, 0xff, 0xff, 0xff) // sequence tx = append(tx, 1) // one output tx = append(tx, 0x00, 0xe4, 0x0b, 0x54, 0x02, 0, 0, 0) // 10 XBT? any value tx = append(tx, 1, 0x51) // OP_TRUE tx = append(tx, 0, 0, 0, 0) // locktime txid := chainhash.DoubleHashH(tx) var h btcwire.BlockHeader version := uint32(btcwire.HeaderV2Flag) | 0x20000000 h.Version = int32(version) h.MerkleRoot = txid h.Timestamp = 1_700_000_000 h.Bits = 0x1d00ffff h.V2 = &btcwire.HeaderV2{Height: 962_619, Flags: 4, TimeOffset: 30} header := h.SerializeV2() raw := make([]byte, 0, len(header)+len(tx)+3) raw = append(raw, header...) raw = append(raw, 1) raw = append(raw, tx...) parsed, err := Parse(raw) if err != nil { t.Fatal(err) } want := h.BlockHash() if parsed.Hash != want { t.Fatalf("block hash %x, want %x", parsed.Hash, want) } // The legacy 80-byte hash must not be what the parser returned. legacy := chainhash.DoubleHashH(header[:btcwire.BlockHeaderSize]) if parsed.Hash == legacy { t.Fatal("the block was hashed over its first 80 bytes") } if len(parsed.TxIDs) != 1 || parsed.TxIDs[0] != txid { t.Fatalf("transactions %x, want the one built here", parsed.TxIDs) } } // TestLegacyBlockStillHashesOverEightyBytes keeps the Bitcoin path pinned while the fork path is // added beside it. func TestLegacyBlockStillHashesOverEightyBytes(t *testing.T) { tx := make([]byte, 0, 32) tx = append(tx, 2, 0, 0, 0) tx = append(tx, 1) tx = append(tx, make([]byte, 32)...) tx = append(tx, 0xff, 0xff, 0xff, 0xff) tx = append(tx, 0) tx = append(tx, 0xff, 0xff, 0xff, 0xff) tx = append(tx, 1) tx = append(tx, 0x00, 0xe4, 0x0b, 0x54, 0x02, 0, 0, 0) tx = append(tx, 1, 0x51) tx = append(tx, 0, 0, 0, 0) txid := chainhash.DoubleHashH(tx) var h btcwire.BlockHeader h.Version = 0x20000000 h.MerkleRoot = txid h.Timestamp = 1_600_000_000 h.Bits = 0x1d00ffff header := h.Serialize() raw := make([]byte, 0, len(header)+len(tx)+3) raw = append(raw, header[:]...) raw = append(raw, 1) raw = append(raw, tx...) parsed, err := Parse(raw) if err != nil { t.Fatal(err) } if parsed.Hash != h.BlockHash() { t.Fatal("a Bitcoin block no longer hashes over its 80-byte header") } if parsed.Hash != chainhash.DoubleHashH(header[:]) { t.Fatal("the legacy hash changed") } _ = binary.LittleEndian }