contracts.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. var discount uint64
  544. if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen {
  545. discount = params.Bls12381MultiExpDiscountTable[k-1]
  546. } else {
  547. discount = params.Bls12381MultiExpDiscountTable[dLen-1]
  548. }
  549. // Calculate gas and return the result
  550. return (uint64(k) * params.Bls12381G1MulGas * discount) / 1000
  551. }
  552. func (c *bls12381G1MultiExp) Run(input []byte) ([]byte, error) {
  553. // Implements EIP-2537 G1MultiExp precompile.
  554. // 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).
  555. // Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes).
  556. k := len(input) / 160
  557. if len(input) == 0 || len(input)%160 != 0 {
  558. return nil, errBLS12381InvalidInputLength
  559. }
  560. var err error
  561. points := make([]*bls12381.PointG1, k)
  562. scalars := make([]*big.Int, k)
  563. // Initialize G1
  564. g := bls12381.NewG1()
  565. // Decode point scalar pairs
  566. for i := 0; i < k; i++ {
  567. off := 160 * i
  568. t0, t1, t2 := off, off+128, off+160
  569. // Decode G1 point
  570. if points[i], err = g.DecodePoint(input[t0:t1]); err != nil {
  571. return nil, err
  572. }
  573. // Decode scalar value
  574. scalars[i] = new(big.Int).SetBytes(input[t1:t2])
  575. }
  576. // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1)
  577. r := g.New()
  578. g.MultiExp(r, points, scalars)
  579. // Encode the G1 point to 128 bytes
  580. return g.EncodePoint(r), nil
  581. }
  582. // bls12381G2Add implements EIP-2537 G2Add precompile.
  583. type bls12381G2Add struct{}
  584. // RequiredGas returns the gas required to execute the pre-compiled contract.
  585. func (c *bls12381G2Add) RequiredGas(input []byte) uint64 {
  586. return params.Bls12381G2AddGas
  587. }
  588. func (c *bls12381G2Add) Run(input []byte) ([]byte, error) {
  589. // Implements EIP-2537 G2Add precompile.
  590. // > G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each).
  591. // > Output is an encoding of addition operation result - single G2 point (`256` bytes).
  592. if len(input) != 512 {
  593. return nil, errBLS12381InvalidInputLength
  594. }
  595. var err error
  596. var p0, p1 *bls12381.PointG2
  597. // Initialize G2
  598. g := bls12381.NewG2()
  599. r := g.New()
  600. // Decode G2 point p_0
  601. if p0, err = g.DecodePoint(input[:256]); err != nil {
  602. return nil, err
  603. }
  604. // Decode G2 point p_1
  605. if p1, err = g.DecodePoint(input[256:]); err != nil {
  606. return nil, err
  607. }
  608. // Compute r = p_0 + p_1
  609. g.Add(r, p0, p1)
  610. // Encode the G2 point into 256 bytes
  611. return g.EncodePoint(r), nil
  612. }
  613. // bls12381G2Mul implements EIP-2537 G2Mul precompile.
  614. type bls12381G2Mul struct{}
  615. // RequiredGas returns the gas required to execute the pre-compiled contract.
  616. func (c *bls12381G2Mul) RequiredGas(input []byte) uint64 {
  617. return params.Bls12381G2MulGas
  618. }
  619. func (c *bls12381G2Mul) Run(input []byte) ([]byte, error) {
  620. // Implements EIP-2537 G2MUL precompile logic.
  621. // > 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).
  622. // > Output is an encoding of multiplication operation result - single G2 point (`256` bytes).
  623. if len(input) != 288 {
  624. return nil, errBLS12381InvalidInputLength
  625. }
  626. var err error
  627. var p0 *bls12381.PointG2
  628. // Initialize G2
  629. g := bls12381.NewG2()
  630. // Decode G2 point
  631. if p0, err = g.DecodePoint(input[:256]); err != nil {
  632. return nil, err
  633. }
  634. // Decode scalar value
  635. e := new(big.Int).SetBytes(input[256:])
  636. // Compute r = e * p_0
  637. r := g.New()
  638. g.MulScalar(r, p0, e)
  639. // Encode the G2 point into 256 bytes
  640. return g.EncodePoint(r), nil
  641. }
  642. // bls12381G2MultiExp implements EIP-2537 G2MultiExp precompile.
  643. type bls12381G2MultiExp struct{}
  644. // RequiredGas returns the gas required to execute the pre-compiled contract.
  645. func (c *bls12381G2MultiExp) RequiredGas(input []byte) uint64 {
  646. // Calculate G2 point, scalar value pair length
  647. k := len(input) / 288
  648. if k == 0 {
  649. // Return 0 gas for small input length
  650. return 0
  651. }
  652. // Lookup discount value for G2 point, scalar value pair length
  653. var discount uint64
  654. if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen {
  655. discount = params.Bls12381MultiExpDiscountTable[k-1]
  656. } else {
  657. discount = params.Bls12381MultiExpDiscountTable[dLen-1]
  658. }
  659. // Calculate gas and return the result
  660. return (uint64(k) * params.Bls12381G2MulGas * discount) / 1000
  661. }
  662. func (c *bls12381G2MultiExp) Run(input []byte) ([]byte, error) {
  663. // Implements EIP-2537 G2MultiExp precompile logic
  664. // > 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).
  665. // > Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes).
  666. k := len(input) / 288
  667. if len(input) == 0 || len(input)%288 != 0 {
  668. return nil, errBLS12381InvalidInputLength
  669. }
  670. var err error
  671. points := make([]*bls12381.PointG2, k)
  672. scalars := make([]*big.Int, k)
  673. // Initialize G2
  674. g := bls12381.NewG2()
  675. // Decode point scalar pairs
  676. for i := 0; i < k; i++ {
  677. off := 288 * i
  678. t0, t1, t2 := off, off+256, off+288
  679. // Decode G1 point
  680. if points[i], err = g.DecodePoint(input[t0:t1]); err != nil {
  681. return nil, err
  682. }
  683. // Decode scalar value
  684. scalars[i] = new(big.Int).SetBytes(input[t1:t2])
  685. }
  686. // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1)
  687. r := g.New()
  688. g.MultiExp(r, points, scalars)
  689. // Encode the G2 point to 256 bytes.
  690. return g.EncodePoint(r), nil
  691. }
  692. // bls12381Pairing implements EIP-2537 Pairing precompile.
  693. type bls12381Pairing struct{}
  694. // RequiredGas returns the gas required to execute the pre-compiled contract.
  695. func (c *bls12381Pairing) RequiredGas(input []byte) uint64 {
  696. return params.Bls12381PairingBaseGas + uint64(len(input)/384)*params.Bls12381PairingPerPairGas
  697. }
  698. func (c *bls12381Pairing) Run(input []byte) ([]byte, error) {
  699. // Implements EIP-2537 Pairing precompile logic.
  700. // > Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure:
  701. // > - `128` bytes of G1 point encoding
  702. // > - `256` bytes of G2 point encoding
  703. // > 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
  704. // > (which is equivalent of Big Endian encoding of Solidity values `uint256(1)` and `uin256(0)` respectively).
  705. k := len(input) / 384
  706. if len(input) == 0 || len(input)%384 != 0 {
  707. return nil, errBLS12381InvalidInputLength
  708. }
  709. // Initialize BLS12-381 pairing engine
  710. e := bls12381.NewPairingEngine()
  711. g1, g2 := e.G1, e.G2
  712. // Decode pairs
  713. for i := 0; i < k; i++ {
  714. off := 384 * i
  715. t0, t1, t2 := off, off+128, off+384
  716. // Decode G1 point
  717. p1, err := g1.DecodePoint(input[t0:t1])
  718. if err != nil {
  719. return nil, err
  720. }
  721. // Decode G2 point
  722. p2, err := g2.DecodePoint(input[t1:t2])
  723. if err != nil {
  724. return nil, err
  725. }
  726. // 'point is on curve' check already done,
  727. // Here we need to apply subgroup checks.
  728. if !g1.InCorrectSubgroup(p1) {
  729. return nil, errBLS12381G1PointSubgroup
  730. }
  731. if !g2.InCorrectSubgroup(p2) {
  732. return nil, errBLS12381G2PointSubgroup
  733. }
  734. // Update pairing engine with G1 and G2 ponits
  735. e.AddPair(p1, p2)
  736. }
  737. // Prepare 32 byte output
  738. out := make([]byte, 32)
  739. // Compute pairing and set the result
  740. if e.Check() {
  741. out[31] = 1
  742. }
  743. return out, nil
  744. }
  745. // decodeBLS12381FieldElement decodes BLS12-381 elliptic curve field element.
  746. // Removes top 16 bytes of 64 byte input.
  747. func decodeBLS12381FieldElement(in []byte) ([]byte, error) {
  748. if len(in) != 64 {
  749. return nil, errors.New("invalid field element length")
  750. }
  751. // check top bytes
  752. for i := 0; i < 16; i++ {
  753. if in[i] != byte(0x00) {
  754. return nil, errBLS12381InvalidFieldElementTopBytes
  755. }
  756. }
  757. out := make([]byte, 48)
  758. copy(out[:], in[16:])
  759. return out, nil
  760. }
  761. // bls12381MapG1 implements EIP-2537 MapG1 precompile.
  762. type bls12381MapG1 struct{}
  763. // RequiredGas returns the gas required to execute the pre-compiled contract.
  764. func (c *bls12381MapG1) RequiredGas(input []byte) uint64 {
  765. return params.Bls12381MapG1Gas
  766. }
  767. func (c *bls12381MapG1) Run(input []byte) ([]byte, error) {
  768. // Implements EIP-2537 Map_To_G1 precompile.
  769. // > Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field.
  770. // > Output of this call is `128` bytes and is G1 point following respective encoding rules.
  771. if len(input) != 64 {
  772. return nil, errBLS12381InvalidInputLength
  773. }
  774. // Decode input field element
  775. fe, err := decodeBLS12381FieldElement(input)
  776. if err != nil {
  777. return nil, err
  778. }
  779. // Initialize G1
  780. g := bls12381.NewG1()
  781. // Compute mapping
  782. r, err := g.MapToCurve(fe)
  783. if err != nil {
  784. return nil, err
  785. }
  786. // Encode the G1 point to 128 bytes
  787. return g.EncodePoint(r), nil
  788. }
  789. // bls12381MapG2 implements EIP-2537 MapG2 precompile.
  790. type bls12381MapG2 struct{}
  791. // RequiredGas returns the gas required to execute the pre-compiled contract.
  792. func (c *bls12381MapG2) RequiredGas(input []byte) uint64 {
  793. return params.Bls12381MapG2Gas
  794. }
  795. func (c *bls12381MapG2) Run(input []byte) ([]byte, error) {
  796. // Implements EIP-2537 Map_FP2_TO_G2 precompile logic.
  797. // > Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field.
  798. // > Output of this call is `256` bytes and is G2 point following respective encoding rules.
  799. if len(input) != 128 {
  800. return nil, errBLS12381InvalidInputLength
  801. }
  802. // Decode input field element
  803. fe := make([]byte, 96)
  804. c0, err := decodeBLS12381FieldElement(input[:64])
  805. if err != nil {
  806. return nil, err
  807. }
  808. copy(fe[48:], c0)
  809. c1, err := decodeBLS12381FieldElement(input[64:])
  810. if err != nil {
  811. return nil, err
  812. }
  813. copy(fe[:48], c1)
  814. // Initialize G2
  815. g := bls12381.NewG2()
  816. // Compute mapping
  817. r, err := g.MapToCurve(fe)
  818. if err != nil {
  819. return nil, err
  820. }
  821. // Encode the G2 point to 256 bytes
  822. return g.EncodePoint(r), nil
  823. }