contracts.go 33 KB

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