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