contracts.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. "encoding/binary"
  20. "errors"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/math"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/crypto/blake2b"
  26. "github.com/ethereum/go-ethereum/crypto/bn256"
  27. "github.com/ethereum/go-ethereum/params"
  28. "golang.org/x/crypto/ripemd160"
  29. )
  30. // PrecompiledContract is the basic interface for native Go contracts. The implementation
  31. // requires a deterministic gas count based on the input size of the Run method of the
  32. // contract.
  33. type PrecompiledContract interface {
  34. RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use
  35. Run(input []byte) ([]byte, error) // Run runs the precompiled contract
  36. }
  37. // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum
  38. // contracts used in the Frontier and Homestead releases.
  39. var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{
  40. common.BytesToAddress([]byte{1}): &ecrecover{},
  41. common.BytesToAddress([]byte{2}): &sha256hash{},
  42. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  43. common.BytesToAddress([]byte{4}): &dataCopy{},
  44. }
  45. // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum
  46. // contracts used in the Byzantium release.
  47. var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{
  48. common.BytesToAddress([]byte{1}): &ecrecover{},
  49. common.BytesToAddress([]byte{2}): &sha256hash{},
  50. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  51. common.BytesToAddress([]byte{4}): &dataCopy{},
  52. common.BytesToAddress([]byte{5}): &bigModExp{},
  53. common.BytesToAddress([]byte{6}): &bn256AddByzantium{},
  54. common.BytesToAddress([]byte{7}): &bn256ScalarMulByzantium{},
  55. common.BytesToAddress([]byte{8}): &bn256PairingByzantium{},
  56. }
  57. // PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum
  58. // contracts used in the Istanbul release.
  59. var PrecompiledContractsIstanbul = map[common.Address]PrecompiledContract{
  60. common.BytesToAddress([]byte{1}): &ecrecover{},
  61. common.BytesToAddress([]byte{2}): &sha256hash{},
  62. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  63. common.BytesToAddress([]byte{4}): &dataCopy{},
  64. common.BytesToAddress([]byte{5}): &bigModExp{},
  65. common.BytesToAddress([]byte{6}): &bn256AddIstanbul{},
  66. common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{},
  67. common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{},
  68. common.BytesToAddress([]byte{9}): &blake2F{},
  69. }
  70. // RunPrecompiledContract runs and evaluates the output of a precompiled contract.
  71. func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) {
  72. gas := p.RequiredGas(input)
  73. if contract.UseGas(gas) {
  74. return p.Run(input)
  75. }
  76. return nil, ErrOutOfGas
  77. }
  78. // ECRECOVER implemented as a native contract.
  79. type ecrecover struct{}
  80. func (c *ecrecover) RequiredGas(input []byte) uint64 {
  81. return params.EcrecoverGas
  82. }
  83. func (c *ecrecover) Run(input []byte) ([]byte, error) {
  84. const ecRecoverInputLength = 128
  85. input = common.RightPadBytes(input, ecRecoverInputLength)
  86. // "input" is (hash, v, r, s), each 32 bytes
  87. // but for ecrecover we want (r, s, v)
  88. r := new(big.Int).SetBytes(input[64:96])
  89. s := new(big.Int).SetBytes(input[96:128])
  90. v := input[63] - 27
  91. // tighter sig s values input homestead only apply to tx sigs
  92. if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
  93. return nil, nil
  94. }
  95. // v needs to be at the end for libsecp256k1
  96. pubKey, err := crypto.Ecrecover(input[:32], append(input[64:128], v))
  97. // make sure the public key is a valid one
  98. if err != nil {
  99. return nil, nil
  100. }
  101. // the first byte of pubkey is bitcoin heritage
  102. return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil
  103. }
  104. // SHA256 implemented as a native contract.
  105. type sha256hash struct{}
  106. // RequiredGas returns the gas required to execute the pre-compiled contract.
  107. //
  108. // This method does not require any overflow checking as the input size gas costs
  109. // required for anything significant is so high it's impossible to pay for.
  110. func (c *sha256hash) RequiredGas(input []byte) uint64 {
  111. return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
  112. }
  113. func (c *sha256hash) Run(input []byte) ([]byte, error) {
  114. h := sha256.Sum256(input)
  115. return h[:], nil
  116. }
  117. // RIPEMD160 implemented as a native contract.
  118. type ripemd160hash struct{}
  119. // RequiredGas returns the gas required to execute the pre-compiled contract.
  120. //
  121. // This method does not require any overflow checking as the input size gas costs
  122. // required for anything significant is so high it's impossible to pay for.
  123. func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
  124. return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas
  125. }
  126. func (c *ripemd160hash) Run(input []byte) ([]byte, error) {
  127. ripemd := ripemd160.New()
  128. ripemd.Write(input)
  129. return common.LeftPadBytes(ripemd.Sum(nil), 32), nil
  130. }
  131. // data copy implemented as a native contract.
  132. type dataCopy struct{}
  133. // RequiredGas returns the gas required to execute the pre-compiled contract.
  134. //
  135. // This method does not require any overflow checking as the input size gas costs
  136. // required for anything significant is so high it's impossible to pay for.
  137. func (c *dataCopy) RequiredGas(input []byte) uint64 {
  138. return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
  139. }
  140. func (c *dataCopy) Run(in []byte) ([]byte, error) {
  141. return in, nil
  142. }
  143. // bigModExp implements a native big integer exponential modular operation.
  144. type bigModExp struct{}
  145. var (
  146. big1 = big.NewInt(1)
  147. big4 = big.NewInt(4)
  148. big8 = big.NewInt(8)
  149. big16 = big.NewInt(16)
  150. big32 = big.NewInt(32)
  151. big64 = big.NewInt(64)
  152. big96 = big.NewInt(96)
  153. big480 = big.NewInt(480)
  154. big1024 = big.NewInt(1024)
  155. big3072 = big.NewInt(3072)
  156. big199680 = big.NewInt(199680)
  157. )
  158. // RequiredGas returns the gas required to execute the pre-compiled contract.
  159. func (c *bigModExp) RequiredGas(input []byte) uint64 {
  160. var (
  161. baseLen = new(big.Int).SetBytes(getData(input, 0, 32))
  162. expLen = new(big.Int).SetBytes(getData(input, 32, 32))
  163. modLen = new(big.Int).SetBytes(getData(input, 64, 32))
  164. )
  165. if len(input) > 96 {
  166. input = input[96:]
  167. } else {
  168. input = input[:0]
  169. }
  170. // Retrieve the head 32 bytes of exp for the adjusted exponent length
  171. var expHead *big.Int
  172. if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
  173. expHead = new(big.Int)
  174. } else {
  175. if expLen.Cmp(big32) > 0 {
  176. expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32))
  177. } else {
  178. expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64()))
  179. }
  180. }
  181. // Calculate the adjusted exponent length
  182. var msb int
  183. if bitlen := expHead.BitLen(); bitlen > 0 {
  184. msb = bitlen - 1
  185. }
  186. adjExpLen := new(big.Int)
  187. if expLen.Cmp(big32) > 0 {
  188. adjExpLen.Sub(expLen, big32)
  189. adjExpLen.Mul(big8, adjExpLen)
  190. }
  191. adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
  192. // Calculate the gas cost of the operation
  193. gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
  194. switch {
  195. case gas.Cmp(big64) <= 0:
  196. gas.Mul(gas, gas)
  197. case gas.Cmp(big1024) <= 0:
  198. gas = new(big.Int).Add(
  199. new(big.Int).Div(new(big.Int).Mul(gas, gas), big4),
  200. new(big.Int).Sub(new(big.Int).Mul(big96, gas), big3072),
  201. )
  202. default:
  203. gas = new(big.Int).Add(
  204. new(big.Int).Div(new(big.Int).Mul(gas, gas), big16),
  205. new(big.Int).Sub(new(big.Int).Mul(big480, gas), big199680),
  206. )
  207. }
  208. gas.Mul(gas, math.BigMax(adjExpLen, big1))
  209. gas.Div(gas, new(big.Int).SetUint64(params.ModExpQuadCoeffDiv))
  210. if gas.BitLen() > 64 {
  211. return math.MaxUint64
  212. }
  213. return gas.Uint64()
  214. }
  215. func (c *bigModExp) Run(input []byte) ([]byte, error) {
  216. var (
  217. baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64()
  218. expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64()
  219. modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64()
  220. )
  221. if len(input) > 96 {
  222. input = input[96:]
  223. } else {
  224. input = input[:0]
  225. }
  226. // Handle a special case when both the base and mod length is zero
  227. if baseLen == 0 && modLen == 0 {
  228. return []byte{}, nil
  229. }
  230. // Retrieve the operands and execute the exponentiation
  231. var (
  232. base = new(big.Int).SetBytes(getData(input, 0, baseLen))
  233. exp = new(big.Int).SetBytes(getData(input, baseLen, expLen))
  234. mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
  235. )
  236. if mod.BitLen() == 0 {
  237. // Modulo 0 is undefined, return zero
  238. return common.LeftPadBytes([]byte{}, int(modLen)), nil
  239. }
  240. return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
  241. }
  242. // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
  243. // returning it, or an error if the point is invalid.
  244. func newCurvePoint(blob []byte) (*bn256.G1, error) {
  245. p := new(bn256.G1)
  246. if _, err := p.Unmarshal(blob); err != nil {
  247. return nil, err
  248. }
  249. return p, nil
  250. }
  251. // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
  252. // returning it, or an error if the point is invalid.
  253. func newTwistPoint(blob []byte) (*bn256.G2, error) {
  254. p := new(bn256.G2)
  255. if _, err := p.Unmarshal(blob); err != nil {
  256. return nil, err
  257. }
  258. return p, nil
  259. }
  260. // runBn256Add implements the Bn256Add precompile, referenced by both
  261. // Byzantium and Istanbul operations.
  262. func runBn256Add(input []byte) ([]byte, error) {
  263. x, err := newCurvePoint(getData(input, 0, 64))
  264. if err != nil {
  265. return nil, err
  266. }
  267. y, err := newCurvePoint(getData(input, 64, 64))
  268. if err != nil {
  269. return nil, err
  270. }
  271. res := new(bn256.G1)
  272. res.Add(x, y)
  273. return res.Marshal(), nil
  274. }
  275. // bn256Add implements a native elliptic curve point addition conforming to
  276. // Istanbul consensus rules.
  277. type bn256AddIstanbul struct{}
  278. // RequiredGas returns the gas required to execute the pre-compiled contract.
  279. func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 {
  280. return params.Bn256AddGasIstanbul
  281. }
  282. func (c *bn256AddIstanbul) Run(input []byte) ([]byte, error) {
  283. return runBn256Add(input)
  284. }
  285. // bn256AddByzantium implements a native elliptic curve point addition
  286. // conforming to Byzantium consensus rules.
  287. type bn256AddByzantium struct{}
  288. // RequiredGas returns the gas required to execute the pre-compiled contract.
  289. func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 {
  290. return params.Bn256AddGasByzantium
  291. }
  292. func (c *bn256AddByzantium) Run(input []byte) ([]byte, error) {
  293. return runBn256Add(input)
  294. }
  295. // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by
  296. // both Byzantium and Istanbul operations.
  297. func runBn256ScalarMul(input []byte) ([]byte, error) {
  298. p, err := newCurvePoint(getData(input, 0, 64))
  299. if err != nil {
  300. return nil, err
  301. }
  302. res := new(bn256.G1)
  303. res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32)))
  304. return res.Marshal(), nil
  305. }
  306. // bn256ScalarMulIstanbul implements a native elliptic curve scalar
  307. // multiplication conforming to Istanbul consensus rules.
  308. type bn256ScalarMulIstanbul struct{}
  309. // RequiredGas returns the gas required to execute the pre-compiled contract.
  310. func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 {
  311. return params.Bn256ScalarMulGasIstanbul
  312. }
  313. func (c *bn256ScalarMulIstanbul) Run(input []byte) ([]byte, error) {
  314. return runBn256ScalarMul(input)
  315. }
  316. // bn256ScalarMulByzantium implements a native elliptic curve scalar
  317. // multiplication conforming to Byzantium consensus rules.
  318. type bn256ScalarMulByzantium struct{}
  319. // RequiredGas returns the gas required to execute the pre-compiled contract.
  320. func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 {
  321. return params.Bn256ScalarMulGasByzantium
  322. }
  323. func (c *bn256ScalarMulByzantium) Run(input []byte) ([]byte, error) {
  324. return runBn256ScalarMul(input)
  325. }
  326. var (
  327. // true32Byte is returned if the bn256 pairing check succeeds.
  328. 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}
  329. // false32Byte is returned if the bn256 pairing check fails.
  330. false32Byte = make([]byte, 32)
  331. // errBadPairingInput is returned if the bn256 pairing input is invalid.
  332. errBadPairingInput = errors.New("bad elliptic curve pairing size")
  333. )
  334. // runBn256Pairing implements the Bn256Pairing precompile, referenced by both
  335. // Byzantium and Istanbul operations.
  336. func runBn256Pairing(input []byte) ([]byte, error) {
  337. // Handle some corner cases cheaply
  338. if len(input)%192 > 0 {
  339. return nil, errBadPairingInput
  340. }
  341. // Convert the input into a set of coordinates
  342. var (
  343. cs []*bn256.G1
  344. ts []*bn256.G2
  345. )
  346. for i := 0; i < len(input); i += 192 {
  347. c, err := newCurvePoint(input[i : i+64])
  348. if err != nil {
  349. return nil, err
  350. }
  351. t, err := newTwistPoint(input[i+64 : i+192])
  352. if err != nil {
  353. return nil, err
  354. }
  355. cs = append(cs, c)
  356. ts = append(ts, t)
  357. }
  358. // Execute the pairing checks and return the results
  359. if bn256.PairingCheck(cs, ts) {
  360. return true32Byte, nil
  361. }
  362. return false32Byte, nil
  363. }
  364. // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve
  365. // conforming to Istanbul consensus rules.
  366. type bn256PairingIstanbul struct{}
  367. // RequiredGas returns the gas required to execute the pre-compiled contract.
  368. func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 {
  369. return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul
  370. }
  371. func (c *bn256PairingIstanbul) Run(input []byte) ([]byte, error) {
  372. return runBn256Pairing(input)
  373. }
  374. // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve
  375. // conforming to Byzantium consensus rules.
  376. type bn256PairingByzantium struct{}
  377. // RequiredGas returns the gas required to execute the pre-compiled contract.
  378. func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 {
  379. return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium
  380. }
  381. func (c *bn256PairingByzantium) Run(input []byte) ([]byte, error) {
  382. return runBn256Pairing(input)
  383. }
  384. type blake2F struct{}
  385. func (c *blake2F) RequiredGas(input []byte) uint64 {
  386. // If the input is malformed, we can't calculate the gas, return 0 and let the
  387. // actual call choke and fault.
  388. if len(input) != blake2FInputLength {
  389. return 0
  390. }
  391. return uint64(binary.BigEndian.Uint32(input[0:4]))
  392. }
  393. const (
  394. blake2FInputLength = 213
  395. blake2FFinalBlockBytes = byte(1)
  396. blake2FNonFinalBlockBytes = byte(0)
  397. )
  398. var (
  399. errBlake2FInvalidInputLength = errors.New("invalid input length")
  400. errBlake2FInvalidFinalFlag = errors.New("invalid final flag")
  401. )
  402. func (c *blake2F) Run(input []byte) ([]byte, error) {
  403. // Make sure the input is valid (correct lenth and final flag)
  404. if len(input) != blake2FInputLength {
  405. return nil, errBlake2FInvalidInputLength
  406. }
  407. if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes {
  408. return nil, errBlake2FInvalidFinalFlag
  409. }
  410. // Parse the input into the Blake2b call parameters
  411. var (
  412. rounds = binary.BigEndian.Uint32(input[0:4])
  413. final = (input[212] == blake2FFinalBlockBytes)
  414. h [8]uint64
  415. m [16]uint64
  416. t [2]uint64
  417. )
  418. for i := 0; i < 8; i++ {
  419. offset := 4 + i*8
  420. h[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
  421. }
  422. for i := 0; i < 16; i++ {
  423. offset := 68 + i*8
  424. m[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
  425. }
  426. t[0] = binary.LittleEndian.Uint64(input[196:204])
  427. t[1] = binary.LittleEndian.Uint64(input[204:212])
  428. // Execute the compression function, extract and return the result
  429. blake2b.F(&h, m, t, final, rounds)
  430. output := make([]byte, 64)
  431. for i := 0; i < 8; i++ {
  432. offset := i * 8
  433. binary.LittleEndian.PutUint64(output[offset:offset+8], h[i])
  434. }
  435. return output, nil
  436. }