-
Notifications
You must be signed in to change notification settings - Fork 76
/
BlockExecution.scala
191 lines (168 loc) · 7.24 KB
/
BlockExecution.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package io.iohk.ethereum.ledger
import io.iohk.ethereum.domain._
import io.iohk.ethereum.ledger.BlockExecutionError.MissingParentError
import io.iohk.ethereum.ledger.Ledger.BlockResult
import io.iohk.ethereum.utils.{BlockchainConfig, DaoForkConfig, Logger}
import io.iohk.ethereum.vm.EvmConfig
import scala.annotation.tailrec
import cats.implicits._
class BlockExecution(
blockchain: BlockchainImpl,
blockchainConfig: BlockchainConfig,
blockPreparator: BlockPreparator,
blockValidation: BlockValidation
) extends Logger {
/** Executes and validate a block
*
* @param alreadyValidated should we skip pre-execution validation (if the block has already been validated,
* eg. in the importBlock method)
*/
def executeAndValidateBlock(
block: Block,
alreadyValidated: Boolean = false
): Either[BlockExecutionError, Seq[Receipt]] = {
val preExecValidationResult =
if (alreadyValidated) Right(block) else blockValidation.validateBlockBeforeExecution(block)
val blockExecResult = {
if (block.hasCheckpoint) {
// block with checkpoint is not executed normally - it's not need to do after execution validation
preExecValidationResult
.map(_ => Seq.empty[Receipt])
} else {
for {
_ <- preExecValidationResult
result <- executeBlock(block)
_ <- blockValidation.validateBlockAfterExecution(
block,
result.worldState.stateRootHash,
result.receipts,
result.gasUsed
)
} yield result.receipts
}
}
if (blockExecResult.isRight) {
log.debug(s"Block ${block.header.number} (with hash: ${block.header.hashAsHexString}) executed correctly")
}
blockExecResult
}
/** Executes a block (executes transactions and pays rewards) */
private def executeBlock(block: Block): Either[BlockExecutionError, BlockResult] = {
for {
parent <- blockchain
.getBlockHeaderByHash(block.header.parentHash)
.toRight(MissingParentError) // Should not never occur because validated earlier
execResult <- executeBlockTransactions(block, parent)
worldToPersist <- Either.catchOnly[Throwable](blockPreparator.payBlockReward(block, execResult.worldState))
.leftMap(BlockExecutionError.MPTError.apply)
// State root hash needs to be up-to-date for validateBlockAfterExecution
worldPersisted = InMemoryWorldStateProxy.persistState(worldToPersist)
} yield execResult.copy(worldState = worldPersisted)
}
/** This function runs transactions
*
* @param block the block with transactions to run
*/
private[ledger] def executeBlockTransactions(
block: Block,
parent: BlockHeader
): Either[BlockExecutionError, BlockResult] = {
val parentStateRoot = parent.stateRoot
val blockHeaderNumber = block.header.number
val initialWorld = blockchain.getWorldStateProxy(
blockNumber = blockHeaderNumber,
accountStartNonce = blockchainConfig.accountStartNonce,
stateRootHash = parentStateRoot,
noEmptyAccounts = EvmConfig.forBlock(blockHeaderNumber, blockchainConfig).noEmptyAccounts,
ethCompatibleStorage = blockchainConfig.ethCompatibleStorage
)
val inputWorld = blockchainConfig.daoForkConfig match {
case Some(daoForkConfig) if daoForkConfig.isDaoForkBlock(blockHeaderNumber) =>
drainDaoForkAccounts(initialWorld, daoForkConfig)
case _ => initialWorld
}
val hashAsHexString = block.header.hashAsHexString
val transactionList = block.body.transactionList
log.debug(
s"About to execute ${transactionList.size} txs from block $blockHeaderNumber (with hash: $hashAsHexString)"
)
val blockTxsExecResult = blockPreparator.executeTransactions(transactionList, inputWorld, block.header)
blockTxsExecResult match {
case Right(_) => log.debug(s"All txs from block $hashAsHexString were executed successfully")
case Left(error) =>
log.debug(s"Not all txs from block $hashAsHexString were executed correctly, due to ${error.reason}")
}
blockTxsExecResult
}
/** This function updates worldState transferring balance from drainList accounts to refundContract address
*
* @param worldState initial world state
* @param daoForkConfig dao fork configuration with drainList and refundContract config
* @return updated world state proxy
*/
private def drainDaoForkAccounts(
worldState: InMemoryWorldStateProxy,
daoForkConfig: DaoForkConfig
): InMemoryWorldStateProxy = {
daoForkConfig.refundContract match {
case Some(refundContractAddress) =>
daoForkConfig.drainList.foldLeft(worldState) { (ws, address) =>
ws.getAccount(address)
.map(account => ws.transfer(from = address, to = refundContractAddress, account.balance))
.getOrElse(ws)
}
case None => worldState
}
}
/** Executes and validates a list of blocks, storing the results in the blockchain.
*
* @param blocks blocks to be executed
* @param parentChainWeight parent weight
*
* @return a list of blocks in incremental order that were correctly executed and an optional [[BlockExecutionError]]
*/
def executeAndValidateBlocks(
blocks: List[Block],
parentChainWeight: ChainWeight
): (List[BlockData], Option[BlockExecutionError]) = {
@tailrec
def go(
executedBlocksDecOrder: List[BlockData],
remainingBlocksIncOrder: List[Block],
parentWeight: ChainWeight,
error: Option[BlockExecutionError]
): (List[BlockData], Option[BlockExecutionError]) = {
if (remainingBlocksIncOrder.isEmpty) {
(executedBlocksDecOrder.reverse, None)
} else {
val blockToExecute = remainingBlocksIncOrder.head
executeAndValidateBlock(blockToExecute, alreadyValidated = true) match {
case Right(receipts) =>
val newWeight = parentWeight.increase(blockToExecute.header)
val newBlockData = BlockData(blockToExecute, receipts, newWeight)
blockchain.save(newBlockData.block, newBlockData.receipts, newBlockData.weight, saveAsBestBlock = true)
go(newBlockData :: executedBlocksDecOrder, remainingBlocksIncOrder.tail, newWeight, None)
case Left(executionError) =>
(executedBlocksDecOrder.reverse, Some(executionError))
}
}
}
go(List.empty[BlockData], blocks, parentChainWeight, None)
}
}
sealed trait BlockExecutionError {
val reason: Any
}
sealed trait BlockExecutionSuccess
final case object BlockExecutionSuccess extends BlockExecutionSuccess
object BlockExecutionError {
final case class ValidationBeforeExecError(reason: Any) extends BlockExecutionError
final case class StateBeforeFailure(worldState: InMemoryWorldStateProxy, acumGas: BigInt, acumReceipts: Seq[Receipt])
final case class TxsExecutionError(stx: SignedTransaction, stateBeforeError: StateBeforeFailure, reason: String)
extends BlockExecutionError
final case class ValidationAfterExecError(reason: String) extends BlockExecutionError
final case object MissingParentError extends BlockExecutionError {
override val reason: Any = "Cannot find parent"
}
final case class MPTError(reason: Throwable) extends BlockExecutionError
}