contracts.go 33 KB

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