package btcwire import ( "crypto/sha256" "encoding/binary" "errors" "fmt" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "golang.org/x/crypto/blake2b" ) // This file carries the forked chain's header format: a version 2 header that appends 84 bytes // of mining fields to the ordinary 80-byte header, and the proof-of-work hash those fields are // committed to. // // The fork reuses Bitcoin's genesis, magic and port, so only these two things differ. Everything // here is gated on the header's own version flag, which means a Bitcoin header never enters any // of it. const ( // HeaderV2Flag marks a version 2 header. It is not a consensus version bit: the rest of // the version field keeps its Bitcoin meaning below the flag. HeaderV2Flag uint32 = 0x80000000 // HeaderV2FieldsSize is the number of bytes a version 2 header appends to the ordinary // 80-byte header. HeaderV2FieldsSize = 84 // BlockHeaderV2Size is the full size of a version 2 header. BlockHeaderV2Size = BlockHeaderSize + HeaderV2FieldsSize // headerV2FlagUseTimeOffset is the flag bit that says the wire time is offset from the // header's real time. headerV2FlagUseTimeOffset uint8 = 4 ) // HeaderV2 holds the fork's extra header fields, in wire order. type HeaderV2 struct { Nonce2 uint32 Nonce3 uint32 Extranonce [16]byte TimeOffset uint32 TxCount uint16 Flags uint8 XorKeyClear uint8 XorKey [16]byte Height int32 MMRHS chainhash.Hash } // IsV2 reports whether the header carries the fork's version flag. func (h *BlockHeader) IsV2() bool { return uint32(h.Version)&HeaderV2Flag != 0 } // TimeOnWire is the timestamp the header puts on the wire: the mining fields may carry it as an // offset from the real time to leave room for grinding. func (h *BlockHeader) TimeOnWire() uint32 { if h.V2 == nil { return h.Timestamp } if h.V2.Flags&headerV2FlagUseTimeOffset == 0 { return h.Timestamp } return h.Timestamp - h.V2.TimeOffset } // SerializeV2 returns the 164-byte wire encoding of a version 2 header. func (h *BlockHeader) SerializeV2() []byte { b := make([]byte, BlockHeaderV2Size) binary.LittleEndian.PutUint32(b[0:4], uint32(h.Version)) copy(b[4:36], h.PrevBlock[:]) copy(b[36:68], h.MerkleRoot[:]) binary.LittleEndian.PutUint32(b[68:72], h.TimeOnWire()) binary.LittleEndian.PutUint32(b[72:76], h.Bits) binary.LittleEndian.PutUint32(b[76:80], h.Nonce) v := h.V2 binary.LittleEndian.PutUint32(b[80:84], v.Nonce2) binary.LittleEndian.PutUint32(b[84:88], v.Nonce3) copy(b[88:104], v.Extranonce[:]) binary.LittleEndian.PutUint32(b[104:108], v.TimeOffset) binary.LittleEndian.PutUint16(b[108:110], v.TxCount) b[110] = v.Flags b[111] = v.XorKeyClear copy(b[112:128], v.XorKey[:]) binary.LittleEndian.PutUint32(b[128:132], uint32(v.Height)) copy(b[132:164], v.MMRHS[:]) return b } // DeserializeAny decodes either kind of header from a buffer whose length is the header's own: // 80 bytes for a Bitcoin header, 164 for a version 2 one. The version flag decides, so a caller // that reads whole records does not have to. func (h *BlockHeader) DeserializeAny(b []byte) error { if len(b) == BlockHeaderV2Size { return h.DeserializeV2(b) } return h.Deserialize(b) } // SerializeAll returns the header's wire encoding, which is 164 bytes for a version 2 header and // 80 for anything else. func (h *BlockHeader) SerializeAll() []byte { if h.V2 == nil { b := h.Serialize() return b[:] } return h.SerializeV2() } // DeserializeV2 replaces h with the header decoded from the first 164 bytes of b. func (h *BlockHeader) DeserializeV2(b []byte) error { if len(b) < BlockHeaderV2Size { return fmt.Errorf("btcwire: version 2 header needs %d bytes, got %d: %w", BlockHeaderV2Size, len(b), errors.New("short header")) } if err := h.Deserialize(b[:BlockHeaderSize]); err != nil { return err } v := &HeaderV2{} v.Nonce2 = binary.LittleEndian.Uint32(b[80:84]) v.Nonce3 = binary.LittleEndian.Uint32(b[84:88]) copy(v.Extranonce[:], b[88:104]) v.TimeOffset = binary.LittleEndian.Uint32(b[104:108]) v.TxCount = binary.LittleEndian.Uint16(b[108:110]) v.Flags = b[110] v.XorKeyClear = b[111] copy(v.XorKey[:], b[112:128]) v.Height = int32(binary.LittleEndian.Uint32(b[128:132])) copy(v.MMRHS[:], b[132:164]) h.V2 = v h.Timestamp += v.TimeOffset if v.Flags&headerV2FlagUseTimeOffset == 0 { h.Timestamp -= v.TimeOffset } return nil } // taggedHash returns the tag prefix Core's TaggedHash starts a writer with: the tag hashed twice // by SHA-256. func taggedHash(tag string) []byte { sum := sha256.Sum256([]byte(tag)) out := make([]byte, 0, 2*sha256.Size) out = append(out, sum[:]...) out = append(out, sum[:]...) return out } // singleSHA256 finalizes a tagged writer the way Core's GetSHA256 does: one SHA-256 over the tag // prefix and the data, not a double hash. func singleSHA256(parts ...[]byte) chainhash.Hash { h := sha256.New() for _, part := range parts { h.Write(part) } var out chainhash.Hash copy(out[:], h.Sum(nil)) return out } // u32 writes a uint32 the way the serializers do, little endian. func u32(value uint32) []byte { var b [4]byte binary.LittleEndian.PutUint32(b[:], value) return b[:] } // ForkHash returns the proof-of-work hash of a version 2 header, in internal byte order, which is // the order every other hash in this package uses. // // The construction is Core's CBlockHeader::GetHash for m_header_v2: tagged SHA-256 over the // fields the mining hardware never sees, a merge-mining hook, then two unkeyed BLAKE2b-256 passes // over the byte streams the ASIC actually grinds, and finally an XOR mask that only the pool // knows. func ForkHash(h *BlockHeader) (chainhash.Hash, error) { if h.V2 == nil { return chainhash.Hash{}, errors.New("btcwire: fork hash needs a version 2 header") } v := h.V2 // The xor key is only known to the pool, so it enters the hash through a tag and two // hashes rather than directly. xorKeyHash := singleSHA256( taggedHash("Bitcoin block hash PoW XOR key"), v.XorKey[:], ) var mask [32]byte if v.XorKey != [16]byte{} { mask = singleSHA256(taggedHash("Bitcoin block hash PoW XOR mask"), v.XorKey[:]) clearBytes := int(v.XorKeyClear / 8) for i := 0; i < clearBytes && i < len(mask); i++ { mask[i] = 0 } if clearBytes < len(mask) { mask[clearBytes] &= 0xff >> (v.XorKeyClear % 8) } } // The previous block enters the pre-image in display order, then once more hashed, because // the hardware is only shown a hash of it. var prevOrdered [32]byte for i := 0; i < 32; i++ { prevOrdered[i] = h.PrevBlock[31-i] } prevHidden := singleSHA256(taggedHash("Bitcoin prevblock header, hashed"), prevOrdered[:]) h1 := make([]byte, 0, 119) h1 = append(h1, u32(uint32(h.Version))...) h1 = append(h1, prevOrdered[:]...) h1 = append(h1, u32(uint32(v.Height))...) h1 = append(h1, h.MerkleRoot[:]...) h1 = append(h1, u32(h.TimeOnWire())...) h1 = append(h1, 0) // reserved for an extended 40-bit time h1 = append(h1, u32(h.Bits)...) h1 = append(h1, u32(uint32(v.TxCount))...) h1 = append(h1, v.Flags) h1 = append(h1, v.XorKeyClear) h1 = append(h1, xorKeyHash[:]...) if len(h1) != 119 { return chainhash.Hash{}, fmt.Errorf("btcwire: version 2 header pre-image is %d bytes, want 119", len(h1)) } h1Hash := singleSHA256(taggedHash("Bitcoin block header 1"), h1) var zeros [16]byte h2 := singleSHA256( taggedHash("Merge-mining hook"), h1Hash[:], zeros[:], zeros[:], v.MMRHS[:], ) // The first BLAKE2b pass covers what the mining machine is told: a zero word, the hook // hash, and the extranonce. first := make([]byte, 0, 52) first = append(first, u32(0)...) first = append(first, h2[:]...) first = append(first, v.Extranonce[:]...) digest := blake2b.Sum256(first) // The second pass is what the ASIC grinds; which fields it sees depends on the flag's low // two bits. var stream []byte switch v.Flags & 3 { case 3: stream = append(stream, zeros[:]...) stream = append(stream, zeros[:]...) fallthrough case 2: for i := 0; i < 3; i++ { stream = append(stream, zeros[:]...) } stream = append(stream, h2[:]...) stream = append(stream, u32(h.Nonce)...) stream = append(stream, u32(v.Nonce2)...) stream = append(stream, u32(v.TimeOffset)...) stream = append(stream, u32(v.Nonce3)...) stream = append(stream, digest[:]...) case 0: hidden := prevHidden for i := 0; i < 6; i++ { hidden[i] = 0 } stream = append(stream, hidden[:]...) stream = append(stream, u32(h.Nonce)...) stream = append(stream, u32(v.Nonce2)...) stream = append(stream, u32(v.TimeOffset)...) stream = append(stream, u32(v.Nonce3)...) stream = append(stream, digest[:]...) case 1: stream = append(stream, u32(h.Nonce)...) stream = append(stream, u32(v.Nonce2)...) stream = append(stream, u32(v.Nonce3)...) stream = append(stream, u32(v.TimeOffset)...) stream = append(stream, digest[:]...) stream = append(stream, h2[:]...) } final := blake2b.Sum256(stream) // The display hash is the second digest XOR the mask; internally that is the same bytes in // reverse, which is what this package calls a hash. var out chainhash.Hash for i := 0; i < 32; i++ { out[31-i] = final[i] ^ mask[i] } return out, nil }