contracts.go 34 KB

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