contracts.go 30 KB

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