big.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. // Decimal256 unmarshals big.Int as a decimal string. When unmarshalling,
  62. // it however accepts either "0x"-prefixed (hex encoded) or non-prefixed (decimal)
  63. type Decimal256 big.Int
  64. // NewHexOrDecimal256 creates a new Decimal256
  65. func NewDecimal256(x int64) *Decimal256 {
  66. b := big.NewInt(x)
  67. d := Decimal256(*b)
  68. return &d
  69. }
  70. // UnmarshalText implements encoding.TextUnmarshaler.
  71. func (i *Decimal256) UnmarshalText(input []byte) error {
  72. bigint, ok := ParseBig256(string(input))
  73. if !ok {
  74. return fmt.Errorf("invalid hex or decimal integer %q", input)
  75. }
  76. *i = Decimal256(*bigint)
  77. return nil
  78. }
  79. // MarshalText implements encoding.TextMarshaler.
  80. func (i *Decimal256) MarshalText() ([]byte, error) {
  81. return []byte(i.String()), nil
  82. }
  83. // String implements Stringer.
  84. func (i *Decimal256) String() string {
  85. if i == nil {
  86. return "0"
  87. }
  88. return fmt.Sprintf("%#d", (*big.Int)(i))
  89. }
  90. // ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax.
  91. // Leading zeros are accepted. The empty string parses as zero.
  92. func ParseBig256(s string) (*big.Int, bool) {
  93. if s == "" {
  94. return new(big.Int), true
  95. }
  96. var bigint *big.Int
  97. var ok bool
  98. if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") {
  99. bigint, ok = new(big.Int).SetString(s[2:], 16)
  100. } else {
  101. bigint, ok = new(big.Int).SetString(s, 10)
  102. }
  103. if ok && bigint.BitLen() > 256 {
  104. bigint, ok = nil, false
  105. }
  106. return bigint, ok
  107. }
  108. // MustParseBig256 parses s as a 256 bit big integer and panics if the string is invalid.
  109. func MustParseBig256(s string) *big.Int {
  110. v, ok := ParseBig256(s)
  111. if !ok {
  112. panic("invalid 256 bit integer: " + s)
  113. }
  114. return v
  115. }
  116. // BigPow returns a ** b as a big integer.
  117. func BigPow(a, b int64) *big.Int {
  118. r := big.NewInt(a)
  119. return r.Exp(r, big.NewInt(b), nil)
  120. }
  121. // BigMax returns the larger of x or y.
  122. func BigMax(x, y *big.Int) *big.Int {
  123. if x.Cmp(y) < 0 {
  124. return y
  125. }
  126. return x
  127. }
  128. // BigMin returns the smaller of x or y.
  129. func BigMin(x, y *big.Int) *big.Int {
  130. if x.Cmp(y) > 0 {
  131. return y
  132. }
  133. return x
  134. }
  135. // FirstBitSet returns the index of the first 1 bit in v, counting from LSB.
  136. func FirstBitSet(v *big.Int) int {
  137. for i := 0; i < v.BitLen(); i++ {
  138. if v.Bit(i) > 0 {
  139. return i
  140. }
  141. }
  142. return v.BitLen()
  143. }
  144. // PaddedBigBytes encodes a big integer as a big-endian byte slice. The length
  145. // of the slice is at least n bytes.
  146. func PaddedBigBytes(bigint *big.Int, n int) []byte {
  147. if bigint.BitLen()/8 >= n {
  148. return bigint.Bytes()
  149. }
  150. ret := make([]byte, n)
  151. ReadBits(bigint, ret)
  152. return ret
  153. }
  154. // bigEndianByteAt returns the byte at position n,
  155. // in Big-Endian encoding
  156. // So n==0 returns the least significant byte
  157. func bigEndianByteAt(bigint *big.Int, n int) byte {
  158. words := bigint.Bits()
  159. // Check word-bucket the byte will reside in
  160. i := n / wordBytes
  161. if i >= len(words) {
  162. return byte(0)
  163. }
  164. word := words[i]
  165. // Offset of the byte
  166. shift := 8 * uint(n%wordBytes)
  167. return byte(word >> shift)
  168. }
  169. // Byte returns the byte at position n,
  170. // with the supplied padlength in Little-Endian encoding.
  171. // n==0 returns the MSB
  172. // Example: bigint '5', padlength 32, n=31 => 5
  173. func Byte(bigint *big.Int, padlength, n int) byte {
  174. if n >= padlength {
  175. return byte(0)
  176. }
  177. return bigEndianByteAt(bigint, padlength-1-n)
  178. }
  179. // ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure
  180. // that buf has enough space. If buf is too short the result will be incomplete.
  181. func ReadBits(bigint *big.Int, buf []byte) {
  182. i := len(buf)
  183. for _, d := range bigint.Bits() {
  184. for j := 0; j < wordBytes && i > 0; j++ {
  185. i--
  186. buf[i] = byte(d)
  187. d >>= 8
  188. }
  189. }
  190. }
  191. // U256 encodes as a 256 bit two's complement number. This operation is destructive.
  192. func U256(x *big.Int) *big.Int {
  193. return x.And(x, tt256m1)
  194. }
  195. // U256Bytes converts a big Int into a 256bit EVM number.
  196. // This operation is destructive.
  197. func U256Bytes(n *big.Int) []byte {
  198. return PaddedBigBytes(U256(n), 32)
  199. }
  200. // S256 interprets x as a two's complement number.
  201. // x must not exceed 256 bits (the result is undefined if it does) and is not modified.
  202. //
  203. // S256(0) = 0
  204. // S256(1) = 1
  205. // S256(2**255) = -2**255
  206. // S256(2**256-1) = -1
  207. func S256(x *big.Int) *big.Int {
  208. if x.Cmp(tt255) < 0 {
  209. return x
  210. }
  211. return new(big.Int).Sub(x, tt256)
  212. }
  213. // Exp implements exponentiation by squaring.
  214. // Exp returns a newly-allocated big integer and does not change
  215. // base or exponent. The result is truncated to 256 bits.
  216. //
  217. // Courtesy @karalabe and @chfast
  218. func Exp(base, exponent *big.Int) *big.Int {
  219. result := big.NewInt(1)
  220. for _, word := range exponent.Bits() {
  221. for i := 0; i < wordBits; i++ {
  222. if word&1 == 1 {
  223. U256(result.Mul(result, base))
  224. }
  225. U256(base.Mul(base, base))
  226. word >>= 1
  227. }
  228. }
  229. return result
  230. }