big.go 5.6 KB

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