contracts.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. var errBadPrecompileInput = errors.New("bad pre compile input")
  29. // Precompiled contract is the basic interface for native Go contracts. The implementation
  30. // requires a deterministic gas count based on the input size of the Run method of the
  31. // contract.
  32. type PrecompiledContract interface {
  33. RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use
  34. Run(input []byte) ([]byte, error) // Run runs the precompiled contract
  35. }
  36. // PrecompiledContracts contains the default set of ethereum contracts
  37. var PrecompiledContracts = 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 ethereum contracts
  44. // for metropolis hardfork
  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}): &pairing{},
  54. }
  55. // RunPrecompile runs and evaluate the output of a precompiled contract defined in contracts.go
  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. } else {
  61. return nil, ErrOutOfGas
  62. }
  63. }
  64. // ECRECOVER implemented as a native contract
  65. type ecrecover struct{}
  66. func (c *ecrecover) RequiredGas(input []byte) uint64 {
  67. return params.EcrecoverGas
  68. }
  69. func (c *ecrecover) Run(in []byte) ([]byte, error) {
  70. const ecRecoverInputLength = 128
  71. in = common.RightPadBytes(in, ecRecoverInputLength)
  72. // "in" is (hash, v, r, s), each 32 bytes
  73. // but for ecrecover we want (r, s, v)
  74. r := new(big.Int).SetBytes(in[64:96])
  75. s := new(big.Int).SetBytes(in[96:128])
  76. v := in[63] - 27
  77. // tighter sig s values in homestead only apply to tx sigs
  78. if !allZero(in[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
  79. return nil, nil
  80. }
  81. // v needs to be at the end for libsecp256k1
  82. pubKey, err := crypto.Ecrecover(in[:32], append(in[64:128], v))
  83. // make sure the public key is a valid one
  84. if err != nil {
  85. return nil, nil
  86. }
  87. // the first byte of pubkey is bitcoin heritage
  88. return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil
  89. }
  90. // SHA256 implemented as a native contract
  91. type sha256hash struct{}
  92. // RequiredGas returns the gas required to execute the pre-compiled contract.
  93. //
  94. // This method does not require any overflow checking as the input size gas costs
  95. // required for anything significant is so high it's impossible to pay for.
  96. func (c *sha256hash) RequiredGas(input []byte) uint64 {
  97. return uint64(len(input)+31)/32*params.Sha256WordGas + params.Sha256Gas
  98. }
  99. func (c *sha256hash) Run(in []byte) ([]byte, error) {
  100. h := sha256.Sum256(in)
  101. return h[:], nil
  102. }
  103. // RIPMED160 implemented as a native contract
  104. type ripemd160hash struct{}
  105. // RequiredGas returns the gas required to execute the pre-compiled contract.
  106. //
  107. // This method does not require any overflow checking as the input size gas costs
  108. // required for anything significant is so high it's impossible to pay for.
  109. func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
  110. return uint64(len(input)+31)/32*params.Ripemd160WordGas + params.Ripemd160Gas
  111. }
  112. func (c *ripemd160hash) Run(in []byte) ([]byte, error) {
  113. ripemd := ripemd160.New()
  114. ripemd.Write(in)
  115. return common.LeftPadBytes(ripemd.Sum(nil), 32), nil
  116. }
  117. // data copy implemented as a native contract
  118. type dataCopy 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 *dataCopy) RequiredGas(input []byte) uint64 {
  124. return uint64(len(input)+31)/32*params.IdentityWordGas + params.IdentityGas
  125. }
  126. func (c *dataCopy) Run(in []byte) ([]byte, error) {
  127. return in, nil
  128. }
  129. // bigModexp implements a native big integer exponential modular operation.
  130. type bigModexp struct{}
  131. // RequiredGas returns the gas required to execute the pre-compiled contract.
  132. //
  133. // This method does not require any overflow checking as the input size gas costs
  134. // required for anything significant is so high it's impossible to pay for.
  135. func (c *bigModexp) RequiredGas(input []byte) uint64 {
  136. // TODO reword required gas to have error reporting and convert arithmetic
  137. // to uint64.
  138. if len(input) < 3*32 {
  139. input = append(input, make([]byte, 3*32-len(input))...)
  140. }
  141. var (
  142. baseLen = new(big.Int).SetBytes(input[:31])
  143. expLen = math.BigMax(new(big.Int).SetBytes(input[32:64]), big.NewInt(1))
  144. modLen = new(big.Int).SetBytes(input[65:97])
  145. )
  146. x := new(big.Int).Set(math.BigMax(baseLen, modLen))
  147. x.Mul(x, x)
  148. x.Mul(x, expLen)
  149. x.Div(x, new(big.Int).SetUint64(params.QuadCoeffDiv))
  150. return x.Uint64()
  151. }
  152. func (c *bigModexp) Run(input []byte) ([]byte, error) {
  153. if len(input) < 3*32 {
  154. input = append(input, make([]byte, 3*32-len(input))...)
  155. }
  156. // why 32-byte? These values won't fit anyway
  157. var (
  158. baseLen = new(big.Int).SetBytes(input[:32]).Uint64()
  159. expLen = new(big.Int).SetBytes(input[32:64]).Uint64()
  160. modLen = new(big.Int).SetBytes(input[64:96]).Uint64()
  161. )
  162. input = input[96:]
  163. if uint64(len(input)) < baseLen {
  164. input = append(input, make([]byte, baseLen-uint64(len(input)))...)
  165. }
  166. base := new(big.Int).SetBytes(input[:baseLen])
  167. input = input[baseLen:]
  168. if uint64(len(input)) < expLen {
  169. input = append(input, make([]byte, expLen-uint64(len(input)))...)
  170. }
  171. exp := new(big.Int).SetBytes(input[:expLen])
  172. input = input[expLen:]
  173. if uint64(len(input)) < modLen {
  174. input = append(input, make([]byte, modLen-uint64(len(input)))...)
  175. }
  176. mod := new(big.Int).SetBytes(input[:modLen])
  177. return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), len(input[:modLen])), nil
  178. }
  179. type bn256Add struct{}
  180. // RequiredGas returns the gas required to execute the pre-compiled contract.
  181. //
  182. // This method does not require any overflow checking as the input size gas costs
  183. // required for anything significant is so high it's impossible to pay for.
  184. func (c *bn256Add) RequiredGas(input []byte) uint64 {
  185. return 0 // TODO
  186. }
  187. func (c *bn256Add) Run(in []byte) ([]byte, error) {
  188. in = common.RightPadBytes(in, 128)
  189. x, onCurve := new(bn256.G1).Unmarshal(in[:64])
  190. if !onCurve {
  191. return nil, errNotOnCurve
  192. }
  193. gx, gy, _, _ := x.CurvePoints()
  194. if gx.Cmp(bn256.P) >= 0 || gy.Cmp(bn256.P) >= 0 {
  195. return nil, errInvalidCurvePoint
  196. }
  197. y, onCurve := new(bn256.G1).Unmarshal(in[64:128])
  198. if !onCurve {
  199. return nil, errNotOnCurve
  200. }
  201. gx, gy, _, _ = y.CurvePoints()
  202. if gx.Cmp(bn256.P) >= 0 || gy.Cmp(bn256.P) >= 0 {
  203. return nil, errInvalidCurvePoint
  204. }
  205. x.Add(x, y)
  206. return x.Marshal(), nil
  207. }
  208. type bn256ScalarMul struct{}
  209. // RequiredGas returns the gas required to execute the pre-compiled contract.
  210. //
  211. // This method does not require any overflow checking as the input size gas costs
  212. // required for anything significant is so high it's impossible to pay for.
  213. func (c *bn256ScalarMul) RequiredGas(input []byte) uint64 {
  214. return 0 // TODO
  215. }
  216. func (c *bn256ScalarMul) Run(in []byte) ([]byte, error) {
  217. in = common.RightPadBytes(in, 96)
  218. g1, onCurve := new(bn256.G1).Unmarshal(in[:64])
  219. if !onCurve {
  220. return nil, errNotOnCurve
  221. }
  222. x, y, _, _ := g1.CurvePoints()
  223. if x.Cmp(bn256.P) >= 0 || y.Cmp(bn256.P) >= 0 {
  224. return nil, errInvalidCurvePoint
  225. }
  226. g1.ScalarMult(g1, new(big.Int).SetBytes(in[64:96]))
  227. return g1.Marshal(), nil
  228. }
  229. // pairing implements a pairing pre-compile for the bn256 curve
  230. type pairing struct{}
  231. // RequiredGas returns the gas required to execute the pre-compiled contract.
  232. //
  233. // This method does not require any overflow checking as the input size gas costs
  234. // required for anything significant is so high it's impossible to pay for.
  235. func (c *pairing) RequiredGas(input []byte) uint64 {
  236. //return 0 // TODO
  237. k := (len(input) + 191) / pairSize
  238. return uint64(60000*k + 40000)
  239. }
  240. const pairSize = 192
  241. var (
  242. 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}
  243. fals32Byte = make([]byte, 32)
  244. errNotOnCurve = errors.New("point not on elliptic curve")
  245. errInvalidCurvePoint = errors.New("invalid elliptic curve point")
  246. )
  247. func (c *pairing) Run(in []byte) ([]byte, error) {
  248. if len(in) == 0 {
  249. return true32Byte, nil
  250. }
  251. if len(in)%pairSize > 0 {
  252. return nil, errBadPrecompileInput
  253. }
  254. var (
  255. g1s []*bn256.G1
  256. g2s []*bn256.G2
  257. )
  258. for i := 0; i < len(in); i += pairSize {
  259. g1, onCurve := new(bn256.G1).Unmarshal(in[i : i+64])
  260. if !onCurve {
  261. return nil, errNotOnCurve
  262. }
  263. x, y, _, _ := g1.CurvePoints()
  264. if x.Cmp(bn256.P) >= 0 || y.Cmp(bn256.P) >= 0 {
  265. return nil, errInvalidCurvePoint
  266. }
  267. g2, onCurve := new(bn256.G2).Unmarshal(in[i+64 : i+192])
  268. if !onCurve {
  269. return nil, errNotOnCurve
  270. }
  271. x2, y2, _, _ := g2.CurvePoints()
  272. if x2.Real().Cmp(bn256.P) >= 0 || x2.Imag().Cmp(bn256.P) >= 0 ||
  273. y2.Real().Cmp(bn256.P) >= 0 || y2.Imag().Cmp(bn256.P) >= 0 {
  274. return nil, errInvalidCurvePoint
  275. }
  276. g1s = append(g1s, g1)
  277. g2s = append(g2s, g2)
  278. }
  279. isOne := bn256.PairingCheck(g1s, g2s)
  280. if isOne {
  281. return true32Byte, nil
  282. }
  283. return fals32Byte, nil
  284. }