github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/common/math/big.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 // Package math provides integer math utilities. 19 package math 20 21 import ( 22 "fmt" 23 "math/big" 24 ) 25 26 // Various big integer limit values. 27 var ( 28 tt255 = BigPow(2, 255) 29 tt256 = BigPow(2, 256) 30 tt256m1 = new(big.Int).Sub(tt256, big.NewInt(1)) 31 tt63 = BigPow(2, 63) 32 MaxBig256 = new(big.Int).Set(tt256m1) 33 MaxBig63 = new(big.Int).Sub(tt63, big.NewInt(1)) 34 ) 35 36 const ( 37 // number of bits in a big.Word 38 wordBits = 32 << (uint64(^big.Word(0)) >> 63) 39 // number of bytes in a big.Word 40 wordBytes = wordBits / 8 41 ) 42 43 // HexOrDecimal256 marshals big.Int as hex or decimal. 44 type HexOrDecimal256 big.Int 45 46 // NewHexOrDecimal256 creates a new HexOrDecimal256 47 func NewHexOrDecimal256(x int64) *HexOrDecimal256 { 48 b := big.NewInt(x) 49 h := HexOrDecimal256(*b) 50 return &h 51 } 52 53 // UnmarshalText implements encoding.TextUnmarshaler. 54 func (i *HexOrDecimal256) UnmarshalText(input []byte) error { 55 bigint, ok := ParseBig256(string(input)) 56 if !ok { 57 return fmt.Errorf("invalid hex or decimal integer %q", input) 58 } 59 *i = HexOrDecimal256(*bigint) 60 return nil 61 } 62 63 // MarshalText implements encoding.TextMarshaler. 64 func (i *HexOrDecimal256) MarshalText() ([]byte, error) { 65 if i == nil { 66 return []byte("0x0"), nil 67 } 68 return []byte(fmt.Sprintf("%#x", (*big.Int)(i))), nil 69 } 70 71 // ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax. 72 // Leading zeros are accepted. The empty string parses as zero. 73 func ParseBig256(s string) (*big.Int, bool) { 74 if s == "" { 75 return new(big.Int), true 76 } 77 var bigint *big.Int 78 var ok bool 79 if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") { 80 bigint, ok = new(big.Int).SetString(s[2:], 16) 81 } else { 82 bigint, ok = new(big.Int).SetString(s, 10) 83 } 84 if ok && bigint.BitLen() > 256 { 85 bigint, ok = nil, false 86 } 87 return bigint, ok 88 } 89 90 // MustParseBig256 parses s as a 256 bit big integer and panics if the string is invalid. 91 func MustParseBig256(s string) *big.Int { 92 v, ok := ParseBig256(s) 93 if !ok { 94 panic("invalid 256 bit integer: " + s) 95 } 96 return v 97 } 98 99 // BigPow returns a ** b as a big integer. 100 func BigPow(a, b int64) *big.Int { 101 r := big.NewInt(a) 102 return r.Exp(r, big.NewInt(b), nil) 103 } 104 105 // BigMax returns the larger of x or y. 106 func BigMax(x, y *big.Int) *big.Int { 107 if x.Cmp(y) < 0 { 108 return y 109 } 110 return x 111 } 112 113 // BigMin returns the smaller of x or y. 114 func BigMin(x, y *big.Int) *big.Int { 115 if x.Cmp(y) > 0 { 116 return y 117 } 118 return x 119 } 120 121 // FirstBitSet returns the index of the first 1 bit in v, counting from LSB. 122 func FirstBitSet(v *big.Int) int { 123 for i := 0; i < v.BitLen(); i++ { 124 if v.Bit(i) > 0 { 125 return i 126 } 127 } 128 return v.BitLen() 129 } 130 131 // PaddedBigBytes encodes a big integer as a big-endian byte slice. The length 132 // of the slice is at least n bytes. 133 func PaddedBigBytes(bigint *big.Int, n int) []byte { 134 if bigint.BitLen()/8 >= n { 135 return bigint.Bytes() 136 } 137 ret := make([]byte, n) 138 ReadBits(bigint, ret) 139 return ret 140 } 141 142 // bigEndianByteAt returns the byte at position n, 143 // in Big-Endian encoding 144 // So n==0 returns the least significant byte 145 func bigEndianByteAt(bigint *big.Int, n int) byte { 146 words := bigint.Bits() 147 // Check word-bucket the byte will reside in 148 i := n / wordBytes 149 if i >= len(words) { 150 return byte(0) 151 } 152 word := words[i] 153 // Offset of the byte 154 shift := 8 * uint(n%wordBytes) 155 156 return byte(word >> shift) 157 } 158 159 // Byte returns the byte at position n, 160 // with the supplied padlength in Little-Endian encoding. 161 // n==0 returns the MSB 162 // Example: bigint '5', padlength 32, n=31 => 5 163 func Byte(bigint *big.Int, padlength, n int) byte { 164 if n >= padlength { 165 return byte(0) 166 } 167 return bigEndianByteAt(bigint, padlength-1-n) 168 } 169 170 // ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure 171 // that buf has enough space. If buf is too short the result will be incomplete. 172 func ReadBits(bigint *big.Int, buf []byte) { 173 i := len(buf) 174 for _, d := range bigint.Bits() { 175 for j := 0; j < wordBytes && i > 0; j++ { 176 i-- 177 buf[i] = byte(d) 178 d >>= 8 179 } 180 } 181 } 182 183 // U256 encodes as a 256 bit two's complement number. This operation is destructive. 184 func U256(x *big.Int) *big.Int { 185 return x.And(x, tt256m1) 186 } 187 188 // S256 interprets x as a two's complement number. 189 // x must not exceed 256 bits (the result is undefined if it does) and is not modified. 190 // 191 // S256(0) = 0 192 // S256(1) = 1 193 // S256(2**255) = -2**255 194 // S256(2**256-1) = -1 195 func S256(x *big.Int) *big.Int { 196 if x.Cmp(tt255) < 0 { 197 return x 198 } 199 return new(big.Int).Sub(x, tt256) 200 } 201 202 // Exp implements exponentiation by squaring. 203 // Exp returns a newly-allocated big integer and does not change 204 // base or exponent. The result is truncated to 256 bits. 205 // 206 // Courtesy @karalabe and @chfast 207 func Exp(base, exponent *big.Int) *big.Int { 208 result := big.NewInt(1) 209 210 for _, word := range exponent.Bits() { 211 for i := 0; i < wordBits; i++ { 212 if word&1 == 1 { 213 U256(result.Mul(result, base)) 214 } 215 U256(base.Mul(base, base)) 216 word >>= 1 217 } 218 } 219 return result 220 }