contracts.go 16 KB

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