github.com/bchainhub/blockbook@v0.3.2/bchain/coins/ritocoin/ritocoinparser.go (about)

     1  package ritocoin
     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  // magic numbers
    14  const (
    15  	MainnetMagic wire.BitcoinNet = 0x2a7bc0a1
    16  	TestnetMagic wire.BitcoinNet = 0x514E5352
    17  )
    18  
    19  // chain parameters
    20  var (
    21  	MainNetParams chaincfg.Params
    22  	TestNetParams chaincfg.Params
    23  )
    24  
    25  func init() {
    26  	MainNetParams = chaincfg.MainNetParams
    27  	MainNetParams.Net = MainnetMagic
    28  	MainNetParams.PubKeyHashAddrID = []byte{25}
    29  	MainNetParams.ScriptHashAddrID = []byte{105}
    30  
    31  	TestNetParams = chaincfg.TestNet3Params
    32  	TestNetParams.Net = TestnetMagic
    33  	TestNetParams.PubKeyHashAddrID = []byte{111}
    34  	TestNetParams.ScriptHashAddrID = []byte{196}
    35  }
    36  
    37  // RitocoinParser handle
    38  type RitocoinParser struct {
    39  	*btc.BitcoinParser
    40  }
    41  
    42  // NewRitocoinParser returns new RitocoinParser instance
    43  func NewRitocoinParser(params *chaincfg.Params, c *btc.Configuration) *RitocoinParser {
    44  	return &RitocoinParser{BitcoinParser: btc.NewBitcoinParser(params, c)}
    45  }
    46  
    47  // GetChainParams contains network parameters
    48  func GetChainParams(chain string) *chaincfg.Params {
    49  	if !chaincfg.IsRegistered(&MainNetParams) {
    50  		err := chaincfg.Register(&MainNetParams)
    51  		if err == nil {
    52  			err = chaincfg.Register(&TestNetParams)
    53  		}
    54  		if err != nil {
    55  			panic(err)
    56  		}
    57  	}
    58  	switch chain {
    59  	case "test":
    60  		return &TestNetParams
    61  	default:
    62  		return &MainNetParams
    63  	}
    64  }
    65  
    66  // ParseBlock parses raw block to our Block struct
    67  func (p *RitocoinParser) ParseBlock(b []byte) (*bchain.Block, error) {
    68  	r := bytes.NewReader(b)
    69  	w := wire.MsgBlock{}
    70  	h := wire.BlockHeader{}
    71  	err := h.Deserialize(r)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	err = utils.DecodeTransactions(r, 0, wire.WitnessEncoding, &w)
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  
    81  	txs := make([]bchain.Tx, len(w.Transactions))
    82  	for ti, t := range w.Transactions {
    83  		txs[ti] = p.TxFromMsgTx(t, false)
    84  	}
    85  
    86  	return &bchain.Block{
    87  		BlockHeader: bchain.BlockHeader{
    88  			Size: len(b),
    89  			Time: h.Timestamp.Unix(),
    90  		},
    91  		Txs: txs,
    92  	}, nil
    93  }