contracts.go 16 KB

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