contracts.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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/bls12381"
  27. "github.com/ethereum/go-ethereum/crypto/bn256"
  28. "github.com/ethereum/go-ethereum/params"
  29. //lint:ignore SA1019 Needed for precompile
  30. "golang.org/x/crypto/ripemd160"
  31. )
  32. // PrecompiledContract is the basic interface for native Go contracts. The implementation
  33. // requires a deterministic gas count based on the input size of the Run method of the
  34. // contract.
  35. type PrecompiledContract interface {
  36. RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use
  37. Run(input []byte) ([]byte, error) // Run runs the precompiled contract
  38. }
  39. // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum
  40. // contracts used in the Frontier and Homestead releases.
  41. var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{
  42. common.BytesToAddress([]byte{1}): &ecrecover{},
  43. common.BytesToAddress([]byte{2}): &sha256hash{},
  44. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  45. common.BytesToAddress([]byte{4}): &dataCopy{},
  46. }
  47. // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum
  48. // contracts used in the Byzantium release.
  49. var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{
  50. common.BytesToAddress([]byte{1}): &ecrecover{},
  51. common.BytesToAddress([]byte{2}): &sha256hash{},
  52. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  53. common.BytesToAddress([]byte{4}): &dataCopy{},
  54. common.BytesToAddress([]byte{5}): &bigModExp{eip2565: false},
  55. common.BytesToAddress([]byte{6}): &bn256AddByzantium{},
  56. common.BytesToAddress([]byte{7}): &bn256ScalarMulByzantium{},
  57. common.BytesToAddress([]byte{8}): &bn256PairingByzantium{},
  58. }
  59. // PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum
  60. // contracts used in the Istanbul release.
  61. var PrecompiledContractsIstanbul = map[common.Address]PrecompiledContract{
  62. common.BytesToAddress([]byte{1}): &ecrecover{},
  63. common.BytesToAddress([]byte{2}): &sha256hash{},
  64. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  65. common.BytesToAddress([]byte{4}): &dataCopy{},
  66. common.BytesToAddress([]byte{5}): &bigModExp{eip2565: false},
  67. common.BytesToAddress([]byte{6}): &bn256AddIstanbul{},
  68. common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{},
  69. common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{},
  70. common.BytesToAddress([]byte{9}): &blake2F{},
  71. }
  72. // PrecompiledContractsYoloV2 contains the default set of pre-compiled Ethereum
  73. // contracts used in the Yolo v2 test release.
  74. var PrecompiledContractsYoloV2 = map[common.Address]PrecompiledContract{
  75. common.BytesToAddress([]byte{1}): &ecrecover{},
  76. common.BytesToAddress([]byte{2}): &sha256hash{},
  77. common.BytesToAddress([]byte{3}): &ripemd160hash{},
  78. common.BytesToAddress([]byte{4}): &dataCopy{},
  79. common.BytesToAddress([]byte{5}): &bigModExp{eip2565: false},
  80. common.BytesToAddress([]byte{6}): &bn256AddIstanbul{},
  81. common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{},
  82. common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{},
  83. common.BytesToAddress([]byte{9}): &blake2F{},
  84. common.BytesToAddress([]byte{10}): &bls12381G1Add{},
  85. common.BytesToAddress([]byte{11}): &bls12381G1Mul{},
  86. common.BytesToAddress([]byte{12}): &bls12381G1MultiExp{},
  87. common.BytesToAddress([]byte{13}): &bls12381G2Add{},
  88. common.BytesToAddress([]byte{14}): &bls12381G2Mul{},
  89. common.BytesToAddress([]byte{15}): &bls12381G2MultiExp{},
  90. common.BytesToAddress([]byte{16}): &bls12381Pairing{},
  91. common.BytesToAddress([]byte{17}): &bls12381MapG1{},
  92. common.BytesToAddress([]byte{18}): &bls12381MapG2{},
  93. }
  94. var (
  95. PrecompiledAddressesYoloV2 []common.Address
  96. PrecompiledAddressesIstanbul []common.Address
  97. PrecompiledAddressesByzantium []common.Address
  98. PrecompiledAddressesHomestead []common.Address
  99. )
  100. func init() {
  101. for k := range PrecompiledContractsHomestead {
  102. PrecompiledAddressesHomestead = append(PrecompiledAddressesHomestead, k)
  103. }
  104. for k := range PrecompiledContractsByzantium {
  105. PrecompiledAddressesHomestead = append(PrecompiledAddressesByzantium, k)
  106. }
  107. for k := range PrecompiledContractsIstanbul {
  108. PrecompiledAddressesIstanbul = append(PrecompiledAddressesIstanbul, k)
  109. }
  110. for k := range PrecompiledContractsYoloV2 {
  111. PrecompiledAddressesYoloV2 = append(PrecompiledAddressesYoloV2, k)
  112. }
  113. }
  114. // RunPrecompiledContract runs and evaluates the output of a precompiled contract.
  115. // It returns
  116. // - the returned bytes,
  117. // - the _remaining_ gas,
  118. // - any error that occurred
  119. func RunPrecompiledContract(p PrecompiledContract, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error) {
  120. gasCost := p.RequiredGas(input)
  121. if suppliedGas < gasCost {
  122. return nil, 0, ErrOutOfGas
  123. }
  124. suppliedGas -= gasCost
  125. output, err := p.Run(input)
  126. return output, suppliedGas, err
  127. }
  128. // ECRECOVER implemented as a native contract.
  129. type ecrecover struct{}
  130. func (c *ecrecover) RequiredGas(input []byte) uint64 {
  131. return params.EcrecoverGas
  132. }
  133. func (c *ecrecover) Run(input []byte) ([]byte, error) {
  134. const ecRecoverInputLength = 128
  135. input = common.RightPadBytes(input, ecRecoverInputLength)
  136. // "input" is (hash, v, r, s), each 32 bytes
  137. // but for ecrecover we want (r, s, v)
  138. r := new(big.Int).SetBytes(input[64:96])
  139. s := new(big.Int).SetBytes(input[96:128])
  140. v := input[63] - 27
  141. // tighter sig s values input homestead only apply to tx sigs
  142. if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
  143. return nil, nil
  144. }
  145. // We must make sure not to modify the 'input', so placing the 'v' along with
  146. // the signature needs to be done on a new allocation
  147. sig := make([]byte, 65)
  148. copy(sig, input[64:128])
  149. sig[64] = v
  150. // v needs to be at the end for libsecp256k1
  151. pubKey, err := crypto.Ecrecover(input[:32], sig)
  152. // make sure the public key is a valid one
  153. if err != nil {
  154. return nil, nil
  155. }
  156. // the first byte of pubkey is bitcoin heritage
  157. return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil
  158. }
  159. // SHA256 implemented as a native contract.
  160. type sha256hash struct{}
  161. // RequiredGas returns the gas required to execute the pre-compiled contract.
  162. //
  163. // This method does not require any overflow checking as the input size gas costs
  164. // required for anything significant is so high it's impossible to pay for.
  165. func (c *sha256hash) RequiredGas(input []byte) uint64 {
  166. return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
  167. }
  168. func (c *sha256hash) Run(input []byte) ([]byte, error) {
  169. h := sha256.Sum256(input)
  170. return h[:], nil
  171. }
  172. // RIPEMD160 implemented as a native contract.
  173. type ripemd160hash struct{}
  174. // RequiredGas returns the gas required to execute the pre-compiled contract.
  175. //
  176. // This method does not require any overflow checking as the input size gas costs
  177. // required for anything significant is so high it's impossible to pay for.
  178. func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
  179. return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas
  180. }
  181. func (c *ripemd160hash) Run(input []byte) ([]byte, error) {
  182. ripemd := ripemd160.New()
  183. ripemd.Write(input)
  184. return common.LeftPadBytes(ripemd.Sum(nil), 32), nil
  185. }
  186. // data copy implemented as a native contract.
  187. type dataCopy struct{}
  188. // RequiredGas returns the gas required to execute the pre-compiled contract.
  189. //
  190. // This method does not require any overflow checking as the input size gas costs
  191. // required for anything significant is so high it's impossible to pay for.
  192. func (c *dataCopy) RequiredGas(input []byte) uint64 {
  193. return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
  194. }
  195. func (c *dataCopy) Run(in []byte) ([]byte, error) {
  196. return in, nil
  197. }
  198. // bigModExp implements a native big integer exponential modular operation.
  199. type bigModExp struct {
  200. eip2565 bool
  201. }
  202. var (
  203. big0 = big.NewInt(0)
  204. big1 = big.NewInt(1)
  205. big3 = big.NewInt(3)
  206. big4 = big.NewInt(4)
  207. big7 = big.NewInt(7)
  208. big8 = big.NewInt(8)
  209. big16 = big.NewInt(16)
  210. big20 = big.NewInt(20)
  211. big32 = big.NewInt(32)
  212. big64 = big.NewInt(64)
  213. big96 = big.NewInt(96)
  214. big480 = big.NewInt(480)
  215. big1024 = big.NewInt(1024)
  216. big3072 = big.NewInt(3072)
  217. big199680 = big.NewInt(199680)
  218. )
  219. // modexpMultComplexity implements bigModexp multComplexity formula, as defined in EIP-198
  220. //
  221. // def mult_complexity(x):
  222. // if x <= 64: return x ** 2
  223. // elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072
  224. // else: return x ** 2 // 16 + 480 * x - 199680
  225. //
  226. // where is x is max(length_of_MODULUS, length_of_BASE)
  227. func modexpMultComplexity(x *big.Int) *big.Int {
  228. switch {
  229. case x.Cmp(big64) <= 0:
  230. x.Mul(x, x) // x ** 2
  231. case x.Cmp(big1024) <= 0:
  232. // (x ** 2 // 4 ) + ( 96 * x - 3072)
  233. x = new(big.Int).Add(
  234. new(big.Int).Div(new(big.Int).Mul(x, x), big4),
  235. new(big.Int).Sub(new(big.Int).Mul(big96, x), big3072),
  236. )
  237. default:
  238. // (x ** 2 // 16) + (480 * x - 199680)
  239. x = new(big.Int).Add(
  240. new(big.Int).Div(new(big.Int).Mul(x, x), big16),
  241. new(big.Int).Sub(new(big.Int).Mul(big480, x), big199680),
  242. )
  243. }
  244. return x
  245. }
  246. // RequiredGas returns the gas required to execute the pre-compiled contract.
  247. func (c *bigModExp) RequiredGas(input []byte) uint64 {
  248. var (
  249. baseLen = new(big.Int).SetBytes(getData(input, 0, 32))
  250. expLen = new(big.Int).SetBytes(getData(input, 32, 32))
  251. modLen = new(big.Int).SetBytes(getData(input, 64, 32))
  252. )
  253. if len(input) > 96 {
  254. input = input[96:]
  255. } else {
  256. input = input[:0]
  257. }
  258. // Retrieve the head 32 bytes of exp for the adjusted exponent length
  259. var expHead *big.Int
  260. if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
  261. expHead = new(big.Int)
  262. } else {
  263. if expLen.Cmp(big32) > 0 {
  264. expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32))
  265. } else {
  266. expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64()))
  267. }
  268. }
  269. // Calculate the adjusted exponent length
  270. var msb int
  271. if bitlen := expHead.BitLen(); bitlen > 0 {
  272. msb = bitlen - 1
  273. }
  274. adjExpLen := new(big.Int)
  275. if expLen.Cmp(big32) > 0 {
  276. adjExpLen.Sub(expLen, big32)
  277. adjExpLen.Mul(big8, adjExpLen)
  278. }
  279. adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
  280. // Calculate the gas cost of the operation
  281. gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
  282. if c.eip2565 {
  283. // EIP-2565 has three changes
  284. // 1. Different multComplexity (inlined here)
  285. // in EIP-2565 (https://eips.ethereum.org/EIPS/eip-2565):
  286. //
  287. // def mult_complexity(x):
  288. // ceiling(x/8)^2
  289. //
  290. //where is x is max(length_of_MODULUS, length_of_BASE)
  291. gas = gas.Add(gas, big7)
  292. gas = gas.Div(gas, big8)
  293. gas.Mul(gas, gas)
  294. gas.Mul(gas, math.BigMax(adjExpLen, big1))
  295. // 2. Different divisor (`GQUADDIVISOR`) (3)
  296. gas.Div(gas, big3)
  297. if gas.BitLen() > 64 {
  298. return math.MaxUint64
  299. }
  300. // 3. Minimum price of 200 gas
  301. if gas.Uint64() < 200 {
  302. return 200
  303. }
  304. return gas.Uint64()
  305. }
  306. gas = modexpMultComplexity(gas)
  307. gas.Mul(gas, math.BigMax(adjExpLen, big1))
  308. gas.Div(gas, big20)
  309. if gas.BitLen() > 64 {
  310. return math.MaxUint64
  311. }
  312. return gas.Uint64()
  313. }
  314. func (c *bigModExp) Run(input []byte) ([]byte, error) {
  315. var (
  316. baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64()
  317. expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64()
  318. modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64()
  319. )
  320. if len(input) > 96 {
  321. input = input[96:]
  322. } else {
  323. input = input[:0]
  324. }
  325. // Handle a special case when both the base and mod length is zero
  326. if baseLen == 0 && modLen == 0 {
  327. return []byte{}, nil
  328. }
  329. // Retrieve the operands and execute the exponentiation
  330. var (
  331. base = new(big.Int).SetBytes(getData(input, 0, baseLen))
  332. exp = new(big.Int).SetBytes(getData(input, baseLen, expLen))
  333. mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
  334. )
  335. if mod.BitLen() == 0 {
  336. // Modulo 0 is undefined, return zero
  337. return common.LeftPadBytes([]byte{}, int(modLen)), nil
  338. }
  339. return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
  340. }
  341. // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
  342. // returning it, or an error if the point is invalid.
  343. func newCurvePoint(blob []byte) (*bn256.G1, error) {
  344. p := new(bn256.G1)
  345. if _, err := p.Unmarshal(blob); err != nil {
  346. return nil, err
  347. }
  348. return p, nil
  349. }
  350. // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
  351. // returning it, or an error if the point is invalid.
  352. func newTwistPoint(blob []byte) (*bn256.G2, error) {
  353. p := new(bn256.G2)
  354. if _, err := p.Unmarshal(blob); err != nil {
  355. return nil, err
  356. }
  357. return p, nil
  358. }
  359. // runBn256Add implements the Bn256Add precompile, referenced by both
  360. // Byzantium and Istanbul operations.
  361. func runBn256Add(input []byte) ([]byte, error) {
  362. x, err := newCurvePoint(getData(input, 0, 64))
  363. if err != nil {
  364. return nil, err
  365. }
  366. y, err := newCurvePoint(getData(input, 64, 64))
  367. if err != nil {
  368. return nil, err
  369. }
  370. res := new(bn256.G1)
  371. res.Add(x, y)
  372. return res.Marshal(), nil
  373. }
  374. // bn256Add implements a native elliptic curve point addition conforming to
  375. // Istanbul consensus rules.
  376. type bn256AddIstanbul struct{}
  377. // RequiredGas returns the gas required to execute the pre-compiled contract.
  378. func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 {
  379. return params.Bn256AddGasIstanbul
  380. }
  381. func (c *bn256AddIstanbul) Run(input []byte) ([]byte, error) {
  382. return runBn256Add(input)
  383. }
  384. // bn256AddByzantium implements a native elliptic curve point addition
  385. // conforming to Byzantium consensus rules.
  386. type bn256AddByzantium struct{}
  387. // RequiredGas returns the gas required to execute the pre-compiled contract.
  388. func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 {
  389. return params.Bn256AddGasByzantium
  390. }
  391. func (c *bn256AddByzantium) Run(input []byte) ([]byte, error) {
  392. return runBn256Add(input)
  393. }
  394. // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by
  395. // both Byzantium and Istanbul operations.
  396. func runBn256ScalarMul(input []byte) ([]byte, error) {
  397. p, err := newCurvePoint(getData(input, 0, 64))
  398. if err != nil {
  399. return nil, err
  400. }
  401. res := new(bn256.G1)
  402. res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32)))
  403. return res.Marshal(), nil
  404. }
  405. // bn256ScalarMulIstanbul implements a native elliptic curve scalar
  406. // multiplication conforming to Istanbul consensus rules.
  407. type bn256ScalarMulIstanbul struct{}
  408. // RequiredGas returns the gas required to execute the pre-compiled contract.
  409. func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 {
  410. return params.Bn256ScalarMulGasIstanbul
  411. }
  412. func (c *bn256ScalarMulIstanbul) Run(input []byte) ([]byte, error) {
  413. return runBn256ScalarMul(input)
  414. }
  415. // bn256ScalarMulByzantium implements a native elliptic curve scalar
  416. // multiplication conforming to Byzantium consensus rules.
  417. type bn256ScalarMulByzantium struct{}
  418. // RequiredGas returns the gas required to execute the pre-compiled contract.
  419. func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 {
  420. return params.Bn256ScalarMulGasByzantium
  421. }
  422. func (c *bn256ScalarMulByzantium) Run(input []byte) ([]byte, error) {
  423. return runBn256ScalarMul(input)
  424. }
  425. var (
  426. // true32Byte is returned if the bn256 pairing check succeeds.
  427. 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}
  428. // false32Byte is returned if the bn256 pairing check fails.
  429. false32Byte = make([]byte, 32)
  430. // errBadPairingInput is returned if the bn256 pairing input is invalid.
  431. errBadPairingInput = errors.New("bad elliptic curve pairing size")
  432. )
  433. // runBn256Pairing implements the Bn256Pairing precompile, referenced by both
  434. // Byzantium and Istanbul operations.
  435. func runBn256Pairing(input []byte) ([]byte, error) {
  436. // Handle some corner cases cheaply
  437. if len(input)%192 > 0 {
  438. return nil, errBadPairingInput
  439. }
  440. // Convert the input into a set of coordinates
  441. var (
  442. cs []*bn256.G1
  443. ts []*bn256.G2
  444. )
  445. for i := 0; i < len(input); i += 192 {
  446. c, err := newCurvePoint(input[i : i+64])
  447. if err != nil {
  448. return nil, err
  449. }
  450. t, err := newTwistPoint(input[i+64 : i+192])
  451. if err != nil {
  452. return nil, err
  453. }
  454. cs = append(cs, c)
  455. ts = append(ts, t)
  456. }
  457. // Execute the pairing checks and return the results
  458. if bn256.PairingCheck(cs, ts) {
  459. return true32Byte, nil
  460. }
  461. return false32Byte, nil
  462. }
  463. // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve
  464. // conforming to Istanbul consensus rules.
  465. type bn256PairingIstanbul struct{}
  466. // RequiredGas returns the gas required to execute the pre-compiled contract.
  467. func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 {
  468. return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul
  469. }
  470. func (c *bn256PairingIstanbul) Run(input []byte) ([]byte, error) {
  471. return runBn256Pairing(input)
  472. }
  473. // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve
  474. // conforming to Byzantium consensus rules.
  475. type bn256PairingByzantium struct{}
  476. // RequiredGas returns the gas required to execute the pre-compiled contract.
  477. func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 {
  478. return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium
  479. }
  480. func (c *bn256PairingByzantium) Run(input []byte) ([]byte, error) {
  481. return runBn256Pairing(input)
  482. }
  483. type blake2F struct{}
  484. func (c *blake2F) RequiredGas(input []byte) uint64 {
  485. // If the input is malformed, we can't calculate the gas, return 0 and let the
  486. // actual call choke and fault.
  487. if len(input) != blake2FInputLength {
  488. return 0
  489. }
  490. return uint64(binary.BigEndian.Uint32(input[0:4]))
  491. }
  492. const (
  493. blake2FInputLength = 213
  494. blake2FFinalBlockBytes = byte(1)
  495. blake2FNonFinalBlockBytes = byte(0)
  496. )
  497. var (
  498. errBlake2FInvalidInputLength = errors.New("invalid input length")
  499. errBlake2FInvalidFinalFlag = errors.New("invalid final flag")
  500. )
  501. func (c *blake2F) Run(input []byte) ([]byte, error) {
  502. // Make sure the input is valid (correct length and final flag)
  503. if len(input) != blake2FInputLength {
  504. return nil, errBlake2FInvalidInputLength
  505. }
  506. if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes {
  507. return nil, errBlake2FInvalidFinalFlag
  508. }
  509. // Parse the input into the Blake2b call parameters
  510. var (
  511. rounds = binary.BigEndian.Uint32(input[0:4])
  512. final = (input[212] == blake2FFinalBlockBytes)
  513. h [8]uint64
  514. m [16]uint64
  515. t [2]uint64
  516. )
  517. for i := 0; i < 8; i++ {
  518. offset := 4 + i*8
  519. h[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
  520. }
  521. for i := 0; i < 16; i++ {
  522. offset := 68 + i*8
  523. m[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
  524. }
  525. t[0] = binary.LittleEndian.Uint64(input[196:204])
  526. t[1] = binary.LittleEndian.Uint64(input[204:212])
  527. // Execute the compression function, extract and return the result
  528. blake2b.F(&h, m, t, final, rounds)
  529. output := make([]byte, 64)
  530. for i := 0; i < 8; i++ {
  531. offset := i * 8
  532. binary.LittleEndian.PutUint64(output[offset:offset+8], h[i])
  533. }
  534. return output, nil
  535. }
  536. var (
  537. errBLS12381InvalidInputLength = errors.New("invalid input length")
  538. errBLS12381InvalidFieldElementTopBytes = errors.New("invalid field element top bytes")
  539. errBLS12381G1PointSubgroup = errors.New("g1 point is not on correct subgroup")
  540. errBLS12381G2PointSubgroup = errors.New("g2 point is not on correct subgroup")
  541. )
  542. // bls12381G1Add implements EIP-2537 G1Add precompile.
  543. type bls12381G1Add struct{}
  544. // RequiredGas returns the gas required to execute the pre-compiled contract.
  545. func (c *bls12381G1Add) RequiredGas(input []byte) uint64 {
  546. return params.Bls12381G1AddGas
  547. }
  548. func (c *bls12381G1Add) Run(input []byte) ([]byte, error) {
  549. // Implements EIP-2537 G1Add precompile.
  550. // > G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each).
  551. // > Output is an encoding of addition operation result - single G1 point (`128` bytes).
  552. if len(input) != 256 {
  553. return nil, errBLS12381InvalidInputLength
  554. }
  555. var err error
  556. var p0, p1 *bls12381.PointG1
  557. // Initialize G1
  558. g := bls12381.NewG1()
  559. // Decode G1 point p_0
  560. if p0, err = g.DecodePoint(input[:128]); err != nil {
  561. return nil, err
  562. }
  563. // Decode G1 point p_1
  564. if p1, err = g.DecodePoint(input[128:]); err != nil {
  565. return nil, err
  566. }
  567. // Compute r = p_0 + p_1
  568. r := g.New()
  569. g.Add(r, p0, p1)
  570. // Encode the G1 point result into 128 bytes
  571. return g.EncodePoint(r), nil
  572. }
  573. // bls12381G1Mul implements EIP-2537 G1Mul precompile.
  574. type bls12381G1Mul struct{}
  575. // RequiredGas returns the gas required to execute the pre-compiled contract.
  576. func (c *bls12381G1Mul) RequiredGas(input []byte) uint64 {
  577. return params.Bls12381G1MulGas
  578. }
  579. func (c *bls12381G1Mul) Run(input []byte) ([]byte, error) {
  580. // Implements EIP-2537 G1Mul precompile.
  581. // > G1 multiplication call expects `160` bytes as an input that is interpreted as byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes).
  582. // > Output is an encoding of multiplication operation result - single G1 point (`128` bytes).
  583. if len(input) != 160 {
  584. return nil, errBLS12381InvalidInputLength
  585. }
  586. var err error
  587. var p0 *bls12381.PointG1
  588. // Initialize G1
  589. g := bls12381.NewG1()
  590. // Decode G1 point
  591. if p0, err = g.DecodePoint(input[:128]); err != nil {
  592. return nil, err
  593. }
  594. // Decode scalar value
  595. e := new(big.Int).SetBytes(input[128:])
  596. // Compute r = e * p_0
  597. r := g.New()
  598. g.MulScalar(r, p0, e)
  599. // Encode the G1 point into 128 bytes
  600. return g.EncodePoint(r), nil
  601. }
  602. // bls12381G1MultiExp implements EIP-2537 G1MultiExp precompile.
  603. type bls12381G1MultiExp struct{}
  604. // RequiredGas returns the gas required to execute the pre-compiled contract.
  605. func (c *bls12381G1MultiExp) RequiredGas(input []byte) uint64 {
  606. // Calculate G1 point, scalar value pair length
  607. k := len(input) / 160
  608. if k == 0 {
  609. // Return 0 gas for small input length
  610. return 0
  611. }
  612. // Lookup discount value for G1 point, scalar value pair length
  613. var discount uint64
  614. if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen {
  615. discount = params.Bls12381MultiExpDiscountTable[k-1]
  616. } else {
  617. discount = params.Bls12381MultiExpDiscountTable[dLen-1]
  618. }
  619. // Calculate gas and return the result
  620. return (uint64(k) * params.Bls12381G1MulGas * discount) / 1000
  621. }
  622. func (c *bls12381G1MultiExp) Run(input []byte) ([]byte, error) {
  623. // Implements EIP-2537 G1MultiExp precompile.
  624. // G1 multiplication call expects `160*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes).
  625. // Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes).
  626. k := len(input) / 160
  627. if len(input) == 0 || len(input)%160 != 0 {
  628. return nil, errBLS12381InvalidInputLength
  629. }
  630. var err error
  631. points := make([]*bls12381.PointG1, k)
  632. scalars := make([]*big.Int, k)
  633. // Initialize G1
  634. g := bls12381.NewG1()
  635. // Decode point scalar pairs
  636. for i := 0; i < k; i++ {
  637. off := 160 * i
  638. t0, t1, t2 := off, off+128, off+160
  639. // Decode G1 point
  640. if points[i], err = g.DecodePoint(input[t0:t1]); err != nil {
  641. return nil, err
  642. }
  643. // Decode scalar value
  644. scalars[i] = new(big.Int).SetBytes(input[t1:t2])
  645. }
  646. // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1)
  647. r := g.New()
  648. g.MultiExp(r, points, scalars)
  649. // Encode the G1 point to 128 bytes
  650. return g.EncodePoint(r), nil
  651. }
  652. // bls12381G2Add implements EIP-2537 G2Add precompile.
  653. type bls12381G2Add struct{}
  654. // RequiredGas returns the gas required to execute the pre-compiled contract.
  655. func (c *bls12381G2Add) RequiredGas(input []byte) uint64 {
  656. return params.Bls12381G2AddGas
  657. }
  658. func (c *bls12381G2Add) Run(input []byte) ([]byte, error) {
  659. // Implements EIP-2537 G2Add precompile.
  660. // > G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each).
  661. // > Output is an encoding of addition operation result - single G2 point (`256` bytes).
  662. if len(input) != 512 {
  663. return nil, errBLS12381InvalidInputLength
  664. }
  665. var err error
  666. var p0, p1 *bls12381.PointG2
  667. // Initialize G2
  668. g := bls12381.NewG2()
  669. r := g.New()
  670. // Decode G2 point p_0
  671. if p0, err = g.DecodePoint(input[:256]); err != nil {
  672. return nil, err
  673. }
  674. // Decode G2 point p_1
  675. if p1, err = g.DecodePoint(input[256:]); err != nil {
  676. return nil, err
  677. }
  678. // Compute r = p_0 + p_1
  679. g.Add(r, p0, p1)
  680. // Encode the G2 point into 256 bytes
  681. return g.EncodePoint(r), nil
  682. }
  683. // bls12381G2Mul implements EIP-2537 G2Mul precompile.
  684. type bls12381G2Mul struct{}
  685. // RequiredGas returns the gas required to execute the pre-compiled contract.
  686. func (c *bls12381G2Mul) RequiredGas(input []byte) uint64 {
  687. return params.Bls12381G2MulGas
  688. }
  689. func (c *bls12381G2Mul) Run(input []byte) ([]byte, error) {
  690. // Implements EIP-2537 G2MUL precompile logic.
  691. // > G2 multiplication call expects `288` bytes as an input that is interpreted as byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes).
  692. // > Output is an encoding of multiplication operation result - single G2 point (`256` bytes).
  693. if len(input) != 288 {
  694. return nil, errBLS12381InvalidInputLength
  695. }
  696. var err error
  697. var p0 *bls12381.PointG2
  698. // Initialize G2
  699. g := bls12381.NewG2()
  700. // Decode G2 point
  701. if p0, err = g.DecodePoint(input[:256]); err != nil {
  702. return nil, err
  703. }
  704. // Decode scalar value
  705. e := new(big.Int).SetBytes(input[256:])
  706. // Compute r = e * p_0
  707. r := g.New()
  708. g.MulScalar(r, p0, e)
  709. // Encode the G2 point into 256 bytes
  710. return g.EncodePoint(r), nil
  711. }
  712. // bls12381G2MultiExp implements EIP-2537 G2MultiExp precompile.
  713. type bls12381G2MultiExp struct{}
  714. // RequiredGas returns the gas required to execute the pre-compiled contract.
  715. func (c *bls12381G2MultiExp) RequiredGas(input []byte) uint64 {
  716. // Calculate G2 point, scalar value pair length
  717. k := len(input) / 288
  718. if k == 0 {
  719. // Return 0 gas for small input length
  720. return 0
  721. }
  722. // Lookup discount value for G2 point, scalar value pair length
  723. var discount uint64
  724. if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen {
  725. discount = params.Bls12381MultiExpDiscountTable[k-1]
  726. } else {
  727. discount = params.Bls12381MultiExpDiscountTable[dLen-1]
  728. }
  729. // Calculate gas and return the result
  730. return (uint64(k) * params.Bls12381G2MulGas * discount) / 1000
  731. }
  732. func (c *bls12381G2MultiExp) Run(input []byte) ([]byte, error) {
  733. // Implements EIP-2537 G2MultiExp precompile logic
  734. // > G2 multiplication call expects `288*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes).
  735. // > Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes).
  736. k := len(input) / 288
  737. if len(input) == 0 || len(input)%288 != 0 {
  738. return nil, errBLS12381InvalidInputLength
  739. }
  740. var err error
  741. points := make([]*bls12381.PointG2, k)
  742. scalars := make([]*big.Int, k)
  743. // Initialize G2
  744. g := bls12381.NewG2()
  745. // Decode point scalar pairs
  746. for i := 0; i < k; i++ {
  747. off := 288 * i
  748. t0, t1, t2 := off, off+256, off+288
  749. // Decode G1 point
  750. if points[i], err = g.DecodePoint(input[t0:t1]); err != nil {
  751. return nil, err
  752. }
  753. // Decode scalar value
  754. scalars[i] = new(big.Int).SetBytes(input[t1:t2])
  755. }
  756. // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1)
  757. r := g.New()
  758. g.MultiExp(r, points, scalars)
  759. // Encode the G2 point to 256 bytes.
  760. return g.EncodePoint(r), nil
  761. }
  762. // bls12381Pairing implements EIP-2537 Pairing precompile.
  763. type bls12381Pairing struct{}
  764. // RequiredGas returns the gas required to execute the pre-compiled contract.
  765. func (c *bls12381Pairing) RequiredGas(input []byte) uint64 {
  766. return params.Bls12381PairingBaseGas + uint64(len(input)/384)*params.Bls12381PairingPerPairGas
  767. }
  768. func (c *bls12381Pairing) Run(input []byte) ([]byte, error) {
  769. // Implements EIP-2537 Pairing precompile logic.
  770. // > Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure:
  771. // > - `128` bytes of G1 point encoding
  772. // > - `256` bytes of G2 point encoding
  773. // > Output is a `32` bytes where last single byte is `0x01` if pairing result is equal to multiplicative identity in a pairing target field and `0x00` otherwise
  774. // > (which is equivalent of Big Endian encoding of Solidity values `uint256(1)` and `uin256(0)` respectively).
  775. k := len(input) / 384
  776. if len(input) == 0 || len(input)%384 != 0 {
  777. return nil, errBLS12381InvalidInputLength
  778. }
  779. // Initialize BLS12-381 pairing engine
  780. e := bls12381.NewPairingEngine()
  781. g1, g2 := e.G1, e.G2
  782. // Decode pairs
  783. for i := 0; i < k; i++ {
  784. off := 384 * i
  785. t0, t1, t2 := off, off+128, off+384
  786. // Decode G1 point
  787. p1, err := g1.DecodePoint(input[t0:t1])
  788. if err != nil {
  789. return nil, err
  790. }
  791. // Decode G2 point
  792. p2, err := g2.DecodePoint(input[t1:t2])
  793. if err != nil {
  794. return nil, err
  795. }
  796. // 'point is on curve' check already done,
  797. // Here we need to apply subgroup checks.
  798. if !g1.InCorrectSubgroup(p1) {
  799. return nil, errBLS12381G1PointSubgroup
  800. }
  801. if !g2.InCorrectSubgroup(p2) {
  802. return nil, errBLS12381G2PointSubgroup
  803. }
  804. // Update pairing engine with G1 and G2 ponits
  805. e.AddPair(p1, p2)
  806. }
  807. // Prepare 32 byte output
  808. out := make([]byte, 32)
  809. // Compute pairing and set the result
  810. if e.Check() {
  811. out[31] = 1
  812. }
  813. return out, nil
  814. }
  815. // decodeBLS12381FieldElement decodes BLS12-381 elliptic curve field element.
  816. // Removes top 16 bytes of 64 byte input.
  817. func decodeBLS12381FieldElement(in []byte) ([]byte, error) {
  818. if len(in) != 64 {
  819. return nil, errors.New("invalid field element length")
  820. }
  821. // check top bytes
  822. for i := 0; i < 16; i++ {
  823. if in[i] != byte(0x00) {
  824. return nil, errBLS12381InvalidFieldElementTopBytes
  825. }
  826. }
  827. out := make([]byte, 48)
  828. copy(out[:], in[16:])
  829. return out, nil
  830. }
  831. // bls12381MapG1 implements EIP-2537 MapG1 precompile.
  832. type bls12381MapG1 struct{}
  833. // RequiredGas returns the gas required to execute the pre-compiled contract.
  834. func (c *bls12381MapG1) RequiredGas(input []byte) uint64 {
  835. return params.Bls12381MapG1Gas
  836. }
  837. func (c *bls12381MapG1) Run(input []byte) ([]byte, error) {
  838. // Implements EIP-2537 Map_To_G1 precompile.
  839. // > Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field.
  840. // > Output of this call is `128` bytes and is G1 point following respective encoding rules.
  841. if len(input) != 64 {
  842. return nil, errBLS12381InvalidInputLength
  843. }
  844. // Decode input field element
  845. fe, err := decodeBLS12381FieldElement(input)
  846. if err != nil {
  847. return nil, err
  848. }
  849. // Initialize G1
  850. g := bls12381.NewG1()
  851. // Compute mapping
  852. r, err := g.MapToCurve(fe)
  853. if err != nil {
  854. return nil, err
  855. }
  856. // Encode the G1 point to 128 bytes
  857. return g.EncodePoint(r), nil
  858. }
  859. // bls12381MapG2 implements EIP-2537 MapG2 precompile.
  860. type bls12381MapG2 struct{}
  861. // RequiredGas returns the gas required to execute the pre-compiled contract.
  862. func (c *bls12381MapG2) RequiredGas(input []byte) uint64 {
  863. return params.Bls12381MapG2Gas
  864. }
  865. func (c *bls12381MapG2) Run(input []byte) ([]byte, error) {
  866. // Implements EIP-2537 Map_FP2_TO_G2 precompile logic.
  867. // > Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field.
  868. // > Output of this call is `256` bytes and is G2 point following respective encoding rules.
  869. if len(input) != 128 {
  870. return nil, errBLS12381InvalidInputLength
  871. }
  872. // Decode input field element
  873. fe := make([]byte, 96)
  874. c0, err := decodeBLS12381FieldElement(input[:64])
  875. if err != nil {
  876. return nil, err
  877. }
  878. copy(fe[48:], c0)
  879. c1, err := decodeBLS12381FieldElement(input[64:])
  880. if err != nil {
  881. return nil, err
  882. }
  883. copy(fe[:48], c1)
  884. // Initialize G2
  885. g := bls12381.NewG2()
  886. // Compute mapping
  887. r, err := g.MapToCurve(fe)
  888. if err != nil {
  889. return nil, err
  890. }
  891. // Encode the G2 point to 256 bytes
  892. return g.EncodePoint(r), nil
  893. }