gas_table.go 15.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

17 18 19
package vm

import (
20 21
	"errors"

22
	"github.com/ethereum/go-ethereum/common"
23
	"github.com/ethereum/go-ethereum/common/math"
24 25 26
	"github.com/ethereum/go-ethereum/params"
)

27
// memoryGasCost calculates the quadratic gas for memory expansion. It does so
28 29 30 31
// only for the memory region that is expanded, not the total memory.
func memoryGasCost(mem *Memory, newMemSize uint64) (uint64, error) {
	if newMemSize == 0 {
		return 0, nil
32
	}
33 34 35 36 37
	// The maximum that will fit in a uint64 is max_word_count - 1. Anything above
	// that will result in an overflow. Additionally, a newMemSize which results in
	// a newMemSizeWords larger than 0xFFFFFFFF will cause the square operation to
	// overflow. The constant 0x1FFFFFFFE0 is the highest number that can be used
	// without overflowing the gas calculation.
38
	if newMemSize > 0x1FFFFFFFE0 {
39
		return 0, ErrGasUintOverflow
40
	}
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
	newMemSizeWords := toWordSize(newMemSize)
	newMemSize = newMemSizeWords * 32

	if newMemSize > uint64(mem.Len()) {
		square := newMemSizeWords * newMemSizeWords
		linCoef := newMemSizeWords * params.MemoryGas
		quadCoef := square / params.QuadCoeffDiv
		newTotalFee := linCoef + quadCoef

		fee := newTotalFee - mem.lastGasCost
		mem.lastGasCost = newTotalFee

		return fee, nil
	}
	return 0, nil
56 57
}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
// memoryCopierGas creates the gas functions for the following opcodes, and takes
// the stack position of the operand which determines the size of the data to copy
// as argument:
// CALLDATACOPY (stack position 2)
// CODECOPY (stack position 2)
// EXTCODECOPY (stack poition 3)
// RETURNDATACOPY (stack position 2)
func memoryCopierGas(stackpos int) gasFunc {
	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
		// Gas for expanding the memory
		gas, err := memoryGasCost(mem, memorySize)
		if err != nil {
			return 0, err
		}
		// And gas for copying data, charged per word at param.CopyGas
73
		words, overflow := stack.Back(stackpos).Uint64WithOverflow()
74
		if overflow {
75
			return 0, ErrGasUintOverflow
76
		}
77

78
		if words, overflow = math.SafeMul(toWordSize(words), params.CopyGas); overflow {
79
			return 0, ErrGasUintOverflow
80
		}
81

82
		if gas, overflow = math.SafeAdd(gas, words); overflow {
83
			return 0, ErrGasUintOverflow
84 85
		}
		return gas, nil
86 87 88
	}
}

89 90 91 92 93 94
var (
	gasCallDataCopy   = memoryCopierGas(2)
	gasCodeCopy       = memoryCopierGas(2)
	gasExtCodeCopy    = memoryCopierGas(3)
	gasReturnDataCopy = memoryCopierGas(2)
)
95

96
func gasSStore(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
97
	var (
98
		y, x    = stack.Back(1), stack.Back(0)
99
		current = evm.StateDB.GetState(contract.Address(), common.Hash(x.Bytes32()))
100
	)
101
	// The legacy gas metering only takes into consideration the current state
102 103 104
	// Legacy rules should be applied if we are in Petersburg (removal of EIP-1283)
	// OR Constantinople is not active
	if evm.chainRules.IsPetersburg || !evm.chainRules.IsConstantinople {
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
		// This checks for 3 scenario's and calculates gas accordingly:
		//
		// 1. From a zero-value address to a non-zero value         (NEW VALUE)
		// 2. From a non-zero value address to a zero-value address (DELETE)
		// 3. From a non-zero to a non-zero                         (CHANGE)
		switch {
		case current == (common.Hash{}) && y.Sign() != 0: // 0 => non 0
			return params.SstoreSetGas, nil
		case current != (common.Hash{}) && y.Sign() == 0: // non 0 => 0
			evm.StateDB.AddRefund(params.SstoreRefundGas)
			return params.SstoreClearGas, nil
		default: // non 0 => non 0 (or 0 => 0)
			return params.SstoreResetGas, nil
		}
	}
	// The new gas metering is based on net gas costs (EIP-1283):
	//
	// 1. If current value equals new value (this is a no-op), 200 gas is deducted.
	// 2. If current value does not equal new value
	//   2.1. If original value equals current value (this storage slot has not been changed by the current execution context)
	//     2.1.1. If original value is 0, 20000 gas is deducted.
	// 	   2.1.2. Otherwise, 5000 gas is deducted. If new value is 0, add 15000 gas to refund counter.
	// 	2.2. If original value does not equal current value (this storage slot is dirty), 200 gas is deducted. Apply both of the following clauses.
	// 	  2.2.1. If original value is not 0
	//       2.2.1.1. If current value is 0 (also means that new value is not 0), remove 15000 gas from refund counter. We can prove that refund counter will never go below 0.
	//       2.2.1.2. If new value is 0 (also means that current value is not 0), add 15000 gas to refund counter.
	// 	  2.2.2. If original value equals new value (this storage slot is reset)
	//       2.2.2.1. If original value is 0, add 19800 gas to refund counter.
	// 	     2.2.2.2. Otherwise, add 4800 gas to refund counter.
134
	value := common.Hash(y.Bytes32())
135 136 137
	if current == value { // noop (1)
		return params.NetSstoreNoopGas, nil
	}
138
	original := evm.StateDB.GetCommittedState(contract.Address(), common.Hash(x.Bytes32()))
139 140 141
	if original == current {
		if original == (common.Hash{}) { // create slot (2.1.1)
			return params.NetSstoreInitGas, nil
142
		}
143 144
		if value == (common.Hash{}) { // delete slot (2.1.2b)
			evm.StateDB.AddRefund(params.NetSstoreClearRefund)
145
		}
146 147 148 149 150 151 152
		return params.NetSstoreCleanGas, nil // write existing slot (2.1.2)
	}
	if original != (common.Hash{}) {
		if current == (common.Hash{}) { // recreate slot (2.2.1.1)
			evm.StateDB.SubRefund(params.NetSstoreClearRefund)
		} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
			evm.StateDB.AddRefund(params.NetSstoreClearRefund)
153 154
		}
	}
155 156 157 158 159
	if original == value {
		if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
			evm.StateDB.AddRefund(params.NetSstoreResetClearRefund)
		} else { // reset to original existing slot (2.2.2.2)
			evm.StateDB.AddRefund(params.NetSstoreResetRefund)
160 161
		}
	}
162
	return params.NetSstoreDirtyGas, nil
163 164
}

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
// 0. If *gasleft* is less than or equal to 2300, fail the current call.
// 1. If current value equals new value (this is a no-op), SSTORE_NOOP_GAS gas is deducted.
// 2. If current value does not equal new value:
//   2.1. If original value equals current value (this storage slot has not been changed by the current execution context):
//     2.1.1. If original value is 0, SSTORE_INIT_GAS gas is deducted.
//     2.1.2. Otherwise, SSTORE_CLEAN_GAS gas is deducted. If new value is 0, add SSTORE_CLEAR_REFUND to refund counter.
//   2.2. If original value does not equal current value (this storage slot is dirty), SSTORE_DIRTY_GAS gas is deducted. Apply both of the following clauses:
//     2.2.1. If original value is not 0:
//       2.2.1.1. If current value is 0 (also means that new value is not 0), subtract SSTORE_CLEAR_REFUND gas from refund counter. We can prove that refund counter will never go below 0.
//       2.2.1.2. If new value is 0 (also means that current value is not 0), add SSTORE_CLEAR_REFUND gas to refund counter.
//     2.2.2. If original value equals new value (this storage slot is reset):
//       2.2.2.1. If original value is 0, add SSTORE_INIT_REFUND to refund counter.
//       2.2.2.2. Otherwise, add SSTORE_CLEAN_REFUND gas to refund counter.
func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
	// If we fail the minimum gas availability invariant, fail (0)
	if contract.Gas <= params.SstoreSentryGasEIP2200 {
		return 0, errors.New("not enough gas for reentrancy sentry")
	}
	// Gas sentry honoured, do the actual gas calculation based on the stored value
	var (
		y, x    = stack.Back(1), stack.Back(0)
186
		current = evm.StateDB.GetState(contract.Address(), common.Hash(x.Bytes32()))
187
	)
188
	value := common.Hash(y.Bytes32())
189 190 191 192

	if current == value { // noop (1)
		return params.SstoreNoopGasEIP2200, nil
	}
193
	original := evm.StateDB.GetCommittedState(contract.Address(), common.Hash(x.Bytes32()))
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	if original == current {
		if original == (common.Hash{}) { // create slot (2.1.1)
			return params.SstoreInitGasEIP2200, nil
		}
		if value == (common.Hash{}) { // delete slot (2.1.2b)
			evm.StateDB.AddRefund(params.SstoreClearRefundEIP2200)
		}
		return params.SstoreCleanGasEIP2200, nil // write existing slot (2.1.2)
	}
	if original != (common.Hash{}) {
		if current == (common.Hash{}) { // recreate slot (2.2.1.1)
			evm.StateDB.SubRefund(params.SstoreClearRefundEIP2200)
		} else if value == (common.Hash{}) { // delete slot (2.2.1.2)
			evm.StateDB.AddRefund(params.SstoreClearRefundEIP2200)
		}
	}
	if original == value {
		if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
			evm.StateDB.AddRefund(params.SstoreInitRefundEIP2200)
		} else { // reset to original existing slot (2.2.2.2)
			evm.StateDB.AddRefund(params.SstoreCleanRefundEIP2200)
		}
	}
	return params.SstoreDirtyGasEIP2200, nil // dirty update (2.2)
}

220
func makeGasLog(n uint64) gasFunc {
221
	return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
222
		requestedSize, overflow := stack.Back(1).Uint64WithOverflow()
223
		if overflow {
224
			return 0, ErrGasUintOverflow
225
		}
226

227 228 229 230 231 232
		gas, err := memoryGasCost(mem, memorySize)
		if err != nil {
			return 0, err
		}

		if gas, overflow = math.SafeAdd(gas, params.LogGas); overflow {
233
			return 0, ErrGasUintOverflow
234 235
		}
		if gas, overflow = math.SafeAdd(gas, n*params.LogTopicGas); overflow {
236
			return 0, ErrGasUintOverflow
237 238 239 240
		}

		var memorySizeGas uint64
		if memorySizeGas, overflow = math.SafeMul(requestedSize, params.LogDataGas); overflow {
241
			return 0, ErrGasUintOverflow
242 243
		}
		if gas, overflow = math.SafeAdd(gas, memorySizeGas); overflow {
244
			return 0, ErrGasUintOverflow
245 246
		}
		return gas, nil
247 248 249
	}
}

250
func gasSha3(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
251 252 253 254
	gas, err := memoryGasCost(mem, memorySize)
	if err != nil {
		return 0, err
	}
255
	wordGas, overflow := stack.Back(1).Uint64WithOverflow()
256
	if overflow {
257
		return 0, ErrGasUintOverflow
258 259
	}
	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Sha3WordGas); overflow {
260
		return 0, ErrGasUintOverflow
261 262
	}
	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
263
		return 0, ErrGasUintOverflow
264 265
	}
	return gas, nil
266 267
}

268 269 270 271 272
// pureMemoryGascost is used by several operations, which aside from their
// static cost have a dynamic cost which is solely based on the memory
// expansion
func pureMemoryGascost(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
	return memoryGasCost(mem, memorySize)
273 274
}

275 276 277 278 279 280 281 282
var (
	gasReturn  = pureMemoryGascost
	gasRevert  = pureMemoryGascost
	gasMLoad   = pureMemoryGascost
	gasMStore8 = pureMemoryGascost
	gasMStore  = pureMemoryGascost
	gasCreate  = pureMemoryGascost
)
283

284
func gasCreate2(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
285 286 287 288
	gas, err := memoryGasCost(mem, memorySize)
	if err != nil {
		return 0, err
	}
289
	wordGas, overflow := stack.Back(2).Uint64WithOverflow()
290
	if overflow {
291
		return 0, ErrGasUintOverflow
292 293
	}
	if wordGas, overflow = math.SafeMul(toWordSize(wordGas), params.Sha3WordGas); overflow {
294
		return 0, ErrGasUintOverflow
295 296
	}
	if gas, overflow = math.SafeAdd(gas, wordGas); overflow {
297
		return 0, ErrGasUintOverflow
298
	}
299 300 301
	return gas, nil
}

302 303
func gasExpFrontier(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
304

305 306 307 308 309
	var (
		gas      = expByteLen * params.ExpByteFrontier // no overflow check required. Max is 256 * ExpByte gas
		overflow bool
	)
	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
310
		return 0, ErrGasUintOverflow
311 312
	}
	return gas, nil
313 314
}

315
func gasExpEIP158(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
316
	expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
317

318
	var (
319
		gas      = expByteLen * params.ExpByteEIP158 // no overflow check required. Max is 256 * ExpByte gas
320 321
		overflow bool
	)
322
	if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
323
		return 0, ErrGasUintOverflow
324 325 326 327
	}
	return gas, nil
}

328
func gasCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
329
	var (
330
		gas            uint64
331 332
		transfersValue = !stack.Back(2).IsZero()
		address        = common.Address(stack.Back(1).Bytes20())
333
	)
334
	if evm.chainRules.IsEIP158 {
335
		if transfersValue && evm.StateDB.Empty(address) {
336
			gas += params.CallNewAccountGas
337
		}
338 339
	} else if !evm.StateDB.Exist(address) {
		gas += params.CallNewAccountGas
340 341
	}
	if transfersValue {
342 343 344 345 346 347 348 349
		gas += params.CallValueTransferGas
	}
	memoryGas, err := memoryGasCost(mem, memorySize)
	if err != nil {
		return 0, err
	}
	var overflow bool
	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
350
		return 0, ErrGasUintOverflow
351 352
	}

353
	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
354 355 356
	if err != nil {
		return 0, err
	}
357
	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
358
		return 0, ErrGasUintOverflow
359 360
	}
	return gas, nil
361 362
}

363
func gasCallCode(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
364 365 366 367
	memoryGas, err := memoryGasCost(mem, memorySize)
	if err != nil {
		return 0, err
	}
368 369 370 371 372 373 374
	var (
		gas      uint64
		overflow bool
	)
	if stack.Back(2).Sign() != 0 {
		gas += params.CallValueTransferGas
	}
375
	if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {
376
		return 0, ErrGasUintOverflow
377
	}
378
	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
379 380 381
	if err != nil {
		return 0, err
	}
382
	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
383
		return 0, ErrGasUintOverflow
384 385
	}
	return gas, nil
386 387
}

388
func gasDelegateCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
389 390 391 392
	gas, err := memoryGasCost(mem, memorySize)
	if err != nil {
		return 0, err
	}
393
	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
394 395 396
	if err != nil {
		return 0, err
	}
397
	var overflow bool
398
	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
399
		return 0, ErrGasUintOverflow
400 401 402 403
	}
	return gas, nil
}

404
func gasStaticCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
405 406 407 408
	gas, err := memoryGasCost(mem, memorySize)
	if err != nil {
		return 0, err
	}
409
	evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))
410 411 412
	if err != nil {
		return 0, err
	}
413
	var overflow bool
414
	if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {
415
		return 0, ErrGasUintOverflow
416 417
	}
	return gas, nil
418
}
419 420 421 422 423 424

func gasSelfdestruct(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
	var gas uint64
	// EIP150 homestead gas reprice fork:
	if evm.chainRules.IsEIP150 {
		gas = params.SelfdestructGasEIP150
425
		var address = common.Address(stack.Back(0).Bytes20())
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

		if evm.chainRules.IsEIP158 {
			// if empty and transfers value
			if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).Sign() != 0 {
				gas += params.CreateBySelfdestructGas
			}
		} else if !evm.StateDB.Exist(address) {
			gas += params.CreateBySelfdestructGas
		}
	}

	if !evm.StateDB.HasSuicided(contract.Address()) {
		evm.StateDB.AddRefund(params.SelfdestructRefundGas)
	}
	return gas, nil
}