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