github.com/xfond/eth-implementation@v1.8.9-0.20180514135602-f6bc65fc6811/common/math/big.go (about)

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