数据结构-Merkle Trees

从 https://simonwillison.net/2025/May/11/cursor-security/#atom-everything 看到的文章看到的相关文章了解到的。

Cursor 使用这个数据结构,用于快速定位到文件内容的变更,当数据块修改的时候,能够快速通过 hash 来找到变化的部分,我让 ai 给我做了个可交互的网页来理解这个数据结构,如下:

Merkle Tree Demo

    body {
        font-family: sans-serif;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px;
        background-color: #f4f4f4;
    }

    h1, h2 {
        color: #333;
    }

    .tree-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 30px;
        width: 100%;
        max-width: 800px; /* Limit max width */
    }

    .level {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
        width: 100%;
    }

    .node {
        background-color: #fff;
        border: 1px solid #ccc;
        padding: 10px 15px;
        margin: 0 5px;
        text-align: center;
        border-radius: 5px;
        word-break: break-all; /* Prevent long hashes from overflowing */
        box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
        transition: background-color 0.3s ease;
        min-width: 100px; /* Ensure some minimum width */
        flex-grow: 1; /* Allow nodes to grow */
        flex-basis: 0; /* Distribute space evenly */
    }

    .node label {
         display: block;
         margin-bottom: 5px;
         font-weight: bold;
         color: #555;
         font-size: 0.9em;
    }

    .node input[type="text"] {
        width: calc(100% - 12px); /* Adjust for padding/border */
        padding: 5px;
        border: 1px solid #ccc;
        border-radius: 3px;
        box-sizing: border-box; /* Include padding and border in element's total width */
        font-size: 0.9em;
    }

    .node .hash {
        font-family: 'Courier New', Courier, monospace;
        color: #007bff;
        font-size: 0.8em;
        margin-top: 5px;
    }

     /* Different colors for different levels */
    .level:last-child .node { background-color: #d4edda; border-color: #c3e6cb; color: #155724; } /* Root */
    .level:nth-last-child(2) .node { background-color: #fff3cd; border-color: #ffeeba; color: #856404; } /* Level 1 */
    .level:nth-last-child(3) .node { background-color: #d1ecf1; border-color: #bee5eb; color: #0c5460; } /* Level 0 (Leaf Parents) */
    /* Leaf level color handled explicitly in JS */

    .leaf-level .node {
         background-color: #f8d7da;
         border-color: #f5c6cb;
         color: #721c24;
         display: flex;
         flex-direction: column;
         align-items: center;
    }

     .leaf-level .node .hash {
         color: #721c24; /* Match text color */
         margin-top: 5px;
         font-size: 0.8em;
     }

    /* Lines (more complex for dynamic tree, simplified visual stacking here) */
    /* Could add lines using pseudo-elements or SVG/Canvas for true visual tree */

    #explanation {
        margin-top: 20px;
        padding: 15px;
        background-color: #e9ecef;
        border-left: 5px solid #007bff;
        max-width: 800px;
        color: #333;
    }
    #explanation h3 { margin-top: 0; }
    #explanation p { margin-bottom: 5px; }


Merkle Tree 默克尔树演示

修改下方的数据,观察上面的哈希值如何变化,尤其是最顶部的默克尔根。



    
    




    

默克尔树工作原理简介

    1. **叶子节点:** 底部是原始数据块(你可以修改它们)。

    2. **哈希计算:** 每个数据块首先计算出自己的哈希值(显示在输入框下方)。

    3. **层层向上:** 相邻的哈希值被组合(串联),然后计算新的哈希值,形成上一层的节点。

    4. **默克尔根:** 这个过程重复进行,直到最顶端只剩下一个哈希值,这就是默克尔根。

    5. **验证:** 默克尔根是整个数据集的"指纹"。如果任何一个数据块或其顺序改变,默克尔根都会完全不同。这使得只通过默克尔根就能快速验证数据的完整性,而无需检查所有数据。

    6. **应用:** 区块链(如比特币、以太坊)、点对点下载(如 BitTorrent)等都广泛使用默克尔树来高效地验证数据的完整性。




    // --- Hashing Function ---
    // Using the Web Crypto API (requires secure context - HTTPS, localhost)
    // Fallback/Simpler demo might use a library like crypto-js or a simpler non-cryptographic hash
    // For this demo, we'll use SHA-256 via Web Crypto API (async)

    async function sha256(message) {
        // encode as UTF-8
        const msgBuffer = new TextEncoder().encode(message);

        // hash the message
        const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

        // convert ArrayBuffer to Array
        const hashArray = Array.from(new Uint8Array(hashBuffer));

        // convert bytes to hex string
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        return hashHex;
    }

    // --- Merkle Tree Building Function ---
    async function buildMerkleTree(dataBlocks) {
        if (dataBlocks.length === 0) {
            return { root: null, levels: [] };
        }

        let currentLevel = [];
        const levels = []; // Store hashes at each level

        // 1. Compute Leaf Hashes
        const leafHashes = await Promise.all(dataBlocks.map(block => sha256(block)));
        currentLevel = leafHashes;
        levels.push(currentLevel); // levels[0] = leaf hashes

        // 2. Build Tree Levels upwards
        while (currentLevel.length > 1) {
            const nextLevel = [];
            for (let i = 0; i < currentLevel.length; i += 2) {
                const left = currentLevel[i];
                // Handle odd number of nodes: duplicate the last hash
                const right = (i + 1 < currentLevel.length) ? currentLevel[i + 1] : left;

                // Standard Merkle Tree pairing: hash(left_hash + right_hash)
                const parentHash = await sha256(left + right);
                nextLevel.push(parentHash);
            }
            currentLevel = nextLevel;
            levels.push(currentLevel); // levels[1] = level above leaves, etc.
        }

        const merkleRoot = currentLevel[0];
        return { root: merkleRoot, levels: levels };
    }

    // --- Display Function ---
    function renderTree(levels, dataBlocks) {
        const container = document.querySelector('.tree-container');
        container.innerHTML = ''; // Clear previous tree

        // Levels are stored bottom-up in the array (levels[0] is leaf hashes)
        // We want to render top-down visually

        // Render Root (top level)
        const rootLevelDiv = document.createElement('div');
        rootLevelDiv.classList.add('level', 'merkle-root-level');
        const rootNodeDiv = document.createElement('div');
        rootNodeDiv.classList.add('node');
        rootNodeDiv.innerHTML = `Merkle Root:

${levels[levels.length - 1][0]} `; rootLevelDiv.appendChild(rootNodeDiv); container.appendChild(rootLevelDiv);

        // Render intermediate levels (top-down, excluding root and leaves)
        for (let i = levels.length - 2; i > 0; i--) {
             const levelDiv = document.createElement('div');
             levelDiv.classList.add('level', `level-${i-1}`); // level-0 above leaves, level-1 etc.
             levels[i].forEach(hash => {
                 const nodeDiv = document.createElement('div');
                 nodeDiv.classList.add('node');
                  // Give generic labels for intermediate nodes
                 nodeDiv.innerHTML = `Hash:

${hash} `; levelDiv.appendChild(nodeDiv); }); container.appendChild(levelDiv); }

        // Render Leaf Level (bottom level)
        const leafLevelDiv = document.createElement('div');
        leafLevelDiv.classList.add('level', 'leaf-level');
        dataBlocks.forEach((data, index) => {
            const nodeDiv = document.createElement('div');
            nodeDiv.classList.add('node');
            // Assuming levels[0] contains the leaf hashes in order
            const leafHash = levels[0] && levels[0][index] ? levels[0][index] : 'Error';
            nodeDiv.innerHTML = `
                数据块 ${index + 1}:
                
                

${leafHash}

            `;
            leafLevelDiv.appendChild(nodeDiv);
        });
        container.appendChild(leafLevelDiv);

         // Add event listeners to new input fields
        attachInputListeners();
    }

    // --- Handle Input Changes ---
    const initialData = ["数据 A", "数据 B", "数据 C", "数据 D"]; // Starting data blocks
    let currentData = [...initialData]; // Use a copy

    async function updateTree() {
         const { root, levels } = await buildMerkleTree(currentData);
         renderTree(levels, currentData);
         console.log("Merkle Root:", root);
         // Merkle root is already displayed by renderTree
    }

    function attachInputListeners() {
         document.querySelectorAll('.leaf-level input[type="text"]').forEach(input => {
             input.addEventListener('input', (event) => {
                 const index = parseInt(event.target.dataset.index, 10);
                 currentData[index] = event.target.value;
                 updateTree(); // Recalculate and re-render the tree
             });
         });
    }

    // --- Initial Load ---
    // Use a small delay to ensure DOM is ready, though async functions help
    document.addEventListener('DOMContentLoaded', () => {
        updateTree(); // Build and render the tree on page load
    });

当修改数据块中的文字,会让对应的树分支上的 hash 修改,一直向上延伸到 root,通过 hash 的对比快速的就能够获取到整个变动的分支。

评论

正在加载评论…

发表评论

评论需审核通过后才会显示。