github.com/bchainhub/blockbook@v0.3.2/bchain/coins/namecoin/namecoinparser.go (about)

     1  package namecoin
     2  
     3  import (
     4  	"blockbook/bchain"
     5  	"blockbook/bchain/coins/btc"
     6  	"blockbook/bchain/coins/utils"
     7  	"bytes"
     8  
     9  	"github.com/martinboehm/btcd/wire"
    10  	"github.com/martinboehm/btcutil/chaincfg"
    11  )
    12  
    13  const (
    14  	// MainnetMagic is mainnet network constant
    15  	MainnetMagic wire.BitcoinNet = 0xfeb4bef9
    16  )
    17  
    18  var (
    19  	// MainNetParams are parser parameters for mainnet
    20  	MainNetParams chaincfg.Params
    21  )
    22  
    23  func init() {
    24  	MainNetParams = chaincfg.MainNetParams
    25  	MainNetParams.Net = MainnetMagic
    26  	MainNetParams.PubKeyHashAddrID = []byte{52}
    27  	MainNetParams.ScriptHashAddrID = []byte{13}
    28  }
    29  
    30  // NamecoinParser handle
    31  type NamecoinParser struct {
    32  	*btc.BitcoinParser
    33  }
    34  
    35  // NewNamecoinParser returns new NamecoinParser instance
    36  func NewNamecoinParser(params *chaincfg.Params, c *btc.Configuration) *NamecoinParser {
    37  	return &NamecoinParser{BitcoinParser: btc.NewBitcoinParser(params, c)}
    38  }
    39  
    40  // GetChainParams contains network parameters for the main Namecoin network,
    41  // and the test Namecoin network
    42  func GetChainParams(chain string) *chaincfg.Params {
    43  	if !chaincfg.IsRegistered(&MainNetParams) {
    44  		err := chaincfg.Register(&MainNetParams)
    45  		if err != nil {
    46  			panic(err)
    47  		}
    48  	}
    49  	switch chain {
    50  	default:
    51  		return &MainNetParams
    52  	}
    53  }
    54  
    55  // ParseBlock parses raw block to our Block struct
    56  // it has special handling for Auxpow blocks that cannot be parsed by standard btc wire parser
    57  func (p *NamecoinParser) ParseBlock(b []byte) (*bchain.Block, error) {
    58  	r := bytes.NewReader(b)
    59  	w := wire.MsgBlock{}
    60  	h := wire.BlockHeader{}
    61  	err := h.Deserialize(r)
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  	if (h.Version & utils.VersionAuxpow) != 0 {
    66  		if err = utils.SkipAuxpow(r); err != nil {
    67  			return nil, err
    68  		}
    69  	}
    70  
    71  	err = utils.DecodeTransactions(r, 0, wire.WitnessEncoding, &w)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	txs := make([]bchain.Tx, len(w.Transactions))
    77  	for ti, t := range w.Transactions {
    78  		txs[ti] = p.TxFromMsgTx(t, false)
    79  	}
    80  
    81  	return &bchain.Block{
    82  		BlockHeader: bchain.BlockHeader{
    83  			Size: len(b),
    84  			Time: h.Timestamp.Unix(),
    85  		},
    86  		Txs: txs,
    87  	}, nil
    88  }