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