github.com/klaytn/klaytn@v1.12.1/common/math/big.go (about)

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