big.go 4.6 KB

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