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