1// Copyright 2016 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
17package core
18
19import (
20	"math/big"
21
22	"github.com/ethereum/go-ethereum/common"
23	"github.com/ethereum/go-ethereum/consensus"
24	"github.com/ethereum/go-ethereum/core/types"
25	"github.com/ethereum/go-ethereum/core/vm"
26)
27
28// ChainContext supports retrieving headers and consensus parameters from the
29// current blockchain to be used during transaction processing.
30type ChainContext interface {
31	// Engine retrieves the chain's consensus engine.
32	Engine() consensus.Engine
33
34	// GetHeader returns the hash corresponding to their hash.
35	GetHeader(common.Hash, uint64) *types.Header
36}
37
38// NewEVMBlockContext creates a new context for use in the EVM.
39func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common.Address) vm.BlockContext {
40	var (
41		beneficiary common.Address
42		baseFee     *big.Int
43	)
44
45	// If we don't have an explicit author (i.e. not mining), extract from the header
46	if author == nil {
47		beneficiary, _ = chain.Engine().Author(header) // Ignore error, we're past header validation
48	} else {
49		beneficiary = *author
50	}
51	if header.BaseFee != nil {
52		baseFee = new(big.Int).Set(header.BaseFee)
53	}
54	return vm.BlockContext{
55		CanTransfer: CanTransfer,
56		Transfer:    Transfer,
57		GetHash:     GetHashFn(header, chain),
58		Coinbase:    beneficiary,
59		BlockNumber: new(big.Int).Set(header.Number),
60		Time:        new(big.Int).SetUint64(header.Time),
61		Difficulty:  new(big.Int).Set(header.Difficulty),
62		BaseFee:     baseFee,
63		GasLimit:    header.GasLimit,
64	}
65}
66
67// NewEVMTxContext creates a new transaction context for a single transaction.
68func NewEVMTxContext(msg Message) vm.TxContext {
69	return vm.TxContext{
70		Origin:   msg.From(),
71		GasPrice: new(big.Int).Set(msg.GasPrice()),
72	}
73}
74
75// GetHashFn returns a GetHashFunc which retrieves header hashes by number
76func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash {
77	// Cache will initially contain [refHash.parent],
78	// Then fill up with [refHash.p, refHash.pp, refHash.ppp, ...]
79	var cache []common.Hash
80
81	return func(n uint64) common.Hash {
82		// If there's no hash cache yet, make one
83		if len(cache) == 0 {
84			cache = append(cache, ref.ParentHash)
85		}
86		if idx := ref.Number.Uint64() - n - 1; idx < uint64(len(cache)) {
87			return cache[idx]
88		}
89		// No luck in the cache, but we can start iterating from the last element we already know
90		lastKnownHash := cache[len(cache)-1]
91		lastKnownNumber := ref.Number.Uint64() - uint64(len(cache))
92
93		for {
94			header := chain.GetHeader(lastKnownHash, lastKnownNumber)
95			if header == nil {
96				break
97			}
98			cache = append(cache, header.ParentHash)
99			lastKnownHash = header.ParentHash
100			lastKnownNumber = header.Number.Uint64() - 1
101			if n == lastKnownNumber {
102				return lastKnownHash
103			}
104		}
105		return common.Hash{}
106	}
107}
108
109// CanTransfer checks whether there are enough funds in the address' account to make a transfer.
110// This does not take the necessary gas in to account to make the transfer valid.
111func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool {
112	return db.GetBalance(addr).Cmp(amount) >= 0
113}
114
115// Transfer subtracts amount from sender and adds amount to recipient using the given Db
116func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
117	db.SubBalance(sender, amount)
118	db.AddBalance(recipient, amount)
119}
120