github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/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 var ( 26 tt255 = BigPow(2, 255) 27 tt256 = BigPow(2, 256) 28 tt256m1 = new(big.Int).Sub(tt256, big.NewInt(1)) 29 MaxBig256 = new(big.Int).Set(tt256m1) 30 ) 31 32 const ( 33 // number of bits in a big.Word 34 wordBits = 32 << (uint64(^big.Word(0)) >> 63) 35 // number of bytes in a big.Word 36 wordBytes = wordBits / 8 37 ) 38 39 // HexOrDecimal256 marshals big.Int as hex or decimal. 40 type HexOrDecimal256 big.Int 41 42 // UnmarshalText implements encoding.TextUnmarshaler. 43 func (i *HexOrDecimal256) UnmarshalText(input []byte) error { 44 bigint, ok := ParseBig256(string(input)) 45 if !ok { 46 return fmt.Errorf("invalid hex or decimal integer %q", input) 47 } 48 *i = HexOrDecimal256(*bigint) 49 return nil 50 } 51 52 // MarshalText implements encoding.TextMarshaler. 53 func (i *HexOrDecimal256) MarshalText() ([]byte, error) { 54 return []byte(fmt.Sprintf("%#x", (*big.Int)(i))), nil 55 } 56 57 // ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax. 58 // Leading zeros are accepted. The empty string parses as zero. 59 func ParseBig256(s string) (*big.Int, bool) { 60 if s == "" { 61 return new(big.Int), true 62 } 63 var bigint *big.Int 64 var ok bool 65 if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") { 66 bigint, ok = new(big.Int).SetString(s[2:], 16) 67 } else { 68 bigint, ok = new(big.Int).SetString(s, 10) 69 } 70 if ok && bigint.BitLen() > 256 { 71 bigint, ok = nil, false 72 } 73 return bigint, ok 74 } 75 76 // MustParseBig parses s as a 256 bit big integer and panics if the string is invalid. 77 func MustParseBig256(s string) *big.Int { 78 v, ok := ParseBig256(s) 79 if !ok { 80 panic("invalid 256 bit integer: " + s) 81 } 82 return v 83 } 84 85 // BigPow returns a ** b as a big integer. 86 func BigPow(a, b int64) *big.Int { 87 r := big.NewInt(a) 88 return r.Exp(r, big.NewInt(b), nil) 89 } 90 91 // BigMax returns the larger of x or y. 92 func BigMax(x, y *big.Int) *big.Int { 93 if x.Cmp(y) < 0 { 94 return y 95 } 96 return x 97 } 98 99 // BigMin returns the smaller of x or y. 100 func BigMin(x, y *big.Int) *big.Int { 101 if x.Cmp(y) > 0 { 102 return y 103 } 104 return x 105 } 106 107 // FirstBitSet returns the index of the first 1 bit in v, counting from LSB. 108 func FirstBitSet(v *big.Int) int { 109 for i := 0; i < v.BitLen(); i++ { 110 if v.Bit(i) > 0 { 111 return i 112 } 113 } 114 return v.BitLen() 115 } 116 117 // PaddedBigBytes encodes a big integer as a big-endian byte slice. The length 118 // of the slice is at least n bytes. 119 func PaddedBigBytes(bigint *big.Int, n int) []byte { 120 if bigint.BitLen()/8 >= n { 121 return bigint.Bytes() 122 } 123 ret := make([]byte, n) 124 ReadBits(bigint, ret) 125 return ret 126 } 127 128 // ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure 129 // that buf has enough space. If buf is too short the result will be incomplete. 130 func ReadBits(bigint *big.Int, buf []byte) { 131 i := len(buf) 132 for _, d := range bigint.Bits() { 133 for j := 0; j < wordBytes && i > 0; j++ { 134 i-- 135 buf[i] = byte(d) 136 d >>= 8 137 } 138 } 139 } 140 141 // U256 encodes as a 256 bit two's complement number. This operation is destructive. 142 func U256(x *big.Int) *big.Int { 143 return x.And(x, tt256m1) 144 } 145 146 // S256 interprets x as a two's complement number. 147 // x must not exceed 256 bits (the result is undefined if it does) and is not modified. 148 // 149 // S256(0) = 0 150 // S256(1) = 1 151 // S256(2**255) = -2**255 152 // S256(2**256-1) = -1 153 func S256(x *big.Int) *big.Int { 154 if x.Cmp(tt255) < 0 { 155 return x 156 } else { 157 return new(big.Int).Sub(x, tt256) 158 } 159 } 160 161 // Exp implements exponentiation by squaring. 162 // Exp returns a newly-allocated big integer and does not change 163 // base or exponent. The result is truncated to 256 bits. 164 // 165 // Courtesy @karalabe and @chfast 166 func Exp(base, exponent *big.Int) *big.Int { 167 result := big.NewInt(1) 168 169 for _, word := range exponent.Bits() { 170 for i := 0; i < wordBits; i++ { 171 if word&1 == 1 { 172 U256(result.Mul(result, base)) 173 } 174 U256(base.Mul(base, base)) 175 word >>= 1 176 } 177 } 178 return result 179 }