github.com/klaytn/klaytn@v1.10.2/blockchain/vm/contracts.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2014 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from core/vm/contracts.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package vm 22 23 import ( 24 "crypto/ecdsa" 25 "crypto/sha256" 26 "encoding/binary" 27 "errors" 28 "math/big" 29 "strconv" 30 31 "github.com/klaytn/klaytn/api/debug" 32 "github.com/klaytn/klaytn/blockchain/types" 33 "github.com/klaytn/klaytn/blockchain/types/accountkey" 34 "github.com/klaytn/klaytn/common" 35 "github.com/klaytn/klaytn/common/math" 36 "github.com/klaytn/klaytn/crypto" 37 "github.com/klaytn/klaytn/crypto/blake2b" 38 "github.com/klaytn/klaytn/crypto/bn256" 39 "github.com/klaytn/klaytn/kerrors" 40 "github.com/klaytn/klaytn/log" 41 "github.com/klaytn/klaytn/params" 42 "golang.org/x/crypto/ripemd160" 43 ) 44 45 var logger = log.NewModuleLogger(log.VM) 46 47 var ( 48 errInputTooShort = errors.New("input length is too short") 49 errWrongSignatureLength = errors.New("wrong signature length") 50 ) 51 52 // PrecompiledContract is the basic interface for native Go contracts. The implementation 53 // requires a deterministic gas count based on the input size of the Run method of the 54 // contract. 55 // If you want more information about Klaytn's precompiled contracts, 56 // please refer https://docs.klaytn.com/smart-contract/precompiled-contracts 57 type PrecompiledContract interface { 58 // GetRequiredGasAndComputationCost returns the gas and computation cost 59 // required to execute the precompiled contract. 60 GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) 61 62 // Run runs the precompiled contract 63 // contract, evm is only exists in klaytn, those are not used in go-ethereum 64 Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) 65 } 66 67 // PrecompiledContractsByzantiumCompatible contains the default set of pre-compiled Klaytn 68 // contracts based on Ethereum Byzantium. 69 var PrecompiledContractsByzantiumCompatible = 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}): &bn256AddByzantium{}, 76 common.BytesToAddress([]byte{7}): &bn256ScalarMulByzantium{}, 77 common.BytesToAddress([]byte{8}): &bn256PairingByzantium{}, 78 common.BytesToAddress([]byte{9}): &vmLog{}, 79 common.BytesToAddress([]byte{10}): &feePayer{}, 80 common.BytesToAddress([]byte{11}): &validateSender{}, 81 } 82 83 // DO NOT USE 0x3FD, 0x3FE, 0x3FF ADDRESSES BEFORE ISTANBUL CHANGE ACTIVATED. 84 85 // PrecompiledContractsIstanbulCompatible contains the default set of pre-compiled Klaytn 86 // contracts based on Ethereum Istanbul. 87 var PrecompiledContractsIstanbulCompatible = 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: false}, 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 common.BytesToAddress([]byte{3, 253}): &vmLog{}, 98 common.BytesToAddress([]byte{3, 254}): &feePayer{}, 99 common.BytesToAddress([]byte{3, 255}): &validateSender{}, 100 } 101 102 // PrecompiledContractsKore contains the default set of pre-compiled Klaytn 103 // contracts based on Ethereum Berlin. 104 var PrecompiledContractsKore = map[common.Address]PrecompiledContract{ 105 common.BytesToAddress([]byte{1}): &ecrecover{}, 106 common.BytesToAddress([]byte{2}): &sha256hash{}, 107 common.BytesToAddress([]byte{3}): &ripemd160hash{}, 108 common.BytesToAddress([]byte{4}): &dataCopy{}, 109 common.BytesToAddress([]byte{5}): &bigModExp{eip2565: true}, 110 common.BytesToAddress([]byte{6}): &bn256AddIstanbul{}, 111 common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{}, 112 common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{}, 113 common.BytesToAddress([]byte{9}): &blake2F{}, 114 common.BytesToAddress([]byte{3, 253}): &vmLog{}, 115 common.BytesToAddress([]byte{3, 254}): &feePayer{}, 116 common.BytesToAddress([]byte{3, 255}): &validateSender{}, 117 } 118 119 var ( 120 PrecompiledAddressesIstanbulCompatible []common.Address 121 PrecompiledAddressesByzantiumCompatible []common.Address 122 ) 123 124 func init() { 125 for k := range PrecompiledContractsByzantiumCompatible { 126 PrecompiledAddressesByzantiumCompatible = append(PrecompiledAddressesByzantiumCompatible, k) 127 } 128 129 // After istanbulCompatible hf, need to support for vmversion0 contracts, too. 130 // VmVersion0 contracts are deployed before istanbulCompatible and they use byzantiumCompatible precompiled contracts. 131 // VmVersion0 contracts are the contracts deployed before istanbulCompatible hf. 132 for k := range PrecompiledContractsIstanbulCompatible { 133 PrecompiledAddressesIstanbulCompatible = append(PrecompiledAddressesIstanbulCompatible, k) 134 } 135 PrecompiledAddressesIstanbulCompatible = append(PrecompiledAddressesIstanbulCompatible, 136 []common.Address{common.BytesToAddress([]byte{10}), common.BytesToAddress([]byte{11})}...) 137 } 138 139 // ActivePrecompiles returns the precompiles enabled with the current configuration. 140 func ActivePrecompiles(rules params.Rules) []common.Address { 141 switch { 142 case rules.IsIstanbul: 143 return PrecompiledAddressesIstanbulCompatible 144 default: 145 return PrecompiledAddressesByzantiumCompatible 146 } 147 } 148 149 // RunPrecompiledContract runs and evaluates the output of a precompiled contract. 150 func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract, evm *EVM) (ret []byte, computationCost uint64, err error) { 151 gas, computationCost := p.GetRequiredGasAndComputationCost(input) 152 if contract.UseGas(gas) { 153 ret, err = p.Run(input, contract, evm) 154 return ret, computationCost, err 155 } 156 return nil, computationCost, kerrors.ErrOutOfGas 157 } 158 159 // ECRECOVER implemented as a native contract. 160 type ecrecover struct{} 161 162 func (c *ecrecover) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 163 return params.EcrecoverGas, params.EcrecoverComputationCost 164 } 165 166 func (c *ecrecover) Run(input []byte, contract *Contract, evm *EVM) ([]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 // GetRequiredGasAndComputationCost returns the gas required to execute the pre-compiled contract 201 // and the computation cost of the precompiled 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) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 206 n32Bytes := uint64(len(input)+31) / 32 207 208 return n32Bytes*params.Sha256PerWordGas + params.Sha256BaseGas, 209 n32Bytes*params.Sha256PerWordComputationCost + params.Sha256BaseComputationCost 210 } 211 212 func (c *sha256hash) Run(input []byte, contract *Contract, evm *EVM) ([]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 // GetRequiredGasAndComputationCost returns the gas required to execute the pre-compiled contract 221 // and the computation cost of the precompiled contract. 222 // 223 // This method does not require any overflow checking as the input size gas costs 224 // required for anything significant is so high it's impossible to pay for. 225 func (c *ripemd160hash) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 226 n32Bytes := uint64(len(input)+31) / 32 227 228 return n32Bytes*params.Ripemd160PerWordGas + params.Ripemd160BaseGas, 229 n32Bytes*params.Ripemd160PerWordComputationCost + params.Ripemd160BaseComputationCost 230 } 231 232 func (c *ripemd160hash) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 233 ripemd := ripemd160.New() 234 ripemd.Write(input) 235 return common.LeftPadBytes(ripemd.Sum(nil), 32), nil 236 } 237 238 // data copy implemented as a native contract. 239 type dataCopy struct{} 240 241 // GetRequiredGasAndComputationCost returns the gas required to execute the pre-compiled contract 242 // and the computation cost of the precompiled contract. 243 // 244 // This method does not require any overflow checking as the input size gas costs 245 // required for anything significant is so high it's impossible to pay for. 246 func (c *dataCopy) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 247 n32Bytes := uint64(len(input)+31) / 32 248 return n32Bytes*params.IdentityPerWordGas + params.IdentityBaseGas, 249 n32Bytes*params.IdentityPerWordComputationCost + params.IdentityBaseComputationCost 250 } 251 252 func (c *dataCopy) Run(in []byte, contract *Contract, evm *EVM) ([]byte, error) { 253 return in, nil 254 } 255 256 // bigModExp implements a native big integer exponential modular operation. 257 type bigModExp struct { 258 eip2565 bool 259 } 260 261 var ( 262 big1 = big.NewInt(1) 263 big3 = big.NewInt(3) 264 big4 = big.NewInt(4) 265 big7 = big.NewInt(7) 266 big8 = big.NewInt(8) 267 big16 = big.NewInt(16) 268 big20 = big.NewInt(20) 269 big32 = big.NewInt(32) 270 big64 = big.NewInt(64) 271 big96 = big.NewInt(96) 272 big480 = big.NewInt(480) 273 big1024 = big.NewInt(1024) 274 big3072 = big.NewInt(3072) 275 big199680 = big.NewInt(199680) 276 ) 277 278 // modexpMultComplexity implements bigModexp multComplexity formula, as defined in EIP-198 279 // 280 // def mult_complexity(x): 281 // if x <= 64: return x ** 2 282 // elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 283 // else: return x ** 2 // 16 + 480 * x - 199680 284 // 285 // where is x is max(length_of_MODULUS, length_of_BASE) 286 func modexpMultComplexity(x *big.Int) *big.Int { 287 switch { 288 case x.Cmp(big64) <= 0: 289 x.Mul(x, x) // x ** 2 290 case x.Cmp(big1024) <= 0: 291 // (x ** 2 // 4 ) + ( 96 * x - 3072) 292 x = new(big.Int).Add( 293 new(big.Int).Div(new(big.Int).Mul(x, x), big4), 294 new(big.Int).Sub(new(big.Int).Mul(big96, x), big3072), 295 ) 296 default: 297 // (x ** 2 // 16) + (480 * x - 199680) 298 x = new(big.Int).Add( 299 new(big.Int).Div(new(big.Int).Mul(x, x), big16), 300 new(big.Int).Sub(new(big.Int).Mul(big480, x), big199680), 301 ) 302 } 303 return x 304 } 305 306 // GetRequiredGasAndComputationCost returns the gas required to execute the pre-compiled contract 307 // and the computation cost of the precompiled contract. 308 func (c *bigModExp) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 309 var ( 310 baseLen = new(big.Int).SetBytes(getData(input, 0, 32)) 311 expLen = new(big.Int).SetBytes(getData(input, 32, 32)) 312 modLen = new(big.Int).SetBytes(getData(input, 64, 32)) 313 ) 314 if len(input) > 96 { 315 input = input[96:] 316 } else { 317 input = input[:0] 318 } 319 // Retrieve the head 32 bytes of exp for the adjusted exponent length 320 var expHead *big.Int 321 if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 { 322 expHead = new(big.Int) 323 } else { 324 if expLen.Cmp(big32) > 0 { 325 expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32)) 326 } else { 327 expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64())) 328 } 329 } 330 // Calculate the adjusted exponent length 331 var msb int 332 if bitlen := expHead.BitLen(); bitlen > 0 { 333 msb = bitlen - 1 334 } 335 adjExpLen := new(big.Int) 336 if expLen.Cmp(big32) > 0 { 337 adjExpLen.Sub(expLen, big32) 338 adjExpLen.Mul(big8, adjExpLen) 339 } 340 adjExpLen.Add(adjExpLen, big.NewInt(int64(msb))) 341 342 // Calculate the gas cost of the operation 343 gas := new(big.Int).Set(math.BigMax(modLen, baseLen)) 344 if c.eip2565 { 345 // EIP-2565 has three changes 346 // 1. Different multComplexity (inlined here) 347 // in EIP-2565 (https://eips.ethereum.org/EIPS/eip-2565): 348 // 349 // def mult_complexity(x): 350 // ceiling(x/8)^2 351 // 352 //where is x is max(length_of_MODULUS, length_of_BASE) 353 gas = gas.Add(gas, big7) 354 gas = gas.Div(gas, big8) 355 gas.Mul(gas, gas) 356 357 gas.Mul(gas, math.BigMax(adjExpLen, big1)) 358 // 2. Different divisor (`GQUADDIVISOR`) (3) 359 gas.Div(gas, big3) 360 if gas.BitLen() > 64 { 361 return math.MaxUint64, math.MaxUint64 362 } 363 // 3. Minimum price of 200 gas 364 if gas.Uint64() < 200 { 365 return 200, (200 / 100) + params.BigModExpBaseComputationCost 366 } 367 return gas.Uint64(), (gas.Uint64() / 100) + params.BigModExpBaseComputationCost 368 } 369 gas = modexpMultComplexity(gas) 370 gas.Mul(gas, math.BigMax(adjExpLen, big1)) 371 gas.Div(gas, big20) 372 373 if gas.BitLen() > 64 { 374 return math.MaxUint64, math.MaxUint64 375 } 376 return gas.Uint64(), (gas.Uint64() / 100) + params.BigModExpBaseComputationCost 377 } 378 379 func (c *bigModExp) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 380 var ( 381 baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64() 382 expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64() 383 modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64() 384 ) 385 if len(input) > 96 { 386 input = input[96:] 387 } else { 388 input = input[:0] 389 } 390 // Handle a special case when both the base and mod length is zero 391 if baseLen == 0 && modLen == 0 { 392 return []byte{}, nil 393 } 394 // Retrieve the operands and execute the exponentiation 395 var ( 396 base = new(big.Int).SetBytes(getData(input, 0, baseLen)) 397 exp = new(big.Int).SetBytes(getData(input, baseLen, expLen)) 398 mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen)) 399 ) 400 if mod.BitLen() == 0 { 401 // Modulo 0 is undefined, return zero 402 return common.LeftPadBytes([]byte{}, int(modLen)), nil 403 } 404 return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil 405 } 406 407 // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point, 408 // returning it, or an error if the point is invalid. 409 func newCurvePoint(blob []byte) (*bn256.G1, error) { 410 p := new(bn256.G1) 411 if _, err := p.Unmarshal(blob); err != nil { 412 return nil, err 413 } 414 return p, nil 415 } 416 417 // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point, 418 // returning it, or an error if the point is invalid. 419 func newTwistPoint(blob []byte) (*bn256.G2, error) { 420 p := new(bn256.G2) 421 if _, err := p.Unmarshal(blob); err != nil { 422 return nil, err 423 } 424 return p, nil 425 } 426 427 // runBn256Add implements the Bn256Add precompile, referenced by both 428 // Byzantium and Istanbul operations. 429 func runBn256Add(input []byte) ([]byte, error) { 430 x, err := newCurvePoint(getData(input, 0, 64)) 431 if err != nil { 432 return nil, err 433 } 434 y, err := newCurvePoint(getData(input, 64, 64)) 435 if err != nil { 436 return nil, err 437 } 438 res := new(bn256.G1) 439 res.Add(x, y) 440 return res.Marshal(), nil 441 } 442 443 // bn256Add implements a native elliptic curve point addition conforming to 444 // Istanbul consensus rules. 445 type bn256AddIstanbul struct{} 446 447 func (c *bn256AddIstanbul) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 448 return params.Bn256AddGasIstanbul, params.Bn256AddComputationCost 449 } 450 451 func (c *bn256AddIstanbul) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 452 return runBn256Add(input) 453 } 454 455 // bn256AddByzantium implements a native elliptic curve point addition 456 // conforming to Byzantium consensus rules. 457 type bn256AddByzantium struct{} 458 459 func (c *bn256AddByzantium) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 460 return params.Bn256AddGasByzantium, params.Bn256AddComputationCost 461 } 462 463 func (c *bn256AddByzantium) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 464 return runBn256Add(input) 465 } 466 467 // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by 468 // both Constantionple and Istanbul operations. 469 func runBn256ScalarMul(input []byte) ([]byte, error) { 470 p, err := newCurvePoint(getData(input, 0, 64)) 471 if err != nil { 472 return nil, err 473 } 474 res := new(bn256.G1) 475 res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32))) 476 return res.Marshal(), nil 477 } 478 479 // bn256ScalarMulIstanbul implements a native elliptic curve scalar 480 // multiplication conforming to Istanbul consensus rules. 481 type bn256ScalarMulIstanbul struct{} 482 483 func (c *bn256ScalarMulIstanbul) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 484 return params.Bn256ScalarMulGasIstanbul, params.Bn256ScalarMulComputationCost 485 } 486 487 func (c *bn256ScalarMulIstanbul) Run(input []byte, contract *Contract, evm *EVM) ([]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 func (c *bn256ScalarMulByzantium) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 496 return params.Bn256ScalarMulGasByzantium, params.Bn256ScalarMulComputationCost 497 } 498 499 func (c *bn256ScalarMulByzantium) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 500 return runBn256ScalarMul(input) 501 } 502 503 var ( 504 // true32Byte is returned if the bn256 pairing check succeeds. 505 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} 506 507 // false32Byte is returned if the bn256 pairing check fails. 508 false32Byte = make([]byte, 32) 509 510 // errBadPairingInput is returned if the bn256 pairing input is invalid. 511 errBadPairingInput = errors.New("bad elliptic curve pairing size") 512 ) 513 514 // runBn256Pairing implements the Bn256Pairing precompile, referenced by both 515 // Byzantium and Istanbul operations. 516 func runBn256Pairing(input []byte) ([]byte, error) { 517 // Handle some corner cases cheaply 518 if len(input)%192 > 0 { 519 return nil, errBadPairingInput 520 } 521 // Convert the input into a set of coordinates 522 var ( 523 cs []*bn256.G1 524 ts []*bn256.G2 525 ) 526 for i := 0; i < len(input); i += 192 { 527 c, err := newCurvePoint(input[i : i+64]) 528 if err != nil { 529 return nil, err 530 } 531 t, err := newTwistPoint(input[i+64 : i+192]) 532 if err != nil { 533 return nil, err 534 } 535 cs = append(cs, c) 536 ts = append(ts, t) 537 } 538 // Execute the pairing checks and return the results 539 if bn256.PairingCheck(cs, ts) { 540 return true32Byte, nil 541 } 542 return false32Byte, nil 543 } 544 545 // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve 546 // conforming to Istanbul consensus rules. 547 type bn256PairingIstanbul struct{} 548 549 func (c *bn256PairingIstanbul) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 550 numParings := uint64(len(input) / 192) 551 return params.Bn256PairingBaseGasIstanbul + numParings*params.Bn256PairingPerPointGasIstanbul, 552 params.Bn256ParingBaseComputationCost + numParings*params.Bn256ParingPerPointComputationCost 553 } 554 555 func (c *bn256PairingIstanbul) Run(input []byte, contract *Contract, evm *EVM) ([]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 func (c *bn256PairingByzantium) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 564 numParings := uint64(len(input) / 192) 565 return params.Bn256PairingBaseGasByzantium + numParings*params.Bn256PairingPerPointGasByzantium, 566 params.Bn256ParingBaseComputationCost + numParings*params.Bn256ParingPerPointComputationCost 567 } 568 569 func (c *bn256PairingByzantium) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 570 return runBn256Pairing(input) 571 } 572 573 type blake2F struct{} 574 575 const ( 576 blake2FInputLength = 213 577 blake2FFinalBlockBytes = byte(1) 578 blake2FNonFinalBlockBytes = byte(0) 579 ) 580 581 var ( 582 errBlake2FInvalidInputLength = errors.New("invalid input length") 583 errBlake2FInvalidFinalFlag = errors.New("invalid final flag") 584 ) 585 586 func (c *blake2F) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 587 // If the input is malformed, we can't calculate the gas, return 0 and let the 588 // actual call choke and fault. 589 if len(input) != blake2FInputLength { 590 return 0, 0 591 } 592 gas := uint64(binary.BigEndian.Uint32(input[0:4])) 593 return gas, params.Blake2bBaseComputationCost + params.Blake2bScaleComputationCost*gas 594 } 595 596 func (c *blake2F) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 597 // Make sure the input is valid (correct length and final flag) 598 if len(input) != blake2FInputLength { 599 return nil, errBlake2FInvalidInputLength 600 } 601 if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes { 602 return nil, errBlake2FInvalidFinalFlag 603 } 604 // Parse the input into the Blake2b call parameters 605 var ( 606 rounds = binary.BigEndian.Uint32(input[0:4]) 607 final = (input[212] == blake2FFinalBlockBytes) 608 609 h [8]uint64 610 m [16]uint64 611 t [2]uint64 612 ) 613 for i := 0; i < 8; i++ { 614 offset := 4 + i*8 615 h[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) 616 } 617 for i := 0; i < 16; i++ { 618 offset := 68 + i*8 619 m[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) 620 } 621 t[0] = binary.LittleEndian.Uint64(input[196:204]) 622 t[1] = binary.LittleEndian.Uint64(input[204:212]) 623 624 // Execute the compression function, extract and return the result 625 blake2b.F(&h, m, t, final, rounds) 626 627 output := make([]byte, 64) 628 for i := 0; i < 8; i++ { 629 offset := i * 8 630 binary.LittleEndian.PutUint64(output[offset:offset+8], h[i]) 631 } 632 return output, nil 633 } 634 635 // vmLog implemented as a native contract. 636 type vmLog struct{} 637 638 // GetRequiredGasAndComputationCost returns the gas required to execute the pre-compiled contract 639 // and the computation cost of the precompiled contract. 640 func (c *vmLog) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 641 l := uint64(len(input)) 642 return l*params.VMLogPerByteGas + params.VMLogBaseGas, 643 l*params.VMLogPerByteComputationCost + params.VMLogBaseComputationCost 644 } 645 646 // Runs the vmLog contract. 647 func (c *vmLog) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 648 if (params.VMLogTarget & params.VMLogToFile) != 0 { 649 prefix := "tx=" + evm.StateDB.GetTxHash().String() + " caller=" + contract.CallerAddress.String() + " msg=" 650 debug.Handler.WriteVMLog(prefix + string(input)) 651 } 652 if (params.VMLogTarget & params.VMLogToStdout) != 0 { 653 logger.Debug("vmlog", "tx", evm.StateDB.GetTxHash().String(), 654 "caller", contract.CallerAddress.String(), "msg", strconv.QuoteToASCII(string(input))) 655 } 656 return nil, nil 657 } 658 659 type feePayer struct{} 660 661 func (c *feePayer) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 662 return params.FeePayerGas, params.FeePayerComputationCost 663 } 664 665 func (c *feePayer) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 666 return contract.FeePayerAddress.Bytes(), nil 667 } 668 669 type validateSender struct{} 670 671 func (c *validateSender) GetRequiredGasAndComputationCost(input []byte) (uint64, uint64) { 672 numSigs := uint64(len(input) / common.SignatureLength) 673 return numSigs * params.ValidateSenderGas, 674 numSigs*params.ValidateSenderPerSigComputationCost + params.ValidateSenderBaseComputationCost 675 } 676 677 func (c *validateSender) Run(input []byte, contract *Contract, evm *EVM) ([]byte, error) { 678 if err := c.validateSender(input, evm.StateDB, evm.BlockNumber.Uint64()); err != nil { 679 // If return error makes contract execution failed, do not return the error. 680 // Instead, print log. 681 logger.Trace("validateSender failed", "err", err) 682 return []byte{0}, nil 683 } 684 return []byte{1}, nil 685 } 686 687 func (c *validateSender) validateSender(input []byte, picker types.AccountKeyPicker, currentBlockNumber uint64) error { 688 ptr := input 689 690 // Parse the first 20 bytes. They represent an address to be verified. 691 if len(ptr) < common.AddressLength { 692 return errInputTooShort 693 } 694 from := common.BytesToAddress(input[0:common.AddressLength]) 695 ptr = ptr[common.AddressLength:] 696 697 // Parse the next 32 bytes. They represent a message which was used to generate signatures. 698 if len(ptr) < common.HashLength { 699 return errInputTooShort 700 } 701 msg := ptr[0:common.HashLength] 702 ptr = ptr[common.HashLength:] 703 704 // Parse remaining bytes. The length should be divided by common.SignatureLength. 705 if len(ptr)%common.SignatureLength != 0 { 706 return errWrongSignatureLength 707 } 708 709 numSigs := len(ptr) / common.SignatureLength 710 pubs := make([]*ecdsa.PublicKey, numSigs) 711 for i := 0; i < numSigs; i++ { 712 p, err := crypto.Ecrecover(msg, ptr[0:common.SignatureLength]) 713 if err != nil { 714 return err 715 } 716 pubs[i], err = crypto.UnmarshalPubkey(p) 717 if err != nil { 718 return err 719 } 720 ptr = ptr[common.SignatureLength:] 721 } 722 723 k := picker.GetKey(from) 724 if err := accountkey.ValidateAccountKey(currentBlockNumber, from, k, pubs, accountkey.RoleTransaction); err != nil { 725 return err 726 } 727 728 return nil 729 }