contracts.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. // RequiredGas returns the gas required to execute the pre-compiled contract.
  131. func (c *bigModExp) RequiredGas(input []byte) uint64 {
  132. // Pad the input with zeroes to the minimum size to read the field lengths
  133. input = common.RightPadBytes(input, 96)
  134. var (
  135. baseLen = new(big.Int).SetBytes(input[:32])
  136. expLen = new(big.Int).SetBytes(input[32:64])
  137. modLen = new(big.Int).SetBytes(input[64:96])
  138. )
  139. input = input[96:]
  140. // Retrieve the head 32 bytes of exp for the adjusted exponent length
  141. var expHead *big.Int
  142. if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
  143. expHead = new(big.Int)
  144. } else {
  145. offset := int(baseLen.Uint64())
  146. input = common.RightPadBytes(input, offset+32)
  147. if expLen.Cmp(big.NewInt(32)) > 0 {
  148. expHead = new(big.Int).SetBytes(input[offset : offset+32])
  149. } else {
  150. expHead = new(big.Int).SetBytes(input[offset : offset+int(expLen.Uint64())])
  151. }
  152. }
  153. // Calculate the adjusted exponent length
  154. var msb int
  155. if bitlen := expHead.BitLen(); bitlen > 0 {
  156. msb = bitlen - 1
  157. }
  158. adjExpLen := new(big.Int)
  159. if expLen.Cmp(big.NewInt(32)) > 0 {
  160. adjExpLen.Sub(expLen, big.NewInt(32))
  161. adjExpLen.Mul(big.NewInt(8), adjExpLen)
  162. }
  163. adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
  164. // Calculate the gas cost of the operation
  165. gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
  166. switch {
  167. case gas.Cmp(big.NewInt(64)) <= 0:
  168. gas.Mul(gas, gas)
  169. case gas.Cmp(big.NewInt(1024)) <= 0:
  170. gas = new(big.Int).Add(
  171. new(big.Int).Div(new(big.Int).Mul(gas, gas), big.NewInt(4)),
  172. new(big.Int).Sub(new(big.Int).Mul(big.NewInt(96), gas), big.NewInt(3072)),
  173. )
  174. default:
  175. gas = new(big.Int).Add(
  176. new(big.Int).Div(new(big.Int).Mul(gas, gas), big.NewInt(16)),
  177. new(big.Int).Sub(new(big.Int).Mul(big.NewInt(480), gas), big.NewInt(199680)),
  178. )
  179. }
  180. gas.Mul(gas, math.BigMax(adjExpLen, big.NewInt(1)))
  181. gas.Div(gas, new(big.Int).SetUint64(params.ModExpQuadCoeffDiv))
  182. if gas.BitLen() > 64 {
  183. return math.MaxUint64
  184. }
  185. return gas.Uint64()
  186. }
  187. func (c *bigModExp) Run(input []byte) ([]byte, error) {
  188. // Pad the input with zeroes to the minimum size to read the field lengths
  189. input = common.RightPadBytes(input, 96)
  190. var (
  191. baseLen = new(big.Int).SetBytes(input[:32]).Uint64()
  192. expLen = new(big.Int).SetBytes(input[32:64]).Uint64()
  193. modLen = new(big.Int).SetBytes(input[64:96]).Uint64()
  194. )
  195. input = input[96:]
  196. // Pad the input with zeroes to the minimum size to read the field contents
  197. input = common.RightPadBytes(input, int(baseLen+expLen+modLen))
  198. var (
  199. base = new(big.Int).SetBytes(input[:baseLen])
  200. exp = new(big.Int).SetBytes(input[baseLen : baseLen+expLen])
  201. mod = new(big.Int).SetBytes(input[baseLen+expLen : baseLen+expLen+modLen])
  202. )
  203. if mod.BitLen() == 0 {
  204. // Modulo 0 is undefined, return zero
  205. return common.LeftPadBytes([]byte{}, int(modLen)), nil
  206. }
  207. return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
  208. }
  209. var (
  210. // errNotOnCurve is returned if a point being unmarshalled as a bn256 elliptic
  211. // curve point is not on the curve.
  212. errNotOnCurve = errors.New("point not on elliptic curve")
  213. // errInvalidCurvePoint is returned if a point being unmarshalled as a bn256
  214. // elliptic curve point is invalid.
  215. errInvalidCurvePoint = errors.New("invalid elliptic curve point")
  216. )
  217. // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
  218. // returning it, or an error if the point is invalid.
  219. func newCurvePoint(blob []byte) (*bn256.G1, error) {
  220. p, onCurve := new(bn256.G1).Unmarshal(blob)
  221. if !onCurve {
  222. return nil, errNotOnCurve
  223. }
  224. gx, gy, _, _ := p.CurvePoints()
  225. if gx.Cmp(bn256.P) >= 0 || gy.Cmp(bn256.P) >= 0 {
  226. return nil, errInvalidCurvePoint
  227. }
  228. return p, nil
  229. }
  230. // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
  231. // returning it, or an error if the point is invalid.
  232. func newTwistPoint(blob []byte) (*bn256.G2, error) {
  233. p, onCurve := new(bn256.G2).Unmarshal(blob)
  234. if !onCurve {
  235. return nil, errNotOnCurve
  236. }
  237. x2, y2, _, _ := p.CurvePoints()
  238. if x2.Real().Cmp(bn256.P) >= 0 || x2.Imag().Cmp(bn256.P) >= 0 ||
  239. y2.Real().Cmp(bn256.P) >= 0 || y2.Imag().Cmp(bn256.P) >= 0 {
  240. return nil, errInvalidCurvePoint
  241. }
  242. return p, nil
  243. }
  244. // bn256Add implements a native elliptic curve point addition.
  245. type bn256Add struct{}
  246. // RequiredGas returns the gas required to execute the pre-compiled contract.
  247. func (c *bn256Add) RequiredGas(input []byte) uint64 {
  248. return params.Bn256AddGas
  249. }
  250. func (c *bn256Add) Run(input []byte) ([]byte, error) {
  251. // Ensure we have enough data to operate on
  252. input = common.RightPadBytes(input, 128)
  253. x, err := newCurvePoint(input[:64])
  254. if err != nil {
  255. return nil, err
  256. }
  257. y, err := newCurvePoint(input[64:128])
  258. if err != nil {
  259. return nil, err
  260. }
  261. x.Add(x, y)
  262. return x.Marshal(), nil
  263. }
  264. // bn256ScalarMul implements a native elliptic curve scalar multiplication.
  265. type bn256ScalarMul struct{}
  266. // RequiredGas returns the gas required to execute the pre-compiled contract.
  267. func (c *bn256ScalarMul) RequiredGas(input []byte) uint64 {
  268. return params.Bn256ScalarMulGas
  269. }
  270. func (c *bn256ScalarMul) Run(input []byte) ([]byte, error) {
  271. // Ensure we have enough data to operate on
  272. input = common.RightPadBytes(input, 96)
  273. p, err := newCurvePoint(input[:64])
  274. if err != nil {
  275. return nil, err
  276. }
  277. p.ScalarMult(p, new(big.Int).SetBytes(input[64:96]))
  278. return p.Marshal(), nil
  279. }
  280. var (
  281. // true32Byte is returned if the bn256 pairing check succeeds.
  282. 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}
  283. // false32Byte is returned if the bn256 pairing check fails.
  284. false32Byte = make([]byte, 32)
  285. // errBadPairingInput is returned if the bn256 pairing input is invalid.
  286. errBadPairingInput = errors.New("bad elliptic curve pairing size")
  287. )
  288. // bn256Pairing implements a pairing pre-compile for the bn256 curve
  289. type bn256Pairing struct{}
  290. // RequiredGas returns the gas required to execute the pre-compiled contract.
  291. func (c *bn256Pairing) RequiredGas(input []byte) uint64 {
  292. return params.Bn256PairingBaseGas + uint64(len(input)/192)*params.Bn256PairingPerPointGas
  293. }
  294. func (c *bn256Pairing) Run(input []byte) ([]byte, error) {
  295. // Handle some corner cases cheaply
  296. if len(input)%192 > 0 {
  297. return nil, errBadPairingInput
  298. }
  299. // Convert the input into a set of coordinates
  300. var (
  301. cs []*bn256.G1
  302. ts []*bn256.G2
  303. )
  304. for i := 0; i < len(input); i += 192 {
  305. c, err := newCurvePoint(input[i : i+64])
  306. if err != nil {
  307. return nil, err
  308. }
  309. t, err := newTwistPoint(input[i+64 : i+192])
  310. if err != nil {
  311. return nil, err
  312. }
  313. cs = append(cs, c)
  314. ts = append(ts, t)
  315. }
  316. // Execute the pairing checks and return the results
  317. ok := bn256.PairingCheck(cs, ts)
  318. if ok {
  319. return true32Byte, nil
  320. }
  321. return false32Byte, nil
  322. }