contracts.go 16 KB

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