When does it run?
The execution for a smart contract transaction occurs when the mining node includes the transaction in a block it generates. The transaction and smart contract code is re-run by every validating node upon receipt of the block.
Mining nodes, to generate a block:
- Receive unconfirmed transactions from the network (p2p protocol)
- Validate each unconfirmed transaction, including running associated code
- Include valid transactions to fill the block in a way that maximizes profitability
Once the block is generated, it's distributed to the network, and any node to receive that block then proceeds to run through the list of transactions, ensuring each transaction is valid (including running associated code). When a new node connects to the network, it downloads every block in history and re-validates every transaction in each.
So when does smart contract code run?
- Lots of times, repeatedly and redundantly. By design.
- But the "official" execution point is the point at which the transaction occurs in the blockchain. If it's transaction #5 in block #3000000, then the transaction's "point of execution" could perhaps only be described as immediately following transaction #4, preceding transaction #6.
The repeated validation is possible because smart contract transactions are deterministic. They may depend on factors such as the block number itself, current storage values for a contract, or the result of another smart contract's computation, but that information is constant and can be recomputed perfectly by stepping through transactions from the start of the chain.
N.B. This pertains to transactions specifically. The EVM also defines the notion of a call. This distinction is well-explained elsewhere on this forum.
What limits the execution time?
The limits are provided by means of the "gas" system. Gas is computed based on amount of storage used, plus individual gas costs for each machine instruction (opcode).
Gas is limited by two mechanisms:
The sender of a transaction specifies the gas limit they're willing to spend for the transaction. (This is usually computed automatically based on an estimate)
Mining nodes specify a block total gas limit, theoretically optimizing for profitability based on network performance. Transactions that exceed the block gas limit will not get included in any block.
During validation, the transaction code execution can safely be aborted if either of these limits is reached. This prevents nodes from spending excess computing time performing this validation, and prevents the block time from growing as the number of transactions increases.