1 package btcwire
2 3 import (
4 "crypto/sha256"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 9 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
10 "golang.org/x/crypto/blake2b"
11 )
12 13 // This file carries the forked chain's header format: a version 2 header that appends 84 bytes
14 // of mining fields to the ordinary 80-byte header, and the proof-of-work hash those fields are
15 // committed to.
16 //
17 // The fork reuses Bitcoin's genesis, magic and port, so only these two things differ. Everything
18 // here is gated on the header's own version flag, which means a Bitcoin header never enters any
19 // of it.
20 21 const (
22 // HeaderV2Flag marks a version 2 header. It is not a consensus version bit: the rest of
23 // the version field keeps its Bitcoin meaning below the flag.
24 HeaderV2Flag uint32 = 0x80000000
25 26 // HeaderV2FieldsSize is the number of bytes a version 2 header appends to the ordinary
27 // 80-byte header.
28 HeaderV2FieldsSize = 84
29 30 // BlockHeaderV2Size is the full size of a version 2 header.
31 BlockHeaderV2Size = BlockHeaderSize + HeaderV2FieldsSize
32 33 // headerV2FlagUseTimeOffset is the flag bit that says the wire time is offset from the
34 // header's real time.
35 headerV2FlagUseTimeOffset uint8 = 4
36 )
37 38 // HeaderV2 holds the fork's extra header fields, in wire order.
39 type HeaderV2 struct {
40 Nonce2 uint32
41 Nonce3 uint32
42 Extranonce [16]byte
43 TimeOffset uint32
44 TxCount uint16
45 Flags uint8
46 XorKeyClear uint8
47 XorKey [16]byte
48 Height int32
49 MMRHS chainhash.Hash
50 }
51 52 // IsV2 reports whether the header carries the fork's version flag.
53 func (h *BlockHeader) IsV2() bool {
54 return uint32(h.Version)&HeaderV2Flag != 0
55 }
56 57 // TimeOnWire is the timestamp the header puts on the wire: the mining fields may carry it as an
58 // offset from the real time to leave room for grinding.
59 func (h *BlockHeader) TimeOnWire() uint32 {
60 if h.V2 == nil {
61 return h.Timestamp
62 }
63 64 if h.V2.Flags&headerV2FlagUseTimeOffset == 0 {
65 return h.Timestamp
66 }
67 68 return h.Timestamp - h.V2.TimeOffset
69 }
70 71 // SerializeV2 returns the 164-byte wire encoding of a version 2 header.
72 func (h *BlockHeader) SerializeV2() []byte {
73 b := make([]byte, BlockHeaderV2Size)
74 75 binary.LittleEndian.PutUint32(b[0:4], uint32(h.Version))
76 copy(b[4:36], h.PrevBlock[:])
77 copy(b[36:68], h.MerkleRoot[:])
78 binary.LittleEndian.PutUint32(b[68:72], h.TimeOnWire())
79 binary.LittleEndian.PutUint32(b[72:76], h.Bits)
80 binary.LittleEndian.PutUint32(b[76:80], h.Nonce)
81 82 v := h.V2
83 binary.LittleEndian.PutUint32(b[80:84], v.Nonce2)
84 binary.LittleEndian.PutUint32(b[84:88], v.Nonce3)
85 copy(b[88:104], v.Extranonce[:])
86 binary.LittleEndian.PutUint32(b[104:108], v.TimeOffset)
87 binary.LittleEndian.PutUint16(b[108:110], v.TxCount)
88 b[110] = v.Flags
89 b[111] = v.XorKeyClear
90 copy(b[112:128], v.XorKey[:])
91 binary.LittleEndian.PutUint32(b[128:132], uint32(v.Height))
92 copy(b[132:164], v.MMRHS[:])
93 94 return b
95 }
96 97 // DeserializeAny decodes either kind of header from a buffer whose length is the header's own:
98 // 80 bytes for a Bitcoin header, 164 for a version 2 one. The version flag decides, so a caller
99 // that reads whole records does not have to.
100 func (h *BlockHeader) DeserializeAny(b []byte) error {
101 if len(b) == BlockHeaderV2Size {
102 return h.DeserializeV2(b)
103 }
104 105 return h.Deserialize(b)
106 }
107 108 // SerializeAll returns the header's wire encoding, which is 164 bytes for a version 2 header and
109 // 80 for anything else.
110 func (h *BlockHeader) SerializeAll() []byte {
111 if h.V2 == nil {
112 b := h.Serialize()
113 return b[:]
114 }
115 116 return h.SerializeV2()
117 }
118 119 // DeserializeV2 replaces h with the header decoded from the first 164 bytes of b.
120 func (h *BlockHeader) DeserializeV2(b []byte) error {
121 if len(b) < BlockHeaderV2Size {
122 return fmt.Errorf("btcwire: version 2 header needs %d bytes, got %d: %w",
123 BlockHeaderV2Size, len(b), errors.New("short header"))
124 }
125 126 if err := h.Deserialize(b[:BlockHeaderSize]); err != nil {
127 return err
128 }
129 130 v := &HeaderV2{}
131 v.Nonce2 = binary.LittleEndian.Uint32(b[80:84])
132 v.Nonce3 = binary.LittleEndian.Uint32(b[84:88])
133 copy(v.Extranonce[:], b[88:104])
134 v.TimeOffset = binary.LittleEndian.Uint32(b[104:108])
135 v.TxCount = binary.LittleEndian.Uint16(b[108:110])
136 v.Flags = b[110]
137 v.XorKeyClear = b[111]
138 copy(v.XorKey[:], b[112:128])
139 v.Height = int32(binary.LittleEndian.Uint32(b[128:132]))
140 copy(v.MMRHS[:], b[132:164])
141 142 h.V2 = v
143 h.Timestamp += v.TimeOffset
144 145 if v.Flags&headerV2FlagUseTimeOffset == 0 {
146 h.Timestamp -= v.TimeOffset
147 }
148 149 return nil
150 }
151 152 // taggedHash returns the tag prefix Core's TaggedHash starts a writer with: the tag hashed twice
153 // by SHA-256.
154 func taggedHash(tag string) []byte {
155 sum := sha256.Sum256([]byte(tag))
156 out := make([]byte, 0, 2*sha256.Size)
157 out = append(out, sum[:]...)
158 out = append(out, sum[:]...)
159 return out
160 }
161 162 // singleSHA256 finalizes a tagged writer the way Core's GetSHA256 does: one SHA-256 over the tag
163 // prefix and the data, not a double hash.
164 func singleSHA256(parts ...[]byte) chainhash.Hash {
165 h := sha256.New()
166 167 for _, part := range parts {
168 h.Write(part)
169 }
170 171 var out chainhash.Hash
172 copy(out[:], h.Sum(nil))
173 174 return out
175 }
176 177 // u32 writes a uint32 the way the serializers do, little endian.
178 func u32(value uint32) []byte {
179 var b [4]byte
180 binary.LittleEndian.PutUint32(b[:], value)
181 return b[:]
182 }
183 184 // ForkHash returns the proof-of-work hash of a version 2 header, in internal byte order, which is
185 // the order every other hash in this package uses.
186 //
187 // The construction is Core's CBlockHeader::GetHash for m_header_v2: tagged SHA-256 over the
188 // fields the mining hardware never sees, a merge-mining hook, then two unkeyed BLAKE2b-256 passes
189 // over the byte streams the ASIC actually grinds, and finally an XOR mask that only the pool
190 // knows.
191 func ForkHash(h *BlockHeader) (chainhash.Hash, error) {
192 if h.V2 == nil {
193 return chainhash.Hash{}, errors.New("btcwire: fork hash needs a version 2 header")
194 }
195 196 v := h.V2
197 198 // The xor key is only known to the pool, so it enters the hash through a tag and two
199 // hashes rather than directly.
200 xorKeyHash := singleSHA256(
201 taggedHash("Bitcoin block hash PoW XOR key"),
202 v.XorKey[:],
203 )
204 205 var mask [32]byte
206 207 if v.XorKey != [16]byte{} {
208 mask = singleSHA256(taggedHash("Bitcoin block hash PoW XOR mask"), v.XorKey[:])
209 210 clearBytes := int(v.XorKeyClear / 8)
211 212 for i := 0; i < clearBytes && i < len(mask); i++ {
213 mask[i] = 0
214 }
215 216 if clearBytes < len(mask) {
217 mask[clearBytes] &= 0xff >> (v.XorKeyClear % 8)
218 }
219 }
220 221 // The previous block enters the pre-image in display order, then once more hashed, because
222 // the hardware is only shown a hash of it.
223 var prevOrdered [32]byte
224 225 for i := 0; i < 32; i++ {
226 prevOrdered[i] = h.PrevBlock[31-i]
227 }
228 229 prevHidden := singleSHA256(taggedHash("Bitcoin prevblock header, hashed"), prevOrdered[:])
230 231 h1 := make([]byte, 0, 119)
232 h1 = append(h1, u32(uint32(h.Version))...)
233 h1 = append(h1, prevOrdered[:]...)
234 h1 = append(h1, u32(uint32(v.Height))...)
235 h1 = append(h1, h.MerkleRoot[:]...)
236 h1 = append(h1, u32(h.TimeOnWire())...)
237 h1 = append(h1, 0) // reserved for an extended 40-bit time
238 h1 = append(h1, u32(h.Bits)...)
239 h1 = append(h1, u32(uint32(v.TxCount))...)
240 h1 = append(h1, v.Flags)
241 h1 = append(h1, v.XorKeyClear)
242 h1 = append(h1, xorKeyHash[:]...)
243 244 if len(h1) != 119 {
245 return chainhash.Hash{}, fmt.Errorf("btcwire: version 2 header pre-image is %d bytes, want 119", len(h1))
246 }
247 248 h1Hash := singleSHA256(taggedHash("Bitcoin block header 1"), h1)
249 250 var zeros [16]byte
251 252 h2 := singleSHA256(
253 taggedHash("Merge-mining hook"),
254 h1Hash[:],
255 zeros[:],
256 zeros[:],
257 v.MMRHS[:],
258 )
259 260 // The first BLAKE2b pass covers what the mining machine is told: a zero word, the hook
261 // hash, and the extranonce.
262 first := make([]byte, 0, 52)
263 first = append(first, u32(0)...)
264 first = append(first, h2[:]...)
265 first = append(first, v.Extranonce[:]...)
266 267 digest := blake2b.Sum256(first)
268 269 // The second pass is what the ASIC grinds; which fields it sees depends on the flag's low
270 // two bits.
271 var stream []byte
272 273 switch v.Flags & 3 {
274 case 3:
275 stream = append(stream, zeros[:]...)
276 stream = append(stream, zeros[:]...)
277 fallthrough
278 case 2:
279 for i := 0; i < 3; i++ {
280 stream = append(stream, zeros[:]...)
281 }
282 283 stream = append(stream, h2[:]...)
284 stream = append(stream, u32(h.Nonce)...)
285 stream = append(stream, u32(v.Nonce2)...)
286 stream = append(stream, u32(v.TimeOffset)...)
287 stream = append(stream, u32(v.Nonce3)...)
288 stream = append(stream, digest[:]...)
289 case 0:
290 hidden := prevHidden
291 292 for i := 0; i < 6; i++ {
293 hidden[i] = 0
294 }
295 296 stream = append(stream, hidden[:]...)
297 stream = append(stream, u32(h.Nonce)...)
298 stream = append(stream, u32(v.Nonce2)...)
299 stream = append(stream, u32(v.TimeOffset)...)
300 stream = append(stream, u32(v.Nonce3)...)
301 stream = append(stream, digest[:]...)
302 case 1:
303 stream = append(stream, u32(h.Nonce)...)
304 stream = append(stream, u32(v.Nonce2)...)
305 stream = append(stream, u32(v.Nonce3)...)
306 stream = append(stream, u32(v.TimeOffset)...)
307 stream = append(stream, digest[:]...)
308 stream = append(stream, h2[:]...)
309 }
310 311 final := blake2b.Sum256(stream)
312 313 // The display hash is the second digest XOR the mask; internally that is the same bytes in
314 // reverse, which is what this package calls a hash.
315 var out chainhash.Hash
316 317 for i := 0; i < 32; i++ {
318 out[31-i] = final[i] ^ mask[i]
319 }
320 321 return out, nil
322 }
323