contracts.go 33 KB

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