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