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