big.go 4.6 KB

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