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