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