github.com/amazechain/amc@v0.1.3/common/math/big.go (about) 1 // Copyright 2023 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain 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 AmazeChain 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 AmazeChain 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 return r.Exp(r, big.NewInt(b), nil) 138 } 139 140 // BigMax returns the larger of x or y. 141 func BigMax(x, y *big.Int) *big.Int { 142 if x.Cmp(y) < 0 { 143 return y 144 } 145 return x 146 } 147 148 // BigMin returns the smaller of x or y. 149 func BigMin(x, y *big.Int) *big.Int { 150 if x.Cmp(y) > 0 { 151 return y 152 } 153 return x 154 } 155 156 // U256Min returns the smaller of x or y. 157 func U256Min(x, y *uint256.Int) *uint256.Int { 158 if x.Cmp(y) > 0 { 159 return y 160 } 161 return x 162 } 163 164 // Min256 returns the smaller of x or y. 165 func Min256(x, y *uint256.Int) *uint256.Int { 166 if x.Cmp(y) > 0 { 167 return y 168 } 169 return x 170 } 171 172 // FirstBitSet returns the index of the first 1 bit in v, counting from LSB. 173 func FirstBitSet(v *big.Int) int { 174 for i := 0; i < v.BitLen(); i++ { 175 if v.Bit(i) > 0 { 176 return i 177 } 178 } 179 return v.BitLen() 180 } 181 182 // PaddedBigBytes encodes a big integer as a big-endian byte slice. The length 183 // of the slice is at least n bytes. 184 func PaddedBigBytes(bigint *big.Int, n int) []byte { 185 if bigint.BitLen()/8 >= n { 186 return bigint.Bytes() 187 } 188 ret := make([]byte, n) 189 ReadBits(bigint, ret) 190 return ret 191 } 192 193 // bigEndianByteAt returns the byte at position n, 194 // in Big-Endian encoding 195 // So n==0 returns the least significant byte 196 func bigEndianByteAt(bigint *big.Int, n int) byte { 197 words := bigint.Bits() 198 // Check word-bucket the byte will reside in 199 i := n / wordBytes 200 if i >= len(words) { 201 return byte(0) 202 } 203 word := words[i] 204 // Offset of the byte 205 shift := 8 * uint(n%wordBytes) 206 207 return byte(word >> shift) 208 } 209 210 // Byte returns the byte at position n, 211 // with the supplied padlength in Little-Endian encoding. 212 // n==0 returns the MSB 213 // Example: bigint '5', padlength 32, n=31 => 5 214 func Byte(bigint *big.Int, padlength, n int) byte { 215 if n >= padlength { 216 return byte(0) 217 } 218 return bigEndianByteAt(bigint, padlength-1-n) 219 } 220 221 // ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure 222 // that buf has enough space. If buf is too short the result will be incomplete. 223 func ReadBits(bigint *big.Int, buf []byte) { 224 i := len(buf) 225 for _, d := range bigint.Bits() { 226 for j := 0; j < wordBytes && i > 0; j++ { 227 i-- 228 buf[i] = byte(d) 229 d >>= 8 230 } 231 } 232 } 233 234 // U256 encodes as a 256 bit two's complement number. This operation is destructive. 235 func U256(x *big.Int) *big.Int { 236 return x.And(x, tt256m1) 237 } 238 239 // U256Bytes converts a big Int into a 256bit EVM number. 240 // This operation is destructive. 241 func U256Bytes(n *big.Int) []byte { 242 return PaddedBigBytes(U256(n), 32) 243 } 244 245 // S256 interprets x as a two's complement number. 246 // x must not exceed 256 bits (the result is undefined if it does) and is not modified. 247 // 248 // S256(0) = 0 249 // S256(1) = 1 250 // S256(2**255) = -2**255 251 // S256(2**256-1) = -1 252 func S256(x *big.Int) *big.Int { 253 if x.Cmp(tt255) < 0 { 254 return x 255 } 256 return new(big.Int).Sub(x, tt256) 257 } 258 259 // Exp implements exponentiation by squaring. 260 // Exp returns a newly-allocated big integer and does not change 261 // base or exponent. The result is truncated to 256 bits. 262 // 263 // Courtesy @karalabe and @chfast 264 func Exp(base, exponent *big.Int) *big.Int { 265 result := big.NewInt(1) 266 267 for _, word := range exponent.Bits() { 268 for i := 0; i < wordBits; i++ { 269 if word&1 == 1 { 270 U256(result.Mul(result, base)) 271 } 272 U256(base.Mul(base, base)) 273 word >>= 1 274 } 275 } 276 return result 277 }