phink 0.1.5

🐙 Phink, a ink! smart-contract property-based and coverage-guided fuzzer
Documentation
<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Starting a campaign - Phink Book</title>


        <!-- Custom HTML head -->
        
        <meta name="description" content="Documentation for Phink fuzzer">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff">

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body class="sidebar-visible no-js">
    <div id="body-container">
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('light')
            html.classList.add(theme);
            var body = document.querySelector('body');
            body.classList.remove('no-js')
            body.classList.add('js');
        </script>

        <input type="checkbox" id="sidebar-toggle-anchor" class="hidden">

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var body = document.querySelector('body');
            var sidebar = null;
            var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            } else {
                sidebar = 'hidden';
            }
            sidebar_toggle.checked = sidebar === 'visible';
            body.classList.remove('sidebar-visible');
            body.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="INTRO.html">Introduction</a></li><li class="chapter-item expanded affix "><li class="part-title">User guide</li><li class="chapter-item expanded "><a href="START.html"><strong aria-hidden="true">1.</strong> Installation</a></li><li class="chapter-item expanded "><a href="CONFIG.html"><strong aria-hidden="true">2.</strong> Configuration</a></li><li class="chapter-item expanded "><a href="CAMPAIGN.html" class="active"><strong aria-hidden="true">3.</strong> Starting a campaign</a></li><li class="chapter-item expanded "><a href="INVARIANTS.html"><strong aria-hidden="true">4.</strong> Invariants</a></li><li class="chapter-item expanded "><a href="RUNTIME.html"><strong aria-hidden="true">5.</strong> Plug-in your runtime</a></li><li class="chapter-item expanded "><a href="SEEDS.html"><strong aria-hidden="true">6.</strong> Seeds</a></li><li class="chapter-item expanded affix "><li class="part-title">Concepts and understanding</li><li class="chapter-item expanded "><a href="CONCEPT.html"><strong aria-hidden="true">7.</strong> Concept and terminology</a></li><li class="chapter-item expanded "><a href="TECH.html"><strong aria-hidden="true">8.</strong> How does Phink work</a></li><li class="chapter-item expanded "><a href="TROUBLESHOTING.html"><strong aria-hidden="true">9.</strong> Troubleshoting</a></li><li class="chapter-item expanded "><a href="BENCHMARKS.html"><strong aria-hidden="true">10.</strong> Benchmarks</a></li><li class="chapter-item expanded "><a href="FAQ.html"><strong aria-hidden="true">11.</strong> FAQ</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle">
                <div class="sidebar-resize-indicator"></div>
            </div>
        </nav>

        <!-- Track and set sidebar scroll position -->
        <script>
            var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
            sidebarScrollbox.addEventListener('click', function(e) {
                if (e.target.tagName === 'A') {
                    sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
                }
            }, { passive: true });
            var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
            sessionStorage.removeItem('sidebar-scroll');
            if (sidebarScrollTop) {
                // preserve sidebar scroll position when navigating via links within sidebar
                sidebarScrollbox.scrollTop = sidebarScrollTop;
            } else {
                // scroll sidebar to current active section when navigating via "next/previous chapter" buttons
                var activeSection = document.querySelector('#sidebar .active');
                if (activeSection) {
                    activeSection.scrollIntoView({ block: 'center' });
                }
            }
        </script>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky">
                    <div class="left-buttons">
                        <label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </label>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Phink Book</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                        <a href="https://github.com/srlabs/phink/" title="Git repository" aria-label="Git repository">
                            <i id="git-repository-button" class="fa fa-github"></i>
                        </a>
                        <a href="https://github.com/srlabs/phink/blob/main/src/src/CAMPAIGN.md" title="Suggest an edit" aria-label="Suggest an edit">
                            <i id="git-edit-button" class="fa fa-edit"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h2 id="writing-properties-for-ink-contracts"><a class="header" href="#writing-properties-for-ink-contracts">Writing properties for ink! contracts</a></h2>
<h3 id="adding-properties"><a class="header" href="#adding-properties">Adding properties</a></h3>
<h4 id="inside-your-cargotoml"><a class="header" href="#inside-your-cargotoml">Inside your <code>Cargo.toml</code></a></h4>
<p>First, you need to add the <code>phink</code> feature to your <code>Cargo.toml</code>, such as:</p>
<pre><code class="language-toml">[features]
phink = []
</code></pre>
<h4 id="inside-your-filers"><a class="header" href="#inside-your-filers">Inside your <code>file.rs</code></a></h4>
<p>Then, you can use the following example to create invariants. Create another <code>impl</code> in your contract, and
put
it under the feature of <code>phink</code>. Use <code>assert!</code> or <code>panic!</code> for your properties.</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[cfg(feature = "phink")]
#[ink(impl)]
impl DomainNameService {
    // This invariant ensures that nobody registed the forbidden number
    #[ink(message)]
    #[cfg(feature = "phink")]
    pub fn phink_assert_dangerous_number(&amp;self) {
        let forbidden_number = 42;
        assert_ne!(self.dangerous_number, forbidden_number);
    }
}
<span class="boring">}</span></code></pre></pre>
<p>You can find more informations in the page dedicated to <a href="INVARIANTS.html">invariants</a>.</p>
<h2 id="running-phink"><a class="header" href="#running-phink">Running Phink</a></h2>
<h3 id="1-instrument-the-contract"><a class="header" href="#1-instrument-the-contract">1. Instrument the contract</a></h3>
<p>First things first: Let’s enable your contract for fuzzing. Run the following command to instrument your ink! smart
contract:</p>
<pre><code class="language-sh">cargo run -- instrument my_contract/
</code></pre>
<p>This step modifies the contract to include necessary hooks for Phink’s fuzzing process. It creates a fork of the
contract, so you don’t have to make a copy before.</p>
<h3 id="2-generate-seeds-optionnal-but-highly-recommended"><a class="header" href="#2-generate-seeds-optionnal-but-highly-recommended">2. Generate seeds (optionnal but highly recommended)</a></h3>
<p>The <code>cargo run -- generate-seed</code> command is an optional but powerful feature that enhances your fuzzing experience by
generating initial seeds from your existing unit and end-to-end (E2E) tests.</p>
<h4 id="what-it-does"><a class="header" href="#what-it-does">What it Does</a></h4>
<p><code>cargo run -- generate-seed</code> executes the unit tests and E2E tests of your ink! smart contract, extracting seeds based
on
executed messages. These seeds are saved in the <code>corpus/</code> directory, which highly helps to reach good coverage, as long
as you have good tests.
<strong>Therefore, we encourage to have good and various unit-tests and E2E tests in your contract.</strong></p>
<h4 id="how-it-works"><a class="header" href="#how-it-works">How It Works</a></h4>
<ul>
<li>
<p><strong>Unit Tests</strong>: The command runs through all defined unit tests and captures the invoked messages, with Alice as the
origin and a value of 0.</p>
</li>
<li>
<p><strong>End-to-End Tests</strong>: For E2E tests, Phink modifies the <code>Cargo.toml</code> to point to
a <a href="https://github.com/kevin-valerio/ink/commit/5869d341ff13a454c22a6980fd232f4520721b97">custom ink! repository</a>. This
step
ensures necessary modifications are included to print debug messages containing the message’s 4-byte hash and
scale-encoded parameters to stdout.</p>
</li>
<li>
<p>If a test invokes at least one message, Phink extracts them all as seeds for use during fuzzing.</p>
</li>
</ul>
<h4 id="usage"><a class="header" href="#usage">Usage</a></h4>
<pre><code class="language-sh">cargo run -- generate-seed &lt;CONTRACT&gt; [COMPILED_DIRECTORY]
</code></pre>
<ul>
<li><code>&lt;CONTRACT&gt;</code>: The root directory path of your ink! smart contract.</li>
<li><code>[COMPILED_DIRECTORY]</code>: Optional path for where the temporary contract will be compiled. Defaults to <code>tmp</code> if
unspecified.</li>
</ul>
<p>This will generate a set of initial inputs, derived from your current tests, to kickstart fuzzing.</p>
<h4 id="why-using-generate-seed"><a class="header" href="#why-using-generate-seed">Why using <code>generate-seed</code>?</a></h4>
<p>Generating seeds from your existing test suite can increase the efficiency of fuzz testing by:</p>
<ul>
<li>Providing a good starting point for fuzzing inputs.</li>
<li>Ensuring that the fuzzing process begins with valid and meaningful test cases.</li>
</ul>
<p>For more information on how seeds work with Phink, refer to
the <a href="SEEDS.html">seeds documentation</a>.</p>
<h3 id="3-run-the-fuzzer"><a class="header" href="#3-run-the-fuzzer">3. Run the fuzzer</a></h3>
<p>After <strong>instrumenting</strong> your contract and <strong>writing</strong> properties and <strong>configuring</strong> your <code>phink.toml</code>, let’s get our
hands on the fuzzing process:</p>
<pre><code class="language-sh">cargo run -- fuzz
</code></pre>
<p>After executing this command, your fuzzing tests will begin based on the configurations specified in your <code>phink.toml</code>
file. You should see a user interface appear.</p>
<p>If you’re utilizing the advanced UI, you’ll receive <em>real-time</em> updates on the fuzzed messages at the bottom of the
screen. For more detailed log information, you can use the following command:</p>
<pre><code class="language-sh">watch -c -t -n 0.5 "clear &amp;&amp; cat output/phink/logs/last_seed.phink" # `output` is the default, but it depends of your `phink.toml`
</code></pre>
<p>This will provide you with clearer logs by continuously updating them every <strong>0.1</strong> seconds.</p>
<h2 id="analyzing-results"><a class="header" href="#analyzing-results">Analyzing results</a></h2>
<h3 id="crashes"><a class="header" href="#crashes">Crashes</a></h3>
<p>In case of crashes, you should see something like the following.</p>
<img src="https://raw.githubusercontent.com/srlabs/phink/refs/heads/main/assets/crashed.png" alt="crash"/>
<p>To analyze the crash, you can run <code>cargo run -- execute &lt;your_crash&gt;</code>, for instance
<code>cargo run -- execute output/phink/crashes/1729082451630/id:000000,sig:06,src:000008,time:627512,execs:3066742,op:havoc,rep:2</code></p>
<div class="table-wrapper"><table><thead><tr><th>Component</th><th>Description</th></tr></thead><tbody>
<tr><td>1729082451630</td><td>Timestamp representing when the crash was recorded</td></tr>
<tr><td>id:000000</td><td>Unique identifier for the crash</td></tr>
<tr><td>sig:06</td><td>Signal number that triggered the crash</td></tr>
<tr><td>src:000008</td><td>Source test case number</td></tr>
<tr><td>time:627512</td><td>Execution time since the start of the testing process</td></tr>
<tr><td>execs:3066742</td><td>Cumulative number of executions performed until the crash</td></tr>
<tr><td>op:havoc,rep:2</td><td>Type of fuzzing operation (havoc) and its repetition number</td></tr>
</tbody></table>
</div>
<p>By running the above command, you should get an output similar to the screenshot below:</p>
<img src="https://raw.githubusercontent.com/srlabs/phink/refs/heads/main/assets/backtrace.png" alt="crash"/>
<h3 id="coverage"><a class="header" href="#coverage">Coverage</a></h3>
<p><strong>This feature is in alpha and unstable.</strong></p>
<h4 id="generating-a-coverage-report"><a class="header" href="#generating-a-coverage-report">Generating a coverage report</a></h4>
<p>First, you need to create a <code>traces.cov</code> file. For this, execute the command below.</p>
<pre><code class="language-sh">cargo run -- run  
</code></pre>
<p>Once done, generate coverage reports to analyze which parts of the contract were tested:</p>
<pre><code class="language-sh">cargo run -- coverage my_contract/
</code></pre>
<p>Some HTML files should then be generated in the path you’ve configured inside your <code>phink.toml</code>. The coverage report
provides a visual representation of the tested code areas. As a rule of thumb, the more green lines you can see there,
the better it is for the code.</p>
<h3 id="coverage-report-example"><a class="header" href="#coverage-report-example">Coverage report example</a></h3>
<p><strong>Green Lines</strong>: Code that has been tested.</p>
<p><img src="https://raw.githubusercontent.com/srlabs/phink/refs/heads/main/assets/coverage_1.png" alt="Coverage Report Part 1" /></p>
<p><em>Figure 1: Coverage Report of one specific file.</em></p>
<img src="https://raw.githubusercontent.com/srlabs/phink/refs/heads/main/assets/coverage_2.png" alt="coverage_2" width="400"/>
<p><em>Figure 2: List of fuzzed Rust files from the ink! smart-contract.</em></p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="CONFIG.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next prefetch" href="INVARIANTS.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="CONFIG.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next prefetch" href="INVARIANTS.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script>
            window.playground_copyable = true;
        </script>


        <script src="elasticlunr.min.js"></script>
        <script src="mark.min.js"></script>
        <script src="searcher.js"></script>

        <script src="clipboard.min.js"></script>
        <script src="highlight.js"></script>
        <script src="book.js"></script>

        <!-- Custom JS scripts -->


    </div>
    </body>
</html>