github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/encoding/web3hex/decoder.go (about)

     1  package web3hex
     2  
     3  import (
     4  	"fmt"
     5  	"math/big"
     6  	"strings"
     7  
     8  	"github.com/hyperledger/burrow/crypto"
     9  	"github.com/tmthrgd/go-hex"
    10  )
    11  
    12  type Decoder struct {
    13  	error
    14  	must bool
    15  }
    16  
    17  func (d *Decoder) Must() *Decoder {
    18  	return &Decoder{must: true}
    19  }
    20  
    21  func (d *Decoder) Err() error {
    22  	return d.error
    23  }
    24  
    25  func (d *Decoder) pushErr(err error) {
    26  	if d.must {
    27  		panic(err)
    28  	}
    29  	if d.error == nil {
    30  		d.error = err
    31  	}
    32  }
    33  
    34  func (d *Decoder) Bytes(hs string) []byte {
    35  	hexString := strings.TrimPrefix(hs, "0x")
    36  	// Ethereum returns odd-length hexString strings when it removes leading zeros
    37  	if len(hexString)%2 == 1 {
    38  		hexString = "0" + hexString
    39  	}
    40  	bs, err := hex.DecodeString(hexString)
    41  	if err != nil {
    42  		d.pushErr(fmt.Errorf("could not decode bytes from '%s': %w", hs, err))
    43  	}
    44  	return bs
    45  }
    46  
    47  func (d *Decoder) Address(hs string) crypto.Address {
    48  	if hs == "" {
    49  		return crypto.Address{}
    50  	}
    51  	address, err := crypto.AddressFromBytes(d.Bytes(hs))
    52  	if err != nil {
    53  		d.pushErr(fmt.Errorf("could not decode address from '%s': %w", hs, err))
    54  	}
    55  	return address
    56  }
    57  
    58  func (d *Decoder) BigInt(hs string) *big.Int {
    59  	return new(big.Int).SetBytes(d.Bytes(hs))
    60  }
    61  
    62  func (d *Decoder) Uint64(hs string) uint64 {
    63  	bi := d.BigInt(hs)
    64  	if !bi.IsUint64() {
    65  		d.pushErr(fmt.Errorf("%v is not uint64", bi))
    66  	}
    67  	return bi.Uint64()
    68  }
    69  
    70  func (d *Decoder) Int64(hs string) int64 {
    71  	bi := d.BigInt(hs)
    72  	if !bi.IsInt64() {
    73  		d.pushErr(fmt.Errorf("%v is not int64", bi))
    74  	}
    75  	return bi.Int64()
    76  }