Smart-Contract Security and AuditingIntroduction and ContextSmart contracts are programs deployed on a blockchain whose execution is governed by consensus rules rather than by a conventional central operator. Their determinism, transparency and resistance to unilateral modification create valuable applications in finance, governance, supply chains and digital assets. These same properties also make failures unusually severe. A vulnerable web application may be patched and its database restored; a vulnerable smart contract may permanently transfer assets, expose private data, or lock funds in an irreversible state. Security therefore cannot be treated as a final testing activity. It is a lifecycle discipline involving requirements analysis, threat modelling, secure design, implementation, testing, formal reasoning, deployment controls, monitoring and incident response. Auditing is one important part of this lifecycle, but an audit is not a guarantee of correctness. It is an independent, evidence-based assessment of whether specified risks and defects have been identified and addressed. This chapter examines the principal security failures encountered in Solidity systems: reentrancy, authorization errors, oracle manipulation, frontrunning, arithmetic defects, denial of service, proxy weaknesses and economic vulnerabilities. It then presents practical methods for threat modelling, static analysis, dynamic testing, formal verification and secure design. Learning ObjectivesBy the end of this chapter, a student should be able to: - Explain the security properties and trust assumptions of an Ethereum smart-contract system.
- Identify and analyse common Solidity vulnerabilities.
- Apply threat-modelling methods to contracts, protocols and external dependencies.
- Distinguish static analysis, testing, auditing and formal verification.
- Use secure coding patterns such as checks-effects-interactions, role-based access control, pull payments and validated upgrade mechanisms.
- Evaluate technical, economic, governance and operational risks.
- Prepare an evidence-based audit report and recommend proportionate controls.
1. The Security Model of Smart ContractsA contract executes within an environment with unusual constraints. Its storage is persistent, calls may invoke untrusted code, execution consumes gas, and deployed bytecode is normally immutable. Transactions are publicly observable before confirmation, and miners or validators may determine transaction ordering within protocol rules. A contract can also depend on tokens, price feeds, bridges, governance systems and upgrade administrators that it does not fully control. A useful security model distinguishes four properties: - Confidentiality: generally weak on public blockchains because contract state and transaction data are observable.
- Integrity: state transitions must occur only when valid authorization and business conditions are satisfied.
- Availability: legitimate users must be able to execute required operations without unreasonable gas costs or permanent blockage.
- Consistency and economic correctness: balances, shares, prices and obligations must remain correct under adversarial behaviour.
The last property is especially important. A contract can be free from conventional coding bugs and still be exploitable because its incentive design permits profitable manipulation. Trust boundaries and attack surfacesA trust boundary is a point at which data, authority or control passes between components with different security assumptions. Common boundaries include: - an externally owned account calling a contract;
- one contract calling another contract;
- a token or oracle supplied by a third party;
- an upgrade administrator controlling implementation code;
- a governance process controlling parameters;
- an off-chain keeper, relayer or user-interface service;
- a bridge connecting different chains.
At each boundary, the designer should ask: Who controls the input? Can it be malicious? Can the callee revert or re-enter? Can the value be stale, manipulated or unavailable? Can authority be transferred or revoked? What happens if the component disappears or behaves differently from its interface? 2. Threat Modelling for Smart ContractsThreat modelling converts vague concern into a structured analysis. A practical process is: - Define assets. List native currency, tokens, claims, governance power, collateral, confidential information and administrative authority.
- Describe actors. Include ordinary users, privileged operators, compromised accounts, arbitrageurs, validators, oracle providers and malicious contracts.
- Map entry points. Identify public and external functions, callbacks, fallback functions, upgrade functions and automated jobs.
- Trace trust boundaries. Document external calls, signatures, bridges, oracles and off-chain dependencies.
- State invariants. Examples include “total liabilities never exceed reserves” and “only an approved role may change the fee.”
- Model abuse cases. Consider reordering, repetition, partial failure, stale data, extreme values, gas exhaustion and compromised privileges.
- Rank risks. A simple qualitative model considers impact, likelihood, exploitability and detectability. It should guide effort rather than pretend to produce objective precision.
- Select controls and evidence. Every material risk should have a mitigation and a test or proof demonstrating its operation.
A data-flow diagram or call graph can help identify where untrusted information enters the system. Threat models should be revised when a contract adds a token integration, changes its upgrade mechanism or introduces governance. Security invariantsAn invariant is a condition intended to remain true before and after every valid state transition. For a reserve contract, a simplified invariant may be: R ≥ L where R is the value of reserves and L is the value of outstanding liabilities, measured using a stated valuation method. This invariant is meaningful only if the valuation method, oracle assumptions and units are defined. In a real protocol, price volatility, rounding, unsettled withdrawals and oracle delays must also be addressed. 3. ReentrancyReentrancy occurs when a contract makes an external call and the receiving code calls back into the original contract before the first operation has completed. The callback can observe intermediate state and invoke functions that the original developer assumed would execute only later. A classic vulnerable pattern is: function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount, "insufficient");
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
balances[msg.sender] -= amount;
}The balance is updated after the interaction. A malicious recipient can re-enter withdraw while its recorded balance is still unchanged. Reentrancy can also occur through ERC-777 hooks, token callbacks, cross-function calls, read-only reentrancy affecting price calculations, and indirect calls through apparently harmless libraries. The preferred ordering is checks, effects, then interactions: function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount, "insufficient");
balances[msg.sender] -= amount;
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
}A reentrancy guard may provide an additional defence: uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private status = NOT_ENTERED;
modifier nonReentrant() {
require(status != ENTERED, "reentrant");
status = ENTERED;
_;
status = NOT_ENTERED;
}A guard is not a substitute for correct state transitions. Separate functions may still create logical reentrancy, and cross-contract systems may require a broader design review. Pull-payment designs, in which users withdraw funds rather than receiving them during complex operations, reduce interaction risk. 4. Authorization and Access-Control FailuresAuthorization answers who may perform an action; authentication answers who the caller is. In Solidity, msg.sender identifies the immediate caller, not necessarily the human or contract that initiated a transaction. Confusing tx.origin with msg.sender creates phishing and intermediary-contract vulnerabilities. Privileged functions should generally use explicit role checks and should not rely on tx.origin. Typical authorization failures include: - missing access modifiers on mint, burn, pause or upgrade functions;
- checking the wrong role or checking it after state changes;
- unprotected initializers in upgradeable contracts;
- incorrect ownership transfer that leaves control with an unintended address;
- signatures without nonce, deadline, chain identifier or contract-domain binding;
- arbitrary
delegatecall or user-controlled target addresses; - failure to validate that a new administrator is a nonzero, intended address.
Role-based access control should define role holders, grant and revoke rules, emergency powers, and separation of duties. A multisignature wallet and timelock can reduce the risk of one compromised key, but they introduce operational and governance dependencies. Administrative powers should be documented publicly and minimised according to the principle of least privilege. For signed authorizations, a robust design normally binds the message to the intended contract and chain, includes a nonce to prevent replay, and includes an expiry. EIP-712 typed structured data is commonly used for this purpose, but correct domain separation and nonce management remain essential. 5. Oracle Manipulation and External DataBlockchains do not inherently know off-chain prices, interest rates or events. Oracles provide this information, creating a trust boundary. An oracle may be manipulated, delayed, unavailable, censored or incorrectly integrated. A protocol that uses the spot price from a shallow automated-market-maker pool may allow an attacker to borrow capital, trade against the pool, trigger a liquidation or minting calculation, and reverse the trade. The attack may be profitable even when every contract follows its code exactly. Controls include: - using decentralized feeds with documented publisher and deviation assumptions;
- using time-weighted average prices rather than a single instantaneous observation;
- rejecting stale data and invalid timestamps;
- enforcing bounds on acceptable prices and update deviations;
- using multiple independent sources where appropriate;
- applying conservative collateral factors and circuit breakers;
- pausing sensitive operations when oracle conditions fail;
- testing decimal precision, signed values and feed-specific interfaces.
An oracle control is only as strong as its assumptions. “Multiple sources” does not provide independence if all sources derive data from the same market or provider. Governance must also define who can change the oracle and how quickly. 6. Frontrunning, Transaction Ordering and MEVPending transactions may be visible before confirmation. An adversary can observe a transaction and submit another transaction with a higher fee, or exploit the fact that a transaction will change a public state variable. This broader extraction of value from transaction ordering is often called maximal extractable value (MEV). Examples include buying an asset before a visible trade, inserting a transaction between two legs of a user operation, exploiting a public liquidation opportunity, or copying a profitable arbitrage transaction. A naive limit order that accepts any execution price is vulnerable to sandwiching. Mitigations depend on the application: - require a user-supplied minimum output or maximum input;
- use deadlines so stale transactions fail;
- use commit–reveal schemes for auctions or sensitive choices;
- use batch auctions or uniform clearing prices;
- avoid exposing intermediate state when possible;
- use private transaction channels with carefully assessed trust assumptions;
- make signatures and permits non-replayable and context-bound.
No contract can generally guarantee a particular ordering on a public network. Slippage limits reduce loss but may also cause legitimate transactions to revert. Commit–reveal schemes add complexity and require a response to users who commit but never reveal. 7. Arithmetic, Types and PrecisionCurrent Solidity versions revert on ordinary integer overflow and underflow in checked arithmetic. This removes a major historical class of defects, but arithmetic risk remains substantial. Developers must still consider division truncation, decimal mismatches, signed and unsigned conversion, unsafe use of unchecked, multiplication order, precision loss and extreme values. For integer division, Solidity truncates toward zero. Thus, if integer variables represent token units, dividing before multiplying can destroy precision. A common safer approach is to multiply first, provided the intermediate product cannot overflow and the economic formula permits that ordering. Token decimals are presentation conventions, not a universal unit system. A token with 6 decimals and another with 18 decimals require explicit scaling. Oracle feeds may have yet another decimal convention. Every calculation should document its unit and scaling factor. A useful review question is whether a formula preserves bounds. For example, a fee calculation might be written as: fee = ⌊amount × rate ÷ D⌋ where amount is denominated in the smallest token unit, rate is an integer rate, and D is the rate denominator. The formula assumes that amount × rate fits the selected integer type and that rounding down is acceptable. If a fee must never be below a minimum, that requirement must be implemented explicitly rather than inferred from the formula. Rounding can create exploitable asymmetry. If deposits round up while withdrawals round down, repeated small operations may accumulate value for one side. Protocols should specify who receives rounding residuals and test boundary values, zero values, maximum values and values just below a unit threshold. 8. Denial of Service and Gas RisksA denial-of-service vulnerability prevents a valid operation from completing. Common causes include unbounded loops, reliance on a recipient that can revert, storage growth, block gas limits and state-dependent paths that become too expensive. This pattern is dangerous: for (uint256 i = 0; i < recipients.length; i++) {
payable(recipients[i]).transfer(amounts[i]);
}One reverting recipient can block all payments, and a growing array can eventually make the function exceed the block gas limit. A pull-payment approach records each entitlement and allows recipients to withdraw independently. Bounded batches, pagination and explicit maximum sizes are other controls. Gas is also a security consideration. A function that is technically correct but unaffordable is unavailable in practice. Auditors should test worst-case storage size, cold and warm access effects where relevant, event costs, revert paths and upgrade-induced changes in execution cost. 9. Proxy and Upgradeability VulnerabilitiesProxy systems separate a stable proxy address from implementation logic. A common delegatecall proxy executes implementation code in the proxy’s storage context. This permits upgrades but creates additional failure modes: - storage-slot collisions between proxy and implementation;
- incorrect variable ordering or incompatible inheritance changes;
- an uninitialized implementation or proxy;
- unauthorized upgrade functions;
- malicious or accidental implementation addresses;
- selector collisions and fallback mistakes;
- initialization functions callable more than once;
- upgrades that change assumptions without migration of state.
Upgrade-safe development requires a documented storage layout, controlled initializers, tested upgrade procedures, explicit authorization and often a timelock or multisignature approval. The upgrade administrator should not be treated as an invisible technical detail: it is a major component of the system’s trust model. Immutable deployments are easier to reason about but harder to repair. Upgradeable deployments are adaptable but introduce governance and implementation risk. The correct choice depends on threat tolerance, operational capacity and the consequences of change. 10. Economic VulnerabilitiesEconomic vulnerabilities arise when a protocol’s rules permit profitable behaviour that violates its intended purpose. They may involve flash loans, collateral mispricing, share-price inflation, liquidation incentives, fee asymmetry, governance capture or liquidity assumptions. A flash loan is not itself a vulnerability. It provides large temporary capital within one transaction, allowing an attacker to execute complex strategies without holding capital between blocks. The protocol must remain safe under atomic, high-capital transactions. Economic analysis should ask: - What can an attacker gain, and what must the attacker spend?
- Can the attacker manipulate a price, reserve, voting weight or exchange rate temporarily?
- Are there profitable sequences involving deposit, donation, withdrawal or liquidation?
- Does governance power correspond to economic stake and time commitment?
- Can a user be liquidated because of an oracle delay or a temporary market movement?
- Do incentives encourage honest participation or strategic abuse?
Testing should include adversarial simulations and scenario analysis, not only unit-level assertions. Economic assumptions should be stated as explicitly as software assumptions. 11. Audit and Verification MethodsNo single method detects every class of defect. Effective assurance uses complementary techniques. Code review and manual auditManual review examines requirements, architecture, control flow, state transitions, external calls, privilege boundaries and economic assumptions. A professional audit should define scope, compiler version, deployed addresses, excluded components, assumptions, severity methodology and residual risks. Findings should include a description, impact, evidence, recommendation and remediation status. Static analysisStatic-analysis tools inspect source or bytecode without executing the system. They can identify reentrancy patterns, dangerous calls, unreachable code, suspicious arithmetic, access-control issues and proxy patterns. Their advantages are speed, repeatability and broad coverage. Their limitations include false positives, false negatives and inability to understand all economic intent. Tool output must be triaged by a qualified reviewer. Dynamic testing and fuzzingUnit tests demonstrate expected examples. Integration tests examine interactions among contracts. Fuzzing generates many inputs, including unexpected boundaries. Property-based testing is especially valuable for invariants such as conservation of balances, authorization restrictions and solvency conditions. A property should be stated precisely. “Users cannot withdraw more than their entitlement” requires a definition of entitlement, treatment of rounding and treatment of pending operations. Fuzz tests should include sequences of actions, not only isolated calls, because many vulnerabilities arise from state history. Symbolic executionSymbolic execution treats inputs as symbolic values and explores execution paths subject to constraints. It can find inputs that reach an assertion failure or unauthorized state. Path explosion, external environment modelling and complex arithmetic limit scalability, so results require interpretation. Formal verificationFormal verification proves a specified property under a formal model. It can establish strong guarantees for critical functions, but it cannot prove an incorrectly stated requirement or an unmodelled oracle assumption. A proof that balances never become negative does not prove that the exchange rate is economically fair. Verification may target functional correctness, access control, temporal properties or invariants. The specification should state preconditions, postconditions and invariants. For example, a withdrawal postcondition might require that the caller’s entitlement decreases by the withdrawn amount and that total liabilities decrease by the same amount, subject to defined fees and rounding. Runtime monitoring and incident responseEvents, balance changes and administrative actions should be monitored. Alert conditions may include unusual minting, oracle deviation, repeated failed withdrawals, unexpected upgrades or rapid governance changes. Emergency pause mechanisms can limit damage, but they must be carefully scoped and tested. A pause controlled by a compromised key is not a reliable defence. 12. Secure Development PatternsImportant patterns include: - Checks-effects-interactions: validate inputs and authority, update internal state, then interact externally.
- Least privilege: separate operational, treasury, upgrade and emergency powers.
- Pull payments: let recipients withdraw rather than making one operation depend on many recipients.
- Fail-safe validation: reject zero addresses, invalid ranges, stale data and unsupported tokens.
- Explicit units: document token decimals, oracle decimals, rates and rounding direction.
- Safe token handling: account for tokens that return false, return no value or impose transfer fees; use well-reviewed libraries and define supported-token assumptions.
- Pause and circuit breakers: limit damage during abnormal conditions, with governance and recovery procedures.
- Checks at boundaries: treat every external contract, callback and return value as untrusted.
- Defence in depth: combine code patterns, tests, monitoring, privilege controls and economic limits.
Security features should not create hidden centralization. A pause key, oracle administrator or upgrade multisig is part of the threat model and must be governed accordingly. 13. Illustrative Case: A Lending Protocol Price AttackBackgroundConsider a fictional lending protocol, DeltaLend, that accepts Token A as collateral and allows users to borrow a stable token. Its collateral value is obtained from the current reserve ratio of a small decentralized exchange pool containing Token A and the stable token. ProblemThe pool has limited liquidity. The lending contract reads the reserve ratio immediately before allowing a borrow. It does not use a time-weighted price, a deviation bound or a liquidity threshold. AnalysisAn attacker obtains temporary capital through a flash loan, buys Token A in the pool, and thereby raises the apparent price. The attacker deposits Token A as collateral while the manipulated price is observed, borrows stable tokens, then reverses the pool trade. If the borrowed amount exceeds the enduring value of the collateral, the protocol is left with bad debt. The code may have correct access control and checked arithmetic; the defect is an oracle and economic-design failure. Approach and solutionA redesign should use a robust price feed with documented freshness requirements, reject stale or invalid observations, apply conservative collateral factors, and impose a maximum deviation from a reference value. The protocol should also assess market liquidity and cap borrowing against newly deposited collateral. A circuit breaker can pause new borrowing when the feed deviates beyond a governance-approved threshold. Fuzzing and economic simulation should test atomic price manipulation, extreme volatility and oracle downtime. OutcomeThe redesign reduces, but does not eliminate, risk. It introduces dependencies on the oracle publishers and governance. Those dependencies must be monitored, and emergency authority must be protected by a multisignature process with a documented response procedure. Learning points- A contract can be syntactically correct yet economically exploitable.
- External data is a trust boundary, not a fact supplied by the blockchain.
- Flash loans amplify existing weaknesses but do not create every weakness.
- Mitigations must address data quality, market liquidity, incentives and governance together.
14. Governance, Ethics and RegulationSecurity decisions affect users who may have limited technical knowledge and no realistic remedy after loss. Developers and auditors therefore have ethical duties to communicate assumptions, disclose material limitations and avoid overstating audit conclusions. Responsible disclosure should provide maintainers an opportunity to remediate while considering imminent exploitation and user protection. Governance should clarify who can pause, upgrade, change fees, alter oracle sources or seize emergency funds. These powers should be visible, bounded and logged. Regulatory obligations vary by jurisdiction and application, but audit trails, access controls, consumer protection, financial-risk management and data-protection requirements may all be relevant. Immutability does not remove legal or organizational accountability. Artificial-intelligence tools can assist with code summarization, pattern detection, test generation and triage. They should not be treated as autonomous auditors. Generated suggestions may be incomplete, hallucinated or unable to understand protocol incentives. Human review, reproducible tests and independently validated specifications remain necessary. 15. Contemporary Developments and Professional PracticeSecurity practice is increasingly moving from contract-level review toward protocol-level assurance. This includes composability analysis, cross-chain messaging, account abstraction, intent-based execution, formalized token standards and automated on-chain monitoring. Cross-chain systems deserve particular caution because message verification, validator assumptions, replay protection and failure recovery span multiple domains. A professional security process should maintain a security register containing assets, threats, assumptions, controls, evidence, owners and residual risks. Before deployment, teams should use independent review, a tested deployment script, verified source code, multisignature administration and a rollback or containment plan where possible. After deployment, monitoring and governance procedures should remain active; security is not complete when the audit report is delivered. Chapter SummarySmart-contract security is a lifecycle discipline based on explicit assets, trust boundaries, invariants and adversarial assumptions. Reentrancy is controlled primarily by correct state ordering and carefully managed interactions. Authorization requires explicit roles, least privilege, replay-resistant signatures and secure initialization. Oracle-dependent systems must address manipulation, staleness, independence and governance. Frontrunning and MEV require slippage controls, deadlines, commit–reveal or suitable market mechanisms. Arithmetic review must include overflow, precision, decimals, rounding and extreme values. Denial-of-service risks arise from unbounded work and failure-prone push operations. Proxy systems add storage, initialization and upgrade-authority risks. Economic vulnerabilities require incentive analysis and adversarial simulation, not merely code inspection. Threat modelling establishes what can go wrong; static analysis, testing, fuzzing, symbolic execution and formal verification provide complementary evidence. Audits identify risk within a defined scope but cannot guarantee safety. Secure systems combine technical patterns, governance controls, monitoring, responsible disclosure and clearly stated assumptions. Key TermsAsset: Something requiring protection, such as funds, authority or data. Audit: A structured independent assessment of code, design and stated security controls. Authorization: The determination of whether an identified caller may perform an action. Checks-effects-interactions: A pattern that validates conditions, updates state and then performs external calls. Circuit breaker: A control that restricts activity when abnormal conditions are detected. Delegatecall: An operation that executes another contract’s code using the caller’s storage and context. Economic vulnerability: A design weakness that permits profitable behaviour contrary to protocol intent. Frontrunning: Exploiting knowledge of a pending transaction or likely ordering to obtain an advantage. Invariant: A property intended to remain true across valid state transitions. MEV: Value extracted by influencing or exploiting transaction ordering and inclusion. Oracle: A mechanism that supplies external data to a blockchain application. Proxy: A contract that delegates execution to implementation code, often to support upgrades. Reentrancy: Re-entry into a contract before an earlier interaction has completed. Replay attack: Reuse of a previously valid authorization in an unintended context or transaction. Slippage: The difference between an expected and actual execution price or amount. Static analysis: Automated inspection without executing the program. Threat model: A structured description of assets, actors, attack surfaces, assumptions and controls. Timelock: A delay between approval and execution of a sensitive operation. Trust boundary: An interface across which authority, data or control passes between different assumptions. Verification: Evidence that implementation satisfies specified properties, potentially through formal proof. Review QuestionsShort Answer Questions- Why is an external contract call considered a trust boundary?
- Describe the checks-effects-interactions pattern.
- Why is
tx.origin generally unsuitable for authorization? - State two causes of denial of service in Solidity systems.
- What additional risks are introduced by upgradeable proxy contracts?
Long Answer Questions- Explain reentrancy, including direct, cross-function and callback-based forms, and evaluate suitable mitigations.
- Discuss how an oracle can be manipulated and design a robust oracle-control framework for a lending protocol.
- Compare static analysis, fuzzing, symbolic execution and formal verification, including the limitations of each.
- Analyse the security trade-offs between immutable and upgradeable smart-contract deployments.
- Explain why economic security cannot be reduced to the absence of programming errors.
Analytical / Application Questions- A withdrawal function sends ether to a user before reducing the user’s balance. Identify the attack path and propose a corrected design.
- A protocol reads a token price from a low-liquidity pool immediately before calculating collateral. Construct an attack scenario and recommend layered controls.
- Design a threat model for a proxy-based lending application. Identify at least five assets, five threat actors or failure sources, major trust boundaries and corresponding evidence-based controls.
Multiple Choice Questions with AnswersQuestion 1Which sequence best implements the checks-effects-interactions pattern? A. External call, state update, input validation B. Input validation, state update, external call C. State update, external call, authorization check D. Authorization check, external call, state update Correct Answer: B. Input validation, state update, external call Question 2What is the principal danger of updating a withdrawal balance only after sending funds to the recipient? A. Integer division B. Oracle staleness C. Reentrancy D. Storage-slot collision Correct Answer: C. Reentrancy Question 3Which value is generally appropriate for identifying the immediate caller of a Solidity function? A. tx.origin B. block.timestamp C. msg.sender D. address(this).codehash Correct Answer: C. msg.sender Question 4Which feature most directly reduces the risk of using a stale oracle observation? A. A freshness or timestamp check B. Increasing the contract bytecode size C. Removing all events D. Using an unbounded loop Correct Answer: A. A freshness or timestamp check Question 5Which design most directly prevents one reverting recipient from blocking every payment in a distribution loop? A. A pull-payment model B. A larger recipient array C. An unchecked arithmetic block D. A public upgrade function Correct Answer: A. A pull-payment model Question 6Why are deadlines and minimum-output parameters useful in exchange transactions? A. They eliminate all validator discretion B. They limit execution at an unacceptable price or after excessive delay C. They make token decimals identical D. They prevent every smart-contract callback Correct Answer: B. They limit execution at an unacceptable price or after excessive delay Question 7What is a major proxy-specific security risk? A. The absence of any persistent storage B. Storage-layout incompatibility between implementations C. Automatic confidentiality of state D. Guaranteed prevention of unauthorized upgrades Correct Answer: B. Storage-layout incompatibility between implementations Question 8What does fuzzing primarily do in smart-contract testing? A. It proves every possible execution mathematically B. It generates varied inputs and sequences to find failures or violated properties C. It permanently encrypts contract storage D. It replaces access-control design Correct Answer: B. It generates varied inputs and sequences to find failures or violated properties Question 9A protocol uses the formula fee = floor(amount × rate ÷ D). What must be considered before implementation? A. Only the function name B. Intermediate overflow, units, denominator and rounding policy C. Whether all callers are validators D. Whether events can be omitted Correct Answer: B. Intermediate overflow, units, denominator and rounding policy Question 10Which statement best describes a formal-verification result? A. It proves the system is safe under every unstated assumption B. It establishes specified properties under the formal model and assumptions C. It guarantees that governance cannot be compromised D. It makes oracle data truthful Correct Answer: B. It establishes specified properties under the formal model and assumptions
|