// Package chains holds the two chain profiles the service follows. // // The profiles are nostrino's, copied byte for byte so this module pins the // constants it was tested against rather than whatever a shared checkout // happens to say. The fork rule itself is not reimplemented: block hashes of // version 2 headers and their proof of work are asked of nostrino's btcwire // and neutrino packages, which carry the fork's vectors. package chains import ( "bytes" "encoding/hex" "fmt" "math/bits" btcdwire "github.com/btcsuite/btcd/wire/v2" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // Parent is the chain the fork rides on. const Parent = "btc" // Fork is the forked chain, called xbt in the profiles and blake by the // application that uses it. const Fork = "xbt" // ParentRetarget is the parent chain's retarget interval, which is the snapshot // cadence of the UTXO dataset. It is the same on both chains: the fork changes // the header form and the one-off target shift, not the interval. const ParentRetarget uint32 = 2016 // SharedLastHeight is the last height whose block both chains produce. const SharedLastHeight = 961631 // ForkFirstHeight is the first height at which the fork writes a version 2 // header. Heights SharedLastHeight+1 to ForkFirstHeight-1 are Bitcoin-format // headers on both chains. const ForkFirstHeight = 961640 // ParentProfileJSON is the Bitcoin mainnet profile in nostrino's format. const ParentProfileJSON = `{ "name": "btc", "magic": "f9beb4d9", "genesis_header": "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c", "genesis_hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f", "p2p_port": "8333", "bech32_hrp": "bc", "pow_limit_bits": "1d00ffff", "target_spacing": 600, "target_timespan": 1209600, "retarget_interval": 2016 }` // ForkProfileJSON is the XBT mainnet profile: the same genesis and magic, with // the header format change and the one-off target shift at the fork. const ForkProfileJSON = `{ "name": "xbt", "magic": "f9beb4d9", "genesis_header": "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c", "genesis_hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f", "p2p_port": "8333", "bech32_hrp": "bc", "pow_limit_bits": "1d00ffff", "target_spacing": 600, "target_timespan": 1209600, "retarget_interval": 2016, "header_v2_height": 961640, "target_shift": 22, "checkpoint": { "height": 961631, "block_hash": "00000000000000000000807f9dc917442a67910426d79ebb2f8aa2149327ce8a", "filter_header": "323d85f60703ce8b32e56bcaab8ccbe1b121abe7669aed933f557767194bb3f6" } }` // Profile returns one profile by the name the application uses. func Profile(name string) (*chain.Profile, error) { ps, err := Profiles() if err != nil { return nil, err } for _, p := range ps { if p.Name == name { return p, nil } } return nil, fmt.Errorf("chains: no profile %q", name) } // Chain is one of the chains this service follows. type Chain struct { // Name is "btc" or "xbt". Name string // Profile carries the chain's header and difficulty rules. Profile *chain.Profile // Exported is what a harness publishes: the genesis header, the difficulty // limit and spacing, so a regtest node can be started on the same chain. Exported ExportedChain } // ExportedChain is everything a node needs to run this chain's rules. type ExportedChain struct { // Magic is the p2p network magic this chain's nodes talk. A node started on // these parameters uses it, so a harness that starts one and a peer that // dials one both read it here rather than from the parent profile: regtest // nodes do not share their magic with the chain they are testing. Magic uint32 `json:"magic"` GenesisHeader string `json:"genesis_header"` GenesisHash string `json:"genesis_hash"` PowLimitBits string `json:"pow_limit_bits"` TargetSpacing int64 `json:"target_spacing"` TargetTimespan int64 `json:"target_timespan"` Retarget uint32 `json:"retarget_interval"` // Maturity is the chain's coinbase maturity rule. It is a rule and not a // constant: see MaturityRule. Maturity MaturityRule `json:"maturity"` } // MaturityRule is how long a coinbase output must wait before it may be spent, // as the node enforces it. // // The rule is not one number. A node can schedule a window in which coinbases // created at or after LongStart need Long blocks instead of Base, and the window // closes again at LongRelease. The fork does exactly this, and its schedule is // in this file. The three heights are compared differently: LongStart against // the coinbase's own height, and LongEnforce and LongRelease against the height // of the block that spends it. That asymmetry is the node's, not this type's // simplification, and RequiredAt reproduces it. type MaturityRule struct { // Base is the ordinary requirement, 100 on Bitcoin. Base uint32 `json:"base"` // Long is the requirement inside the window for coinbases created at or // after LongStart. Zero means no window is scheduled. Long uint32 `json:"long"` // LongStart is the first coinbase height the long requirement applies to. LongStart uint32 `json:"long_start"` // LongEnforce is the first spend height at which the window is active. LongEnforce uint32 `json:"long_enforce"` // LongRelease is the first spend height at which it is no longer active. LongRelease uint32 `json:"long_release"` } // RequiredAt is how many blocks must separate the coinbase's block from the // block that spends it, for a spend at spendHeight of an output created at // coinHeight. func (m MaturityRule) RequiredAt(coinHeight, spendHeight uint32) uint32 { if m.Long == 0 { return m.Base } // The window is opened and closed by the spend height; which requirement // applies to the coin is decided by the coin's own height. if spendHeight >= m.LongEnforce && spendHeight < m.LongRelease && coinHeight >= m.LongStart { return m.Long } return m.Base } // Scheduled reports whether the chain has a long-maturity window at all. func (m MaturityRule) Scheduled() bool { return m.Long != 0 } // parentExported and forkExported are the two chains' consensus parameters. The // fork's genesis is Bitcoin's block: the fork reuses the genesis, the magic and // the port, and changes the header from ForkFirstHeight on. var ( parentExported = ExportedChain{ GenesisHeader: parentGenesisHeader, GenesisHash: parentGenesisHash, PowLimitBits: "1d00ffff", TargetSpacing: 600, TargetTimespan: 1209600, Retarget: 2016, // Bitcoin Core enforces 100 and schedules nothing else. Maturity: MaturityRule{Base: 100}, } // forkExported starts as the parent's parameters because the fork reuses // the genesis, the magic and the port. The coinbase maturity is the rule // that differs, and the numbers are the fork node's own, from its // chainparams: the long-maturity window is scheduled after the header // upgrade rather than at genesis, so the requirement is 100 outside it and // 6480 inside it for coinbases created at or after 973440. forkExported = func() ExportedChain { e := parentExported e.Maturity = MaturityRule{ Base: 100, Long: 6480, LongStart: 973440, LongEnforce: 973440, LongRelease: 979920, } return e }() // regtestExported is the local test chain: Bitcoin Core's regtest // parameters, which is the chain the gate's node runs. Its genesis is not // mainnet's, and a store anchored on the wrong one refuses every header a // node sends. regtestExported = ExportedChain{ // The magic a chain's regtest nodes listen on. Bitcoin Core's regtest // and btcd's regression test both use this one, which is neither the // parent chain's nor btcd's - it is the network both harnesses start // when asked for a regtest chain. Magic: regtestMagic, GenesisHeader: regtestGenesisHeader, GenesisHash: regtestGenesisHash, PowLimitBits: "207fffff", TargetSpacing: 600, TargetTimespan: 1209600, Retarget: 144, // Regtest schedules no long window unless the node is started with // -coinbase-maturity-long-*, which the rig does not do. Maturity: MaturityRule{Base: 100}, } ) // WireMagic is a profile's magic in the order btcd's wire writes it. // // The profile carries the magic as the four bytes appear on the wire: mainnet // is f9beb4d9. btcd's BitcoinNet is those same four bytes read as a // little-endian uint32, so its mainnet constant is d9b4bef9. Passing the // profile's value straight to a btcd type reverses the magic of every frame it // writes, which a node discards without a word, and the connection waits for a // version that will never come. func WireMagic(p *chain.Profile) btcdwire.BitcoinNet { return btcdwire.BitcoinNet(bits.ReverseBytes32(p.Magic)) } // WireMagic is this chain's magic in btcd's convention. func (c Chain) WireMagic() btcdwire.BitcoinNet { return WireMagic(c.Profile) } const ( // regtestMagic is the p2p network magic a regtest node listens on, in // btcd's convention. // regtestMagic is measured, not assumed: a bitcoind started with -regtest // accepts this magic and no other, and a peer that dials it with Bitcoin // Core's own regtest magic completes the key exchange and then has every // packet dropped. The value is btcd's test-chain magic. regtestMagic = 0xdab5bffa // regtestMagicWire is the same magic as the four bytes on the wire, which // is the form a profile carries. regtestMagicWire = 0xfabfb5da ) const ( regtestGenesisHash = "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206" // regtestGenesisHeader is the first eighty bytes of the block a regtest // node reports for height 0: version 1, no previous block, the same // merkle root as mainnet's genesis, time 1296688602, bits 0x207fffff and // nonce 2. regtestGenesisHeader = "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4adae5494dffff7f2002000000" parentGenesisHash = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f" parentGenesisHeader = "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c" ) // Genesis decodes the chain's genesis header into the form the stores use, and // returns its hash. Both chains carry the same genesis: the fork reuses // Bitcoin's block and changes the header form from ForkFirstHeight on. // // The header is built by btcd's deserializer, which is the one that agrees with // a node on a header's hash; the stores' header type builds its bytes in a // layout that hashes differently, so it is converted field by field from what // btcd read. A store anchored on anything but this header refuses every header // a peer sends, because each one carries this hash on its PrevBlock. func (c Chain) Genesis() (btcwire.BlockHeader, error) { raw, err := hex.DecodeString(c.Exported.GenesisHeader) if err != nil { return btcwire.BlockHeader{}, fmt.Errorf("chains: %s genesis: %w", c.Name, err) } var v btcdwire.BlockHeader if err := v.Deserialize(bytes.NewReader(raw)); err != nil { return btcwire.BlockHeader{}, fmt.Errorf("chains: %s genesis: %w", c.Name, err) } want, err := chainhash.NewHashFromStr(c.Exported.GenesisHash) if err != nil { return btcwire.BlockHeader{}, fmt.Errorf("chains: %s genesis hash: %w", c.Name, err) } // The chain names a block by its reversed hash; the stores hold hashes in // the order they compute them, so the comparison is made reversed. if got := [32]byte(v.BlockHash()); got != [32]byte(*want) && reverse32(got[:]) != [32]byte(*want) { return btcwire.BlockHeader{}, fmt.Errorf("chains: %s genesis header hashes to %x, the profile names %s", c.Name, got, want) } return btcwire.BlockHeader{ Version: v.Version, PrevBlock: [32]byte(v.PrevBlock), MerkleRoot: [32]byte(v.MerkleRoot), Timestamp: uint32(v.Timestamp.Unix()), Bits: v.Bits, Nonce: v.Nonce, }, nil } // ParentChain returns the chain the fork rides on. func ParentChain() (Chain, error) { p, err := chain.ParseProfile([]byte(ParentProfileJSON)) if err != nil { return Chain{}, err } return Chain{Name: Parent, Profile: p, Exported: parentExported}, nil } // ForkChain returns the forked chain. func ForkChain() (Chain, error) { p, err := chain.ParseProfile([]byte(ForkProfileJSON)) if err != nil { return Chain{}, err } return Chain{Name: Fork, Profile: p, Exported: forkExported}, nil } // reverse32 returns a hash in the order a chain prints it, which is the // reverse of the order this project and btcd both compute it in. func reverse32(b []byte) [32]byte { var out [32]byte for i := 0; i < 32; i++ { out[i] = b[31-i] } return out } // Regtest returns the local test chain, for the harness tests that run against // a regtest node. func Regtest() Chain { chainInfo, err := ParentChain() if err != nil { // The profile could not be parsed, so there is no fork or parent to // name: an empty name is honest, a name taken from the caller's // default is a wrong value returned as if it were read. return Chain{Exported: regtestExported} } chainInfo.Exported = regtestExported // A regtest node's net magic is the regtest chain's, not the one the node // would use on the parent network: a peer that dials a regtest node with // the parent's magic completes the key exchange and then has every packet // dropped, which reads as a stalled handshake. if p, err := chain.ParseProfile([]byte(ParentProfileJSON)); err == nil { p.Magic = regtestMagicWire chainInfo.Profile = p } return chainInfo } // ByName returns a chain by the name the application uses. func ByName(name string) (Chain, error) { switch name { case Parent: return ParentChain() case Fork: return ForkChain() } return Chain{}, fmt.Errorf("chains: no chain %q", name) } func Profiles() ([]*chain.Profile, error) { btc, err := chain.ParseProfile([]byte(ParentProfileJSON)) if err != nil { return nil, fmt.Errorf("chains: btc profile: %w", err) } xbt, err := chain.ParseProfile([]byte(ForkProfileJSON)) if err != nil { return nil, fmt.Errorf("chains: xbt profile: %w", err) } if btc.HeaderV2Height != 0 { return nil, fmt.Errorf("chains: the btc profile carries a fork height") } if xbt.HeaderV2Height == 0 { return nil, fmt.Errorf("chains: the xbt profile has no fork height") } if btc.GenesisHash != xbt.GenesisHash || btc.Magic != xbt.Magic { return nil, fmt.Errorf("chains: the two profiles do not share a genesis") } return []*chain.Profile{btc, xbt}, nil }