contracts.go 30 KB

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