contracts.go 32 KB

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