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