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