1 // Package chains holds the two chain profiles the service follows.
2 //
3 // The profiles are nostrino's, copied byte for byte so this module pins the
4 // constants it was tested against rather than whatever a shared checkout
5 // happens to say. The fork rule itself is not reimplemented: block hashes of
6 // version 2 headers and their proof of work are asked of nostrino's btcwire
7 // and neutrino packages, which carry the fork's vectors.
8 package chains
9 10 import (
11 "bytes"
12 "encoding/hex"
13 "fmt"
14 "math/bits"
15 16 btcdwire "github.com/btcsuite/btcd/wire/v2"
17 18 "git.smesh.lol/nostrino/pkg/btcwire"
19 "git.smesh.lol/nostrino/pkg/chain"
20 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
21 )
22 23 // Parent is the chain the fork rides on.
24 const Parent = "btc"
25 26 // Fork is the forked chain, called xbt in the profiles and blake by the
27 // application that uses it.
28 const Fork = "xbt"
29 30 // ParentRetarget is the parent chain's retarget interval, which is the snapshot
31 // cadence of the UTXO dataset. It is the same on both chains: the fork changes
32 // the header form and the one-off target shift, not the interval.
33 const ParentRetarget uint32 = 2016
34 35 // SharedLastHeight is the last height whose block both chains produce.
36 const SharedLastHeight = 961631
37 38 // ForkFirstHeight is the first height at which the fork writes a version 2
39 // header. Heights SharedLastHeight+1 to ForkFirstHeight-1 are Bitcoin-format
40 // headers on both chains.
41 const ForkFirstHeight = 961640
42 43 // ParentProfileJSON is the Bitcoin mainnet profile in nostrino's format.
44 const ParentProfileJSON = `{
45 "name": "btc",
46 "magic": "f9beb4d9",
47 "genesis_header": "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c",
48 "genesis_hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
49 "p2p_port": "8333",
50 "bech32_hrp": "bc",
51 "pow_limit_bits": "1d00ffff",
52 "target_spacing": 600,
53 "target_timespan": 1209600,
54 "retarget_interval": 2016
55 }`
56 57 // ForkProfileJSON is the XBT mainnet profile: the same genesis and magic, with
58 // the header format change and the one-off target shift at the fork.
59 const ForkProfileJSON = `{
60 "name": "xbt",
61 "magic": "f9beb4d9",
62 "genesis_header": "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c",
63 "genesis_hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
64 "p2p_port": "8333",
65 "bech32_hrp": "bc",
66 "pow_limit_bits": "1d00ffff",
67 "target_spacing": 600,
68 "target_timespan": 1209600,
69 "retarget_interval": 2016,
70 "header_v2_height": 961640,
71 "target_shift": 22,
72 "checkpoint": {
73 "height": 961631,
74 "block_hash": "00000000000000000000807f9dc917442a67910426d79ebb2f8aa2149327ce8a",
75 "filter_header": "323d85f60703ce8b32e56bcaab8ccbe1b121abe7669aed933f557767194bb3f6"
76 }
77 }`
78 79 // Profile returns one profile by the name the application uses.
80 func Profile(name string) (*chain.Profile, error) {
81 ps, err := Profiles()
82 if err != nil {
83 return nil, err
84 }
85 for _, p := range ps {
86 if p.Name == name {
87 return p, nil
88 }
89 }
90 return nil, fmt.Errorf("chains: no profile %q", name)
91 }
92 93 // Chain is one of the chains this service follows.
94 type Chain struct {
95 // Name is "btc" or "xbt".
96 Name string
97 // Profile carries the chain's header and difficulty rules.
98 Profile *chain.Profile
99 // Exported is what a harness publishes: the genesis header, the difficulty
100 // limit and spacing, so a regtest node can be started on the same chain.
101 Exported ExportedChain
102 }
103 104 // ExportedChain is everything a node needs to run this chain's rules.
105 type ExportedChain struct {
106 // Magic is the p2p network magic this chain's nodes talk. A node started on
107 // these parameters uses it, so a harness that starts one and a peer that
108 // dials one both read it here rather than from the parent profile: regtest
109 // nodes do not share their magic with the chain they are testing.
110 Magic uint32 `json:"magic"`
111 GenesisHeader string `json:"genesis_header"`
112 GenesisHash string `json:"genesis_hash"`
113 PowLimitBits string `json:"pow_limit_bits"`
114 TargetSpacing int64 `json:"target_spacing"`
115 TargetTimespan int64 `json:"target_timespan"`
116 Retarget uint32 `json:"retarget_interval"`
117 // Maturity is the chain's coinbase maturity rule. It is a rule and not a
118 // constant: see MaturityRule.
119 Maturity MaturityRule `json:"maturity"`
120 }
121 122 // MaturityRule is how long a coinbase output must wait before it may be spent,
123 // as the node enforces it.
124 //
125 // The rule is not one number. A node can schedule a window in which coinbases
126 // created at or after LongStart need Long blocks instead of Base, and the window
127 // closes again at LongRelease. The fork does exactly this, and its schedule is
128 // in this file. The three heights are compared differently: LongStart against
129 // the coinbase's own height, and LongEnforce and LongRelease against the height
130 // of the block that spends it. That asymmetry is the node's, not this type's
131 // simplification, and RequiredAt reproduces it.
132 type MaturityRule struct {
133 // Base is the ordinary requirement, 100 on Bitcoin.
134 Base uint32 `json:"base"`
135 // Long is the requirement inside the window for coinbases created at or
136 // after LongStart. Zero means no window is scheduled.
137 Long uint32 `json:"long"`
138 // LongStart is the first coinbase height the long requirement applies to.
139 LongStart uint32 `json:"long_start"`
140 // LongEnforce is the first spend height at which the window is active.
141 LongEnforce uint32 `json:"long_enforce"`
142 // LongRelease is the first spend height at which it is no longer active.
143 LongRelease uint32 `json:"long_release"`
144 }
145 146 // RequiredAt is how many blocks must separate the coinbase's block from the
147 // block that spends it, for a spend at spendHeight of an output created at
148 // coinHeight.
149 func (m MaturityRule) RequiredAt(coinHeight, spendHeight uint32) uint32 {
150 if m.Long == 0 {
151 return m.Base
152 }
153 // The window is opened and closed by the spend height; which requirement
154 // applies to the coin is decided by the coin's own height.
155 if spendHeight >= m.LongEnforce && spendHeight < m.LongRelease && coinHeight >= m.LongStart {
156 return m.Long
157 }
158 return m.Base
159 }
160 161 // Scheduled reports whether the chain has a long-maturity window at all.
162 func (m MaturityRule) Scheduled() bool { return m.Long != 0 }
163 164 // parentExported and forkExported are the two chains' consensus parameters. The
165 // fork's genesis is Bitcoin's block: the fork reuses the genesis, the magic and
166 // the port, and changes the header from ForkFirstHeight on.
167 var (
168 parentExported = ExportedChain{
169 GenesisHeader: parentGenesisHeader,
170 GenesisHash: parentGenesisHash,
171 PowLimitBits: "1d00ffff",
172 TargetSpacing: 600,
173 TargetTimespan: 1209600,
174 Retarget: 2016,
175 // Bitcoin Core enforces 100 and schedules nothing else.
176 Maturity: MaturityRule{Base: 100},
177 }
178 // forkExported starts as the parent's parameters because the fork reuses
179 // the genesis, the magic and the port. The coinbase maturity is the rule
180 // that differs, and the numbers are the fork node's own, from its
181 // chainparams: the long-maturity window is scheduled after the header
182 // upgrade rather than at genesis, so the requirement is 100 outside it and
183 // 6480 inside it for coinbases created at or after 973440.
184 forkExported = func() ExportedChain {
185 e := parentExported
186 e.Maturity = MaturityRule{
187 Base: 100,
188 Long: 6480,
189 LongStart: 973440,
190 LongEnforce: 973440,
191 LongRelease: 979920,
192 }
193 return e
194 }()
195 196 // regtestExported is the local test chain: Bitcoin Core's regtest
197 // parameters, which is the chain the gate's node runs. Its genesis is not
198 // mainnet's, and a store anchored on the wrong one refuses every header a
199 // node sends.
200 regtestExported = ExportedChain{
201 // The magic a chain's regtest nodes listen on. Bitcoin Core's regtest
202 // and btcd's regression test both use this one, which is neither the
203 // parent chain's nor btcd's - it is the network both harnesses start
204 // when asked for a regtest chain.
205 Magic: regtestMagic,
206 GenesisHeader: regtestGenesisHeader,
207 GenesisHash: regtestGenesisHash,
208 PowLimitBits: "207fffff",
209 TargetSpacing: 600,
210 TargetTimespan: 1209600,
211 Retarget: 144,
212 // Regtest schedules no long window unless the node is started with
213 // -coinbase-maturity-long-*, which the rig does not do.
214 Maturity: MaturityRule{Base: 100},
215 }
216 )
217 218 // WireMagic is a profile's magic in the order btcd's wire writes it.
219 //
220 // The profile carries the magic as the four bytes appear on the wire: mainnet
221 // is f9beb4d9. btcd's BitcoinNet is those same four bytes read as a
222 // little-endian uint32, so its mainnet constant is d9b4bef9. Passing the
223 // profile's value straight to a btcd type reverses the magic of every frame it
224 // writes, which a node discards without a word, and the connection waits for a
225 // version that will never come.
226 func WireMagic(p *chain.Profile) btcdwire.BitcoinNet {
227 return btcdwire.BitcoinNet(bits.ReverseBytes32(p.Magic))
228 }
229 230 // WireMagic is this chain's magic in btcd's convention.
231 func (c Chain) WireMagic() btcdwire.BitcoinNet { return WireMagic(c.Profile) }
232 233 const (
234 // regtestMagic is the p2p network magic a regtest node listens on, in
235 // btcd's convention.
236 // regtestMagic is measured, not assumed: a bitcoind started with -regtest
237 // accepts this magic and no other, and a peer that dials it with Bitcoin
238 // Core's own regtest magic completes the key exchange and then has every
239 // packet dropped. The value is btcd's test-chain magic.
240 regtestMagic = 0xdab5bffa
241 // regtestMagicWire is the same magic as the four bytes on the wire, which
242 // is the form a profile carries.
243 regtestMagicWire = 0xfabfb5da
244 )
245 246 const (
247 regtestGenesisHash = "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"
248 // regtestGenesisHeader is the first eighty bytes of the block a regtest
249 // node reports for height 0: version 1, no previous block, the same
250 // merkle root as mainnet's genesis, time 1296688602, bits 0x207fffff and
251 // nonce 2.
252 regtestGenesisHeader = "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4adae5494dffff7f2002000000"
253 254 parentGenesisHash = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
255 parentGenesisHeader = "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c"
256 )
257 258 // Genesis decodes the chain's genesis header into the form the stores use, and
259 // returns its hash. Both chains carry the same genesis: the fork reuses
260 // Bitcoin's block and changes the header form from ForkFirstHeight on.
261 //
262 // The header is built by btcd's deserializer, which is the one that agrees with
263 // a node on a header's hash; the stores' header type builds its bytes in a
264 // layout that hashes differently, so it is converted field by field from what
265 // btcd read. A store anchored on anything but this header refuses every header
266 // a peer sends, because each one carries this hash on its PrevBlock.
267 func (c Chain) Genesis() (btcwire.BlockHeader, error) {
268 raw, err := hex.DecodeString(c.Exported.GenesisHeader)
269 if err != nil {
270 return btcwire.BlockHeader{}, fmt.Errorf("chains: %s genesis: %w", c.Name, err)
271 }
272 var v btcdwire.BlockHeader
273 if err := v.Deserialize(bytes.NewReader(raw)); err != nil {
274 return btcwire.BlockHeader{}, fmt.Errorf("chains: %s genesis: %w", c.Name, err)
275 }
276 want, err := chainhash.NewHashFromStr(c.Exported.GenesisHash)
277 if err != nil {
278 return btcwire.BlockHeader{}, fmt.Errorf("chains: %s genesis hash: %w", c.Name, err)
279 }
280 // The chain names a block by its reversed hash; the stores hold hashes in
281 // the order they compute them, so the comparison is made reversed.
282 if got := [32]byte(v.BlockHash()); got != [32]byte(*want) && reverse32(got[:]) != [32]byte(*want) {
283 return btcwire.BlockHeader{}, fmt.Errorf("chains: %s genesis header hashes to %x, the profile names %s", c.Name, got, want)
284 }
285 return btcwire.BlockHeader{
286 Version: v.Version,
287 PrevBlock: [32]byte(v.PrevBlock),
288 MerkleRoot: [32]byte(v.MerkleRoot),
289 Timestamp: uint32(v.Timestamp.Unix()),
290 Bits: v.Bits,
291 Nonce: v.Nonce,
292 }, nil
293 }
294 295 // ParentChain returns the chain the fork rides on.
296 func ParentChain() (Chain, error) {
297 p, err := chain.ParseProfile([]byte(ParentProfileJSON))
298 if err != nil {
299 return Chain{}, err
300 }
301 return Chain{Name: Parent, Profile: p, Exported: parentExported}, nil
302 }
303 304 // ForkChain returns the forked chain.
305 func ForkChain() (Chain, error) {
306 p, err := chain.ParseProfile([]byte(ForkProfileJSON))
307 if err != nil {
308 return Chain{}, err
309 }
310 return Chain{Name: Fork, Profile: p, Exported: forkExported}, nil
311 }
312 313 // reverse32 returns a hash in the order a chain prints it, which is the
314 // reverse of the order this project and btcd both compute it in.
315 func reverse32(b []byte) [32]byte {
316 var out [32]byte
317 for i := 0; i < 32; i++ {
318 out[i] = b[31-i]
319 }
320 return out
321 }
322 323 // Regtest returns the local test chain, for the harness tests that run against
324 // a regtest node.
325 func Regtest() Chain {
326 chainInfo, err := ParentChain()
327 if err != nil {
328 // The profile could not be parsed, so there is no fork or parent to
329 // name: an empty name is honest, a name taken from the caller's
330 // default is a wrong value returned as if it were read.
331 return Chain{Exported: regtestExported}
332 }
333 chainInfo.Exported = regtestExported
334 // A regtest node's net magic is the regtest chain's, not the one the node
335 // would use on the parent network: a peer that dials a regtest node with
336 // the parent's magic completes the key exchange and then has every packet
337 // dropped, which reads as a stalled handshake.
338 if p, err := chain.ParseProfile([]byte(ParentProfileJSON)); err == nil {
339 p.Magic = regtestMagicWire
340 chainInfo.Profile = p
341 }
342 return chainInfo
343 }
344 345 // ByName returns a chain by the name the application uses.
346 func ByName(name string) (Chain, error) {
347 switch name {
348 case Parent:
349 return ParentChain()
350 case Fork:
351 return ForkChain()
352 }
353 return Chain{}, fmt.Errorf("chains: no chain %q", name)
354 }
355 356 func Profiles() ([]*chain.Profile, error) {
357 btc, err := chain.ParseProfile([]byte(ParentProfileJSON))
358 if err != nil {
359 return nil, fmt.Errorf("chains: btc profile: %w", err)
360 }
361 xbt, err := chain.ParseProfile([]byte(ForkProfileJSON))
362 if err != nil {
363 return nil, fmt.Errorf("chains: xbt profile: %w", err)
364 }
365 if btc.HeaderV2Height != 0 {
366 return nil, fmt.Errorf("chains: the btc profile carries a fork height")
367 }
368 if xbt.HeaderV2Height == 0 {
369 return nil, fmt.Errorf("chains: the xbt profile has no fork height")
370 }
371 if btc.GenesisHash != xbt.GenesisHash || btc.Magic != xbt.Magic {
372 return nil, fmt.Errorf("chains: the two profiles do not share a genesis")
373 }
374 return []*chain.Profile{btc, xbt}, nil
375 }
376