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