github.com/MikyChow/arbitrum-go-ethereum@v0.0.0-20230306102812-078da49636de/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/MikyChow/arbitrum-go-ethereum/common" 26 "github.com/MikyChow/arbitrum-go-ethereum/common/math" 27 "github.com/MikyChow/arbitrum-go-ethereum/crypto" 28 "github.com/MikyChow/arbitrum-go-ethereum/crypto/blake2b" 29 "github.com/MikyChow/arbitrum-go-ethereum/crypto/bls12381" 30 "github.com/MikyChow/arbitrum-go-ethereum/crypto/bn256" 31 "github.com/MikyChow/arbitrum-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 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 // 289 // if x <= 64: return x ** 2 290 // elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 291 // else: return x ** 2 // 16 + 480 * x - 199680 292 // 293 // where is x is max(length_of_MODULUS, length_of_BASE) 294 func modexpMultComplexity(x *big.Int) *big.Int { 295 switch { 296 case x.Cmp(big64) <= 0: 297 x.Mul(x, x) // x ** 2 298 case x.Cmp(big1024) <= 0: 299 // (x ** 2 // 4 ) + ( 96 * x - 3072) 300 x = new(big.Int).Add( 301 new(big.Int).Div(new(big.Int).Mul(x, x), big4), 302 new(big.Int).Sub(new(big.Int).Mul(big96, x), big3072), 303 ) 304 default: 305 // (x ** 2 // 16) + (480 * x - 199680) 306 x = new(big.Int).Add( 307 new(big.Int).Div(new(big.Int).Mul(x, x), big16), 308 new(big.Int).Sub(new(big.Int).Mul(big480, x), big199680), 309 ) 310 } 311 return x 312 } 313 314 // RequiredGas returns the gas required to execute the pre-compiled contract. 315 func (c *bigModExp) RequiredGas(input []byte) uint64 { 316 var ( 317 baseLen = new(big.Int).SetBytes(getData(input, 0, 32)) 318 expLen = new(big.Int).SetBytes(getData(input, 32, 32)) 319 modLen = new(big.Int).SetBytes(getData(input, 64, 32)) 320 ) 321 if len(input) > 96 { 322 input = input[96:] 323 } else { 324 input = input[:0] 325 } 326 // Retrieve the head 32 bytes of exp for the adjusted exponent length 327 var expHead *big.Int 328 if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 { 329 expHead = new(big.Int) 330 } else { 331 if expLen.Cmp(big32) > 0 { 332 expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32)) 333 } else { 334 expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64())) 335 } 336 } 337 // Calculate the adjusted exponent length 338 var msb int 339 if bitlen := expHead.BitLen(); bitlen > 0 { 340 msb = bitlen - 1 341 } 342 adjExpLen := new(big.Int) 343 if expLen.Cmp(big32) > 0 { 344 adjExpLen.Sub(expLen, big32) 345 adjExpLen.Mul(big8, adjExpLen) 346 } 347 adjExpLen.Add(adjExpLen, big.NewInt(int64(msb))) 348 // Calculate the gas cost of the operation 349 gas := new(big.Int).Set(math.BigMax(modLen, baseLen)) 350 if c.eip2565 { 351 // EIP-2565 has three changes 352 // 1. Different multComplexity (inlined here) 353 // in EIP-2565 (https://eips.ethereum.org/EIPS/eip-2565): 354 // 355 // def mult_complexity(x): 356 // ceiling(x/8)^2 357 // 358 //where is x is max(length_of_MODULUS, length_of_BASE) 359 gas = gas.Add(gas, big7) 360 gas = gas.Div(gas, big8) 361 gas.Mul(gas, gas) 362 363 gas.Mul(gas, math.BigMax(adjExpLen, big1)) 364 // 2. Different divisor (`GQUADDIVISOR`) (3) 365 gas.Div(gas, big3) 366 if gas.BitLen() > 64 { 367 return math.MaxUint64 368 } 369 // 3. Minimum price of 200 gas 370 if gas.Uint64() < 200 { 371 return 200 372 } 373 return gas.Uint64() 374 } 375 gas = modexpMultComplexity(gas) 376 gas.Mul(gas, math.BigMax(adjExpLen, big1)) 377 gas.Div(gas, big20) 378 379 if gas.BitLen() > 64 { 380 return math.MaxUint64 381 } 382 return gas.Uint64() 383 } 384 385 func (c *bigModExp) Run(input []byte) ([]byte, error) { 386 var ( 387 baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64() 388 expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64() 389 modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64() 390 ) 391 if len(input) > 96 { 392 input = input[96:] 393 } else { 394 input = input[:0] 395 } 396 // Handle a special case when both the base and mod length is zero 397 if baseLen == 0 && modLen == 0 { 398 return []byte{}, nil 399 } 400 // Retrieve the operands and execute the exponentiation 401 var ( 402 base = new(big.Int).SetBytes(getData(input, 0, baseLen)) 403 exp = new(big.Int).SetBytes(getData(input, baseLen, expLen)) 404 mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen)) 405 ) 406 if mod.BitLen() == 0 { 407 // Modulo 0 is undefined, return zero 408 return common.LeftPadBytes([]byte{}, int(modLen)), nil 409 } 410 return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil 411 } 412 413 // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point, 414 // returning it, or an error if the point is invalid. 415 func newCurvePoint(blob []byte) (*bn256.G1, error) { 416 p := new(bn256.G1) 417 if _, err := p.Unmarshal(blob); err != nil { 418 return nil, err 419 } 420 return p, nil 421 } 422 423 // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point, 424 // returning it, or an error if the point is invalid. 425 func newTwistPoint(blob []byte) (*bn256.G2, error) { 426 p := new(bn256.G2) 427 if _, err := p.Unmarshal(blob); err != nil { 428 return nil, err 429 } 430 return p, nil 431 } 432 433 // runBn256Add implements the Bn256Add precompile, referenced by both 434 // Byzantium and Istanbul operations. 435 func runBn256Add(input []byte) ([]byte, error) { 436 x, err := newCurvePoint(getData(input, 0, 64)) 437 if err != nil { 438 return nil, err 439 } 440 y, err := newCurvePoint(getData(input, 64, 64)) 441 if err != nil { 442 return nil, err 443 } 444 res := new(bn256.G1) 445 res.Add(x, y) 446 return res.Marshal(), nil 447 } 448 449 // bn256Add implements a native elliptic curve point addition conforming to 450 // Istanbul consensus rules. 451 type bn256AddIstanbul struct{} 452 453 // RequiredGas returns the gas required to execute the pre-compiled contract. 454 func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 { 455 return params.Bn256AddGasIstanbul 456 } 457 458 func (c *bn256AddIstanbul) Run(input []byte) ([]byte, error) { 459 return runBn256Add(input) 460 } 461 462 // bn256AddByzantium implements a native elliptic curve point addition 463 // conforming to Byzantium consensus rules. 464 type bn256AddByzantium struct{} 465 466 // RequiredGas returns the gas required to execute the pre-compiled contract. 467 func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 { 468 return params.Bn256AddGasByzantium 469 } 470 471 func (c *bn256AddByzantium) Run(input []byte) ([]byte, error) { 472 return runBn256Add(input) 473 } 474 475 // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by 476 // both Byzantium and Istanbul operations. 477 func runBn256ScalarMul(input []byte) ([]byte, error) { 478 p, err := newCurvePoint(getData(input, 0, 64)) 479 if err != nil { 480 return nil, err 481 } 482 res := new(bn256.G1) 483 res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32))) 484 return res.Marshal(), nil 485 } 486 487 // bn256ScalarMulIstanbul implements a native elliptic curve scalar 488 // multiplication conforming to Istanbul consensus rules. 489 type bn256ScalarMulIstanbul struct{} 490 491 // RequiredGas returns the gas required to execute the pre-compiled contract. 492 func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 { 493 return params.Bn256ScalarMulGasIstanbul 494 } 495 496 func (c *bn256ScalarMulIstanbul) Run(input []byte) ([]byte, error) { 497 return runBn256ScalarMul(input) 498 } 499 500 // bn256ScalarMulByzantium implements a native elliptic curve scalar 501 // multiplication conforming to Byzantium consensus rules. 502 type bn256ScalarMulByzantium struct{} 503 504 // RequiredGas returns the gas required to execute the pre-compiled contract. 505 func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 { 506 return params.Bn256ScalarMulGasByzantium 507 } 508 509 func (c *bn256ScalarMulByzantium) Run(input []byte) ([]byte, error) { 510 return runBn256ScalarMul(input) 511 } 512 513 var ( 514 // true32Byte is returned if the bn256 pairing check succeeds. 515 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} 516 517 // false32Byte is returned if the bn256 pairing check fails. 518 false32Byte = make([]byte, 32) 519 520 // errBadPairingInput is returned if the bn256 pairing input is invalid. 521 errBadPairingInput = errors.New("bad elliptic curve pairing size") 522 ) 523 524 // runBn256Pairing implements the Bn256Pairing precompile, referenced by both 525 // Byzantium and Istanbul operations. 526 func runBn256Pairing(input []byte) ([]byte, error) { 527 // Handle some corner cases cheaply 528 if len(input)%192 > 0 { 529 return nil, errBadPairingInput 530 } 531 // Convert the input into a set of coordinates 532 var ( 533 cs []*bn256.G1 534 ts []*bn256.G2 535 ) 536 for i := 0; i < len(input); i += 192 { 537 c, err := newCurvePoint(input[i : i+64]) 538 if err != nil { 539 return nil, err 540 } 541 t, err := newTwistPoint(input[i+64 : i+192]) 542 if err != nil { 543 return nil, err 544 } 545 cs = append(cs, c) 546 ts = append(ts, t) 547 } 548 // Execute the pairing checks and return the results 549 if bn256.PairingCheck(cs, ts) { 550 return true32Byte, nil 551 } 552 return false32Byte, nil 553 } 554 555 // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve 556 // conforming to Istanbul consensus rules. 557 type bn256PairingIstanbul struct{} 558 559 // RequiredGas returns the gas required to execute the pre-compiled contract. 560 func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 { 561 return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul 562 } 563 564 func (c *bn256PairingIstanbul) Run(input []byte) ([]byte, error) { 565 return runBn256Pairing(input) 566 } 567 568 // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve 569 // conforming to Byzantium consensus rules. 570 type bn256PairingByzantium struct{} 571 572 // RequiredGas returns the gas required to execute the pre-compiled contract. 573 func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 { 574 return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium 575 } 576 577 func (c *bn256PairingByzantium) Run(input []byte) ([]byte, error) { 578 return runBn256Pairing(input) 579 } 580 581 type blake2F struct{} 582 583 func (c *blake2F) RequiredGas(input []byte) uint64 { 584 // If the input is malformed, we can't calculate the gas, return 0 and let the 585 // actual call choke and fault. 586 if len(input) != blake2FInputLength { 587 return 0 588 } 589 return uint64(binary.BigEndian.Uint32(input[0:4])) 590 } 591 592 const ( 593 blake2FInputLength = 213 594 blake2FFinalBlockBytes = byte(1) 595 blake2FNonFinalBlockBytes = byte(0) 596 ) 597 598 var ( 599 errBlake2FInvalidInputLength = errors.New("invalid input length") 600 errBlake2FInvalidFinalFlag = errors.New("invalid final flag") 601 ) 602 603 func (c *blake2F) Run(input []byte) ([]byte, error) { 604 // Make sure the input is valid (correct length and final flag) 605 if len(input) != blake2FInputLength { 606 return nil, errBlake2FInvalidInputLength 607 } 608 if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes { 609 return nil, errBlake2FInvalidFinalFlag 610 } 611 // Parse the input into the Blake2b call parameters 612 var ( 613 rounds = binary.BigEndian.Uint32(input[0:4]) 614 final = input[212] == blake2FFinalBlockBytes 615 616 h [8]uint64 617 m [16]uint64 618 t [2]uint64 619 ) 620 for i := 0; i < 8; i++ { 621 offset := 4 + i*8 622 h[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) 623 } 624 for i := 0; i < 16; i++ { 625 offset := 68 + i*8 626 m[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) 627 } 628 t[0] = binary.LittleEndian.Uint64(input[196:204]) 629 t[1] = binary.LittleEndian.Uint64(input[204:212]) 630 631 // Execute the compression function, extract and return the result 632 blake2b.F(&h, m, t, final, rounds) 633 634 output := make([]byte, 64) 635 for i := 0; i < 8; i++ { 636 offset := i * 8 637 binary.LittleEndian.PutUint64(output[offset:offset+8], h[i]) 638 } 639 return output, nil 640 } 641 642 var ( 643 errBLS12381InvalidInputLength = errors.New("invalid input length") 644 errBLS12381InvalidFieldElementTopBytes = errors.New("invalid field element top bytes") 645 errBLS12381G1PointSubgroup = errors.New("g1 point is not on correct subgroup") 646 errBLS12381G2PointSubgroup = errors.New("g2 point is not on correct subgroup") 647 ) 648 649 // bls12381G1Add implements EIP-2537 G1Add precompile. 650 type bls12381G1Add struct{} 651 652 // RequiredGas returns the gas required to execute the pre-compiled contract. 653 func (c *bls12381G1Add) RequiredGas(input []byte) uint64 { 654 return params.Bls12381G1AddGas 655 } 656 657 func (c *bls12381G1Add) Run(input []byte) ([]byte, error) { 658 // Implements EIP-2537 G1Add precompile. 659 // > G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each). 660 // > Output is an encoding of addition operation result - single G1 point (`128` bytes). 661 if len(input) != 256 { 662 return nil, errBLS12381InvalidInputLength 663 } 664 var err error 665 var p0, p1 *bls12381.PointG1 666 667 // Initialize G1 668 g := bls12381.NewG1() 669 670 // Decode G1 point p_0 671 if p0, err = g.DecodePoint(input[:128]); err != nil { 672 return nil, err 673 } 674 // Decode G1 point p_1 675 if p1, err = g.DecodePoint(input[128:]); err != nil { 676 return nil, err 677 } 678 679 // Compute r = p_0 + p_1 680 r := g.New() 681 g.Add(r, p0, p1) 682 683 // Encode the G1 point result into 128 bytes 684 return g.EncodePoint(r), nil 685 } 686 687 // bls12381G1Mul implements EIP-2537 G1Mul precompile. 688 type bls12381G1Mul struct{} 689 690 // RequiredGas returns the gas required to execute the pre-compiled contract. 691 func (c *bls12381G1Mul) RequiredGas(input []byte) uint64 { 692 return params.Bls12381G1MulGas 693 } 694 695 func (c *bls12381G1Mul) Run(input []byte) ([]byte, error) { 696 // Implements EIP-2537 G1Mul precompile. 697 // > 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). 698 // > Output is an encoding of multiplication operation result - single G1 point (`128` bytes). 699 if len(input) != 160 { 700 return nil, errBLS12381InvalidInputLength 701 } 702 var err error 703 var p0 *bls12381.PointG1 704 705 // Initialize G1 706 g := bls12381.NewG1() 707 708 // Decode G1 point 709 if p0, err = g.DecodePoint(input[:128]); err != nil { 710 return nil, err 711 } 712 // Decode scalar value 713 e := new(big.Int).SetBytes(input[128:]) 714 715 // Compute r = e * p_0 716 r := g.New() 717 g.MulScalar(r, p0, e) 718 719 // Encode the G1 point into 128 bytes 720 return g.EncodePoint(r), nil 721 } 722 723 // bls12381G1MultiExp implements EIP-2537 G1MultiExp precompile. 724 type bls12381G1MultiExp struct{} 725 726 // RequiredGas returns the gas required to execute the pre-compiled contract. 727 func (c *bls12381G1MultiExp) RequiredGas(input []byte) uint64 { 728 // Calculate G1 point, scalar value pair length 729 k := len(input) / 160 730 if k == 0 { 731 // Return 0 gas for small input length 732 return 0 733 } 734 // Lookup discount value for G1 point, scalar value pair length 735 var discount uint64 736 if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen { 737 discount = params.Bls12381MultiExpDiscountTable[k-1] 738 } else { 739 discount = params.Bls12381MultiExpDiscountTable[dLen-1] 740 } 741 // Calculate gas and return the result 742 return (uint64(k) * params.Bls12381G1MulGas * discount) / 1000 743 } 744 745 func (c *bls12381G1MultiExp) Run(input []byte) ([]byte, error) { 746 // Implements EIP-2537 G1MultiExp precompile. 747 // 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). 748 // Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes). 749 k := len(input) / 160 750 if len(input) == 0 || len(input)%160 != 0 { 751 return nil, errBLS12381InvalidInputLength 752 } 753 var err error 754 points := make([]*bls12381.PointG1, k) 755 scalars := make([]*big.Int, k) 756 757 // Initialize G1 758 g := bls12381.NewG1() 759 760 // Decode point scalar pairs 761 for i := 0; i < k; i++ { 762 off := 160 * i 763 t0, t1, t2 := off, off+128, off+160 764 // Decode G1 point 765 if points[i], err = g.DecodePoint(input[t0:t1]); err != nil { 766 return nil, err 767 } 768 // Decode scalar value 769 scalars[i] = new(big.Int).SetBytes(input[t1:t2]) 770 } 771 772 // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1) 773 r := g.New() 774 g.MultiExp(r, points, scalars) 775 776 // Encode the G1 point to 128 bytes 777 return g.EncodePoint(r), nil 778 } 779 780 // bls12381G2Add implements EIP-2537 G2Add precompile. 781 type bls12381G2Add struct{} 782 783 // RequiredGas returns the gas required to execute the pre-compiled contract. 784 func (c *bls12381G2Add) RequiredGas(input []byte) uint64 { 785 return params.Bls12381G2AddGas 786 } 787 788 func (c *bls12381G2Add) Run(input []byte) ([]byte, error) { 789 // Implements EIP-2537 G2Add precompile. 790 // > G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). 791 // > Output is an encoding of addition operation result - single G2 point (`256` bytes). 792 if len(input) != 512 { 793 return nil, errBLS12381InvalidInputLength 794 } 795 var err error 796 var p0, p1 *bls12381.PointG2 797 798 // Initialize G2 799 g := bls12381.NewG2() 800 r := g.New() 801 802 // Decode G2 point p_0 803 if p0, err = g.DecodePoint(input[:256]); err != nil { 804 return nil, err 805 } 806 // Decode G2 point p_1 807 if p1, err = g.DecodePoint(input[256:]); err != nil { 808 return nil, err 809 } 810 811 // Compute r = p_0 + p_1 812 g.Add(r, p0, p1) 813 814 // Encode the G2 point into 256 bytes 815 return g.EncodePoint(r), nil 816 } 817 818 // bls12381G2Mul implements EIP-2537 G2Mul precompile. 819 type bls12381G2Mul struct{} 820 821 // RequiredGas returns the gas required to execute the pre-compiled contract. 822 func (c *bls12381G2Mul) RequiredGas(input []byte) uint64 { 823 return params.Bls12381G2MulGas 824 } 825 826 func (c *bls12381G2Mul) Run(input []byte) ([]byte, error) { 827 // Implements EIP-2537 G2MUL precompile logic. 828 // > 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). 829 // > Output is an encoding of multiplication operation result - single G2 point (`256` bytes). 830 if len(input) != 288 { 831 return nil, errBLS12381InvalidInputLength 832 } 833 var err error 834 var p0 *bls12381.PointG2 835 836 // Initialize G2 837 g := bls12381.NewG2() 838 839 // Decode G2 point 840 if p0, err = g.DecodePoint(input[:256]); err != nil { 841 return nil, err 842 } 843 // Decode scalar value 844 e := new(big.Int).SetBytes(input[256:]) 845 846 // Compute r = e * p_0 847 r := g.New() 848 g.MulScalar(r, p0, e) 849 850 // Encode the G2 point into 256 bytes 851 return g.EncodePoint(r), nil 852 } 853 854 // bls12381G2MultiExp implements EIP-2537 G2MultiExp precompile. 855 type bls12381G2MultiExp struct{} 856 857 // RequiredGas returns the gas required to execute the pre-compiled contract. 858 func (c *bls12381G2MultiExp) RequiredGas(input []byte) uint64 { 859 // Calculate G2 point, scalar value pair length 860 k := len(input) / 288 861 if k == 0 { 862 // Return 0 gas for small input length 863 return 0 864 } 865 // Lookup discount value for G2 point, scalar value pair length 866 var discount uint64 867 if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen { 868 discount = params.Bls12381MultiExpDiscountTable[k-1] 869 } else { 870 discount = params.Bls12381MultiExpDiscountTable[dLen-1] 871 } 872 // Calculate gas and return the result 873 return (uint64(k) * params.Bls12381G2MulGas * discount) / 1000 874 } 875 876 func (c *bls12381G2MultiExp) Run(input []byte) ([]byte, error) { 877 // Implements EIP-2537 G2MultiExp precompile logic 878 // > 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). 879 // > Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes). 880 k := len(input) / 288 881 if len(input) == 0 || len(input)%288 != 0 { 882 return nil, errBLS12381InvalidInputLength 883 } 884 var err error 885 points := make([]*bls12381.PointG2, k) 886 scalars := make([]*big.Int, k) 887 888 // Initialize G2 889 g := bls12381.NewG2() 890 891 // Decode point scalar pairs 892 for i := 0; i < k; i++ { 893 off := 288 * i 894 t0, t1, t2 := off, off+256, off+288 895 // Decode G1 point 896 if points[i], err = g.DecodePoint(input[t0:t1]); err != nil { 897 return nil, err 898 } 899 // Decode scalar value 900 scalars[i] = new(big.Int).SetBytes(input[t1:t2]) 901 } 902 903 // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1) 904 r := g.New() 905 g.MultiExp(r, points, scalars) 906 907 // Encode the G2 point to 256 bytes. 908 return g.EncodePoint(r), nil 909 } 910 911 // bls12381Pairing implements EIP-2537 Pairing precompile. 912 type bls12381Pairing struct{} 913 914 // RequiredGas returns the gas required to execute the pre-compiled contract. 915 func (c *bls12381Pairing) RequiredGas(input []byte) uint64 { 916 return params.Bls12381PairingBaseGas + uint64(len(input)/384)*params.Bls12381PairingPerPairGas 917 } 918 919 func (c *bls12381Pairing) Run(input []byte) ([]byte, error) { 920 // Implements EIP-2537 Pairing precompile logic. 921 // > Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: 922 // > - `128` bytes of G1 point encoding 923 // > - `256` bytes of G2 point encoding 924 // > 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 925 // > (which is equivalent of Big Endian encoding of Solidity values `uint256(1)` and `uin256(0)` respectively). 926 k := len(input) / 384 927 if len(input) == 0 || len(input)%384 != 0 { 928 return nil, errBLS12381InvalidInputLength 929 } 930 931 // Initialize BLS12-381 pairing engine 932 e := bls12381.NewPairingEngine() 933 g1, g2 := e.G1, e.G2 934 935 // Decode pairs 936 for i := 0; i < k; i++ { 937 off := 384 * i 938 t0, t1, t2 := off, off+128, off+384 939 940 // Decode G1 point 941 p1, err := g1.DecodePoint(input[t0:t1]) 942 if err != nil { 943 return nil, err 944 } 945 // Decode G2 point 946 p2, err := g2.DecodePoint(input[t1:t2]) 947 if err != nil { 948 return nil, err 949 } 950 951 // 'point is on curve' check already done, 952 // Here we need to apply subgroup checks. 953 if !g1.InCorrectSubgroup(p1) { 954 return nil, errBLS12381G1PointSubgroup 955 } 956 if !g2.InCorrectSubgroup(p2) { 957 return nil, errBLS12381G2PointSubgroup 958 } 959 960 // Update pairing engine with G1 and G2 ponits 961 e.AddPair(p1, p2) 962 } 963 // Prepare 32 byte output 964 out := make([]byte, 32) 965 966 // Compute pairing and set the result 967 if e.Check() { 968 out[31] = 1 969 } 970 return out, nil 971 } 972 973 // decodeBLS12381FieldElement decodes BLS12-381 elliptic curve field element. 974 // Removes top 16 bytes of 64 byte input. 975 func decodeBLS12381FieldElement(in []byte) ([]byte, error) { 976 if len(in) != 64 { 977 return nil, errors.New("invalid field element length") 978 } 979 // check top bytes 980 for i := 0; i < 16; i++ { 981 if in[i] != byte(0x00) { 982 return nil, errBLS12381InvalidFieldElementTopBytes 983 } 984 } 985 out := make([]byte, 48) 986 copy(out[:], in[16:]) 987 return out, nil 988 } 989 990 // bls12381MapG1 implements EIP-2537 MapG1 precompile. 991 type bls12381MapG1 struct{} 992 993 // RequiredGas returns the gas required to execute the pre-compiled contract. 994 func (c *bls12381MapG1) RequiredGas(input []byte) uint64 { 995 return params.Bls12381MapG1Gas 996 } 997 998 func (c *bls12381MapG1) Run(input []byte) ([]byte, error) { 999 // Implements EIP-2537 Map_To_G1 precompile. 1000 // > Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field. 1001 // > Output of this call is `128` bytes and is G1 point following respective encoding rules. 1002 if len(input) != 64 { 1003 return nil, errBLS12381InvalidInputLength 1004 } 1005 1006 // Decode input field element 1007 fe, err := decodeBLS12381FieldElement(input) 1008 if err != nil { 1009 return nil, err 1010 } 1011 1012 // Initialize G1 1013 g := bls12381.NewG1() 1014 1015 // Compute mapping 1016 r, err := g.MapToCurve(fe) 1017 if err != nil { 1018 return nil, err 1019 } 1020 1021 // Encode the G1 point to 128 bytes 1022 return g.EncodePoint(r), nil 1023 } 1024 1025 // bls12381MapG2 implements EIP-2537 MapG2 precompile. 1026 type bls12381MapG2 struct{} 1027 1028 // RequiredGas returns the gas required to execute the pre-compiled contract. 1029 func (c *bls12381MapG2) RequiredGas(input []byte) uint64 { 1030 return params.Bls12381MapG2Gas 1031 } 1032 1033 func (c *bls12381MapG2) Run(input []byte) ([]byte, error) { 1034 // Implements EIP-2537 Map_FP2_TO_G2 precompile logic. 1035 // > Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field. 1036 // > Output of this call is `256` bytes and is G2 point following respective encoding rules. 1037 if len(input) != 128 { 1038 return nil, errBLS12381InvalidInputLength 1039 } 1040 1041 // Decode input field element 1042 fe := make([]byte, 96) 1043 c0, err := decodeBLS12381FieldElement(input[:64]) 1044 if err != nil { 1045 return nil, err 1046 } 1047 copy(fe[48:], c0) 1048 c1, err := decodeBLS12381FieldElement(input[64:]) 1049 if err != nil { 1050 return nil, err 1051 } 1052 copy(fe[:48], c1) 1053 1054 // Initialize G2 1055 g := bls12381.NewG2() 1056 1057 // Compute mapping 1058 r, err := g.MapToCurve(fe) 1059 if err != nil { 1060 return nil, err 1061 } 1062 1063 // Encode the G2 point to 256 bytes 1064 return g.EncodePoint(r), nil 1065 }