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