contracts.go 33 KB

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