big.go 5.4 KB

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