contracts.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright 2014 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 vm
  17. import (
  18. "crypto/sha256"
  19. "errors"
  20. "math/big"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/math"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/crypto/bn256"
  25. "github.com/ethereum/go-ethereum/params"
  26. "golang.org/x/crypto/ripemd160"
  27. )
  28. // PrecompiledContract is the basic interface for native Go contracts. The implementation
  29. // requires a deterministic gas count based on the input size of the Run method of the
  30. // contract.
  31. type PrecompiledContract interface {
  32. RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use
  33. Run(input []byte) ([]byte, error) // Run runs the precompiled contract
  34. }
  35. // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum
  36. // contracts used in the Frontier and Homestead releases.
  37. var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{
  38. common.BytesToAddress([]byte{1}): &ecrecover{},
  39. common.BytesToAddress([]byte{2}): &sha256hash{},
  40. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  41. common.BytesToAddress([]byte{4}): &dataCopy{},
  42. }
  43. // PrecompiledContractsMetropolis contains the default set of pre-compiled Ethereum
  44. // contracts used in the Metropolis release.
  45. var PrecompiledContractsMetropolis = map[common.Address]PrecompiledContract{
  46. common.BytesToAddress([]byte{1}): &ecrecover{},
  47. common.BytesToAddress([]byte{2}): &sha256hash{},
  48. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  49. common.BytesToAddress([]byte{4}): &dataCopy{},
  50. common.BytesToAddress([]byte{5}): &bigModExp{},
  51. common.BytesToAddress([]byte{6}): &bn256Add{},
  52. common.BytesToAddress([]byte{7}): &bn256ScalarMul{},
  53. common.BytesToAddress([]byte{8}): &bn256Pairing{},
  54. }
  55. // RunPrecompiledContract runs and evaluates the output of a precompiled contract.
  56. func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) {
  57. gas := p.RequiredGas(input)
  58. if contract.UseGas(gas) {
  59. return p.Run(input)
  60. }
  61. return nil, ErrOutOfGas
  62. }
  63. // ECRECOVER implemented as a native contract.
  64. type ecrecover struct{}
  65. func (c *ecrecover) RequiredGas(input []byte) uint64 {
  66. return params.EcrecoverGas
  67. }
  68. func (c *ecrecover) Run(input []byte) ([]byte, error) {
  69. const ecRecoverInputLength = 128
  70. input = common.RightPadBytes(input, ecRecoverInputLength)
  71. // "input" is (hash, v, r, s), each 32 bytes
  72. // but for ecrecover we want (r, s, v)
  73. r := new(big.Int).SetBytes(input[64:96])
  74. s := new(big.Int).SetBytes(input[96:128])
  75. v := input[63] - 27
  76. // tighter sig s values input homestead only apply to tx sigs
  77. if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
  78. return nil, nil
  79. }
  80. // v needs to be at the end for libsecp256k1
  81. pubKey, err := crypto.Ecrecover(input[:32], append(input[64:128], v))
  82. // make sure the public key is a valid one
  83. if err != nil {
  84. return nil, nil
  85. }
  86. // the first byte of pubkey is bitcoin heritage
  87. return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil
  88. }
  89. // SHA256 implemented as a native contract.
  90. type sha256hash struct{}
  91. // RequiredGas returns the gas required to execute the pre-compiled contract.
  92. //
  93. // This method does not require any overflow checking as the input size gas costs
  94. // required for anything significant is so high it's impossible to pay for.
  95. func (c *sha256hash) RequiredGas(input []byte) uint64 {
  96. return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
  97. }
  98. func (c *sha256hash) Run(input []byte) ([]byte, error) {
  99. h := sha256.Sum256(input)
  100. return h[:], nil
  101. }
  102. // RIPMED160 implemented as a native contract.
  103. type ripemd160hash struct{}
  104. // RequiredGas returns the gas required to execute the pre-compiled contract.
  105. //
  106. // This method does not require any overflow checking as the input size gas costs
  107. // required for anything significant is so high it's impossible to pay for.
  108. func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
  109. return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas
  110. }
  111. func (c *ripemd160hash) Run(input []byte) ([]byte, error) {
  112. ripemd := ripemd160.New()
  113. ripemd.Write(input)
  114. return common.LeftPadBytes(ripemd.Sum(nil), 32), nil
  115. }
  116. // data copy implemented as a native contract.
  117. type dataCopy struct{}
  118. // RequiredGas returns the gas required to execute the pre-compiled contract.
  119. //
  120. // This method does not require any overflow checking as the input size gas costs
  121. // required for anything significant is so high it's impossible to pay for.
  122. func (c *dataCopy) RequiredGas(input []byte) uint64 {
  123. return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
  124. }
  125. func (c *dataCopy) Run(in []byte) ([]byte, error) {
  126. return in, nil
  127. }
  128. // bigModExp implements a native big integer exponential modular operation.
  129. type bigModExp struct{}
  130. var (
  131. big1 = big.NewInt(1)
  132. big4 = big.NewInt(4)
  133. big8 = big.NewInt(8)
  134. big16 = big.NewInt(16)
  135. big32 = big.NewInt(32)
  136. big64 = big.NewInt(64)
  137. big96 = big.NewInt(96)
  138. big480 = big.NewInt(480)
  139. big1024 = big.NewInt(1024)
  140. big3072 = big.NewInt(3072)
  141. big199680 = big.NewInt(199680)
  142. )
  143. // RequiredGas returns the gas required to execute the pre-compiled contract.
  144. func (c *bigModExp) RequiredGas(input []byte) uint64 {
  145. var (
  146. baseLen = new(big.Int).SetBytes(getData(input, 0, 32))
  147. expLen = new(big.Int).SetBytes(getData(input, 32, 32))
  148. modLen = new(big.Int).SetBytes(getData(input, 64, 32))
  149. )
  150. if len(input) > 96 {
  151. input = input[96:]
  152. } else {
  153. input = input[:0]
  154. }
  155. // Retrieve the head 32 bytes of exp for the adjusted exponent length
  156. var expHead *big.Int
  157. if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
  158. expHead = new(big.Int)
  159. } else {
  160. if expLen.Cmp(big32) > 0 {
  161. expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32))
  162. } else {
  163. expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64()))
  164. }
  165. }
  166. // Calculate the adjusted exponent length
  167. var msb int
  168. if bitlen := expHead.BitLen(); bitlen > 0 {
  169. msb = bitlen - 1
  170. }
  171. adjExpLen := new(big.Int)
  172. if expLen.Cmp(big32) > 0 {
  173. adjExpLen.Sub(expLen, big32)
  174. adjExpLen.Mul(big8, adjExpLen)
  175. }
  176. adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
  177. // Calculate the gas cost of the operation
  178. gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
  179. switch {
  180. case gas.Cmp(big64) <= 0:
  181. gas.Mul(gas, gas)
  182. case gas.Cmp(big1024) <= 0:
  183. gas = new(big.Int).Add(
  184. new(big.Int).Div(new(big.Int).Mul(gas, gas), big4),
  185. new(big.Int).Sub(new(big.Int).Mul(big96, gas), big3072),
  186. )
  187. default:
  188. gas = new(big.Int).Add(
  189. new(big.Int).Div(new(big.Int).Mul(gas, gas), big16),
  190. new(big.Int).Sub(new(big.Int).Mul(big480, gas), big199680),
  191. )
  192. }
  193. gas.Mul(gas, math.BigMax(adjExpLen, big1))
  194. gas.Div(gas, new(big.Int).SetUint64(params.ModExpQuadCoeffDiv))
  195. if gas.BitLen() > 64 {
  196. return math.MaxUint64
  197. }
  198. return gas.Uint64()
  199. }
  200. func (c *bigModExp) Run(input []byte) ([]byte, error) {
  201. var (
  202. baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64()
  203. expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64()
  204. modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64()
  205. )
  206. if len(input) > 96 {
  207. input = input[96:]
  208. } else {
  209. input = input[:0]
  210. }
  211. // Handle a special case when both the base and mod length is zero
  212. if baseLen == 0 && modLen == 0 {
  213. return []byte{}, nil
  214. }
  215. // Retrieve the operands and execute the exponentiation
  216. var (
  217. base = new(big.Int).SetBytes(getData(input, 0, baseLen))
  218. exp = new(big.Int).SetBytes(getData(input, baseLen, expLen))
  219. mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
  220. )
  221. if mod.BitLen() == 0 {
  222. // Modulo 0 is undefined, return zero
  223. return common.LeftPadBytes([]byte{}, int(modLen)), nil
  224. }
  225. return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
  226. }
  227. var (
  228. // errNotOnCurve is returned if a point being unmarshalled as a bn256 elliptic
  229. // curve point is not on the curve.
  230. errNotOnCurve = errors.New("point not on elliptic curve")
  231. // errInvalidCurvePoint is returned if a point being unmarshalled as a bn256
  232. // elliptic curve point is invalid.
  233. errInvalidCurvePoint = errors.New("invalid elliptic curve point")
  234. )
  235. // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
  236. // returning it, or an error if the point is invalid.
  237. func newCurvePoint(blob []byte) (*bn256.G1, error) {
  238. p, onCurve := new(bn256.G1).Unmarshal(blob)
  239. if !onCurve {
  240. return nil, errNotOnCurve
  241. }
  242. gx, gy, _, _ := p.CurvePoints()
  243. if gx.Cmp(bn256.P) >= 0 || gy.Cmp(bn256.P) >= 0 {
  244. return nil, errInvalidCurvePoint
  245. }
  246. return p, nil
  247. }
  248. // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
  249. // returning it, or an error if the point is invalid.
  250. func newTwistPoint(blob []byte) (*bn256.G2, error) {
  251. p, onCurve := new(bn256.G2).Unmarshal(blob)
  252. if !onCurve {
  253. return nil, errNotOnCurve
  254. }
  255. x2, y2, _, _ := p.CurvePoints()
  256. if x2.Real().Cmp(bn256.P) >= 0 || x2.Imag().Cmp(bn256.P) >= 0 ||
  257. y2.Real().Cmp(bn256.P) >= 0 || y2.Imag().Cmp(bn256.P) >= 0 {
  258. return nil, errInvalidCurvePoint
  259. }
  260. return p, nil
  261. }
  262. // bn256Add implements a native elliptic curve point addition.
  263. type bn256Add struct{}
  264. // RequiredGas returns the gas required to execute the pre-compiled contract.
  265. func (c *bn256Add) RequiredGas(input []byte) uint64 {
  266. return params.Bn256AddGas
  267. }
  268. func (c *bn256Add) Run(input []byte) ([]byte, error) {
  269. x, err := newCurvePoint(getData(input, 0, 64))
  270. if err != nil {
  271. return nil, err
  272. }
  273. y, err := newCurvePoint(getData(input, 64, 64))
  274. if err != nil {
  275. return nil, err
  276. }
  277. x.Add(x, y)
  278. return x.Marshal(), nil
  279. }
  280. // bn256ScalarMul implements a native elliptic curve scalar multiplication.
  281. type bn256ScalarMul struct{}
  282. // RequiredGas returns the gas required to execute the pre-compiled contract.
  283. func (c *bn256ScalarMul) RequiredGas(input []byte) uint64 {
  284. return params.Bn256ScalarMulGas
  285. }
  286. func (c *bn256ScalarMul) Run(input []byte) ([]byte, error) {
  287. p, err := newCurvePoint(getData(input, 0, 64))
  288. if err != nil {
  289. return nil, err
  290. }
  291. p.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32)))
  292. return p.Marshal(), nil
  293. }
  294. var (
  295. // true32Byte is returned if the bn256 pairing check succeeds.
  296. true32Byte = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
  297. // false32Byte is returned if the bn256 pairing check fails.
  298. false32Byte = make([]byte, 32)
  299. // errBadPairingInput is returned if the bn256 pairing input is invalid.
  300. errBadPairingInput = errors.New("bad elliptic curve pairing size")
  301. )
  302. // bn256Pairing implements a pairing pre-compile for the bn256 curve
  303. type bn256Pairing struct{}
  304. // RequiredGas returns the gas required to execute the pre-compiled contract.
  305. func (c *bn256Pairing) RequiredGas(input []byte) uint64 {
  306. return params.Bn256PairingBaseGas + uint64(len(input)/192)*params.Bn256PairingPerPointGas
  307. }
  308. func (c *bn256Pairing) Run(input []byte) ([]byte, error) {
  309. // Handle some corner cases cheaply
  310. if len(input)%192 > 0 {
  311. return nil, errBadPairingInput
  312. }
  313. // Convert the input into a set of coordinates
  314. var (
  315. cs []*bn256.G1
  316. ts []*bn256.G2
  317. )
  318. for i := 0; i < len(input); i += 192 {
  319. c, err := newCurvePoint(input[i : i+64])
  320. if err != nil {
  321. return nil, err
  322. }
  323. t, err := newTwistPoint(input[i+64 : i+192])
  324. if err != nil {
  325. return nil, err
  326. }
  327. cs = append(cs, c)
  328. ts = append(ts, t)
  329. }
  330. // Execute the pairing checks and return the results
  331. ok := bn256.PairingCheck(cs, ts)
  332. if ok {
  333. return true32Byte, nil
  334. }
  335. return false32Byte, nil
  336. }