contracts.go 33 KB

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