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