github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/common/math/big.go (about)

     1  // Package math provides integer math utilities.
     2  package math
     3  
     4  import (
     5  	"fmt"
     6  	"math/big"
     7  )
     8  
     9  var (
    10  	tt255     = BigPow(2, 255)
    11  	tt256     = BigPow(2, 256)
    12  	tt256m1   = new(big.Int).Sub(tt256, big.NewInt(1))
    13  	MaxBig256 = new(big.Int).Set(tt256m1)
    14  	tt63      = BigPow(2, 63)
    15  	MaxBig63  = new(big.Int).Sub(tt63, big.NewInt(1))
    16  )
    17  
    18  const (
    19  	// number of bits in a big.Word
    20  	wordBits = 32 << (uint64(^big.Word(0)) >> 63)
    21  	// number of bytes in a big.Word
    22  	wordBytes = wordBits / 8
    23  )
    24  
    25  // HexOrDecimal256 marshals big.Int as hex or decimal.
    26  type HexOrDecimal256 big.Int
    27  
    28  // UnmarshalText implements encoding.TextUnmarshaler.
    29  func (i *HexOrDecimal256) UnmarshalText(input []byte) error {
    30  	bigint, ok := ParseBig256(string(input))
    31  	if !ok {
    32  		return fmt.Errorf("invalid hex or decimal integer %q", input)
    33  	}
    34  	*i = HexOrDecimal256(*bigint)
    35  	return nil
    36  }
    37  
    38  // MarshalText implements encoding.TextMarshaler.
    39  func (i *HexOrDecimal256) MarshalText() ([]byte, error) {
    40  	if i == nil {
    41  		return []byte("0x0"), nil
    42  	}
    43  	return []byte(fmt.Sprintf("%#x", (*big.Int)(i))), nil
    44  }
    45  
    46  // ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax.
    47  // Leading zeros are accepted. The empty string parses as zero.
    48  func ParseBig256(s string) (*big.Int, bool) {
    49  	if s == "" {
    50  		return new(big.Int), true
    51  	}
    52  	var bigint *big.Int
    53  	var ok bool
    54  	if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") {
    55  		bigint, ok = new(big.Int).SetString(s[2:], 16)
    56  	} else {
    57  		bigint, ok = new(big.Int).SetString(s, 10)
    58  	}
    59  	if ok && bigint.BitLen() > 256 {
    60  		bigint, ok = nil, false
    61  	}
    62  	return bigint, ok
    63  }
    64  
    65  // MustParseBig parses s as a 256 bit big integer and panics if the string is invalid.
    66  func MustParseBig256(s string) *big.Int {
    67  	v, ok := ParseBig256(s)
    68  	if !ok {
    69  		panic("invalid 256 bit integer: " + s)
    70  	}
    71  	return v
    72  }
    73  
    74  // BigPow returns a ** b as a big integer.
    75  func BigPow(a, b int64) *big.Int {
    76  	r := big.NewInt(a)
    77  	return r.Exp(r, big.NewInt(b), nil)
    78  }
    79  
    80  // BigMax returns the larger of x or y.
    81  func BigMax(x, y *big.Int) *big.Int {
    82  	if x.Cmp(y) < 0 {
    83  		return y
    84  	}
    85  	return x
    86  }
    87  
    88  // BigMin returns the smaller of x or y.
    89  func BigMin(x, y *big.Int) *big.Int {
    90  	if x.Cmp(y) > 0 {
    91  		return y
    92  	}
    93  	return x
    94  }
    95  
    96  // FirstBitSet returns the index of the first 1 bit in v, counting from LSB.
    97  func FirstBitSet(v *big.Int) int {
    98  	for i := 0; i < v.BitLen(); i++ {
    99  		if v.Bit(i) > 0 {
   100  			return i
   101  		}
   102  	}
   103  	return v.BitLen()
   104  }
   105  
   106  // PaddedBigBytes encodes a big integer as a big-endian byte slice. The length
   107  // of the slice is at least n bytes.
   108  func PaddedBigBytes(bigint *big.Int, n int) []byte {
   109  	if bigint.BitLen()/8 >= n {
   110  		return bigint.Bytes()
   111  	}
   112  	ret := make([]byte, n)
   113  	ReadBits(bigint, ret)
   114  	return ret
   115  }
   116  
   117  // bigEndianByteAt returns the byte at position n,
   118  // in Big-Endian encoding
   119  // So n==0 returns the least significant byte
   120  func bigEndianByteAt(bigint *big.Int, n int) byte {
   121  	words := bigint.Bits()
   122  	// Check word-bucket the byte will reside in
   123  	i := n / wordBytes
   124  	if i >= len(words) {
   125  		return byte(0)
   126  	}
   127  	word := words[i]
   128  	// Offset of the byte
   129  	shift := 8 * uint(n%wordBytes)
   130  
   131  	return byte(word >> shift)
   132  }
   133  
   134  // Byte returns the byte at position n,
   135  // with the supplied padlength in Little-Endian encoding.
   136  // n==0 returns the MSB
   137  // Example: bigint '5', padlength 32, n=31 => 5
   138  func Byte(bigint *big.Int, padlength, n int) byte {
   139  	if n >= padlength {
   140  		return byte(0)
   141  	}
   142  	return bigEndianByteAt(bigint, padlength-1-n)
   143  }
   144  
   145  // ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure
   146  // that buf has enough space. If buf is too short the result will be incomplete.
   147  func ReadBits(bigint *big.Int, buf []byte) {
   148  	i := len(buf)
   149  	for _, d := range bigint.Bits() {
   150  		for j := 0; j < wordBytes && i > 0; j++ {
   151  			i--
   152  			buf[i] = byte(d)
   153  			d >>= 8
   154  		}
   155  	}
   156  }
   157  
   158  // U256 encodes as a 256 bit two's complement number. This operation is destructive.
   159  func U256(x *big.Int) *big.Int {
   160  	return x.And(x, tt256m1)
   161  }
   162  
   163  // S256 interprets x as a two's complement number.
   164  // x must not exceed 256 bits (the result is undefined if it does) and is not modified.
   165  //
   166  //   S256(0)        = 0
   167  //   S256(1)        = 1
   168  //   S256(2**255)   = -2**255
   169  //   S256(2**256-1) = -1
   170  func S256(x *big.Int) *big.Int {
   171  	if x.Cmp(tt255) < 0 {
   172  		return x
   173  	} else {
   174  		return new(big.Int).Sub(x, tt256)
   175  	}
   176  }
   177  
   178  // Exp implements exponentiation by squaring.
   179  // Exp returns a newly-allocated big integer and does not change
   180  // base or exponent. The result is truncated to 256 bits.
   181  //
   182  // Courtesy @karalabe and @chfast
   183  func Exp(base, exponent *big.Int) *big.Int {
   184  	result := big.NewInt(1)
   185  
   186  	for _, word := range exponent.Bits() {
   187  		for i := 0; i < wordBits; i++ {
   188  			if word&1 == 1 {
   189  				U256(result.Mul(result, base))
   190  			}
   191  			U256(base.Mul(base, base))
   192  			word >>= 1
   193  		}
   194  	}
   195  	return result
   196  }