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