You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现IPFS哈希主列表的查重与新增功能求助

Build an IPFS Hash Tracker with Duplicate Check (Python)

Hey Troy! Sounds like a solid project—let's put together a flexible Python script that manages your IPFS hash list with duplicate checks, and set it up so you can easily add features later.

First, Let's Define the JSON Structure

Let's start with a simple, scalable JSON format. Your file (let's call it ipfs_hashes.json) will look like this:

[
  {
    "hash": "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG",
    "description": "Sample IPFS hash for test content"
  }
]

This array of dictionaries makes it easy to search, add, and modify entries down the line.

Step 1: Core Functions to Handle the JSON File

We'll write reusable functions to load existing data, check for duplicates, add new entries, and save changes—keeping everything modular for future expansion.

1. Load Existing Hash Data

First, a function to load the JSON file. We'll handle the case where the file doesn't exist yet by automatically creating an empty list to start fresh:

import json
from typing import List, Dict

def load_ipfs_hashes(file_path: str) -> List[Dict]:
    try:
        with open(file_path, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        # Return empty list if file doesn't exist
        return []

2. Duplicate Check Function

This function will quickly check if a given IPFS hash already exists in your list:

def is_hash_duplicate(hashes_list: List[Dict], new_hash: str) -> bool:
    # Use `any()` for efficiency—it stops checking as soon as a match is found
    return any(entry['hash'] == new_hash for entry in hashes_list)

3. Add New Hash Entry Safely

Combine the above functions to add a new hash only if it's not a duplicate, then save the updated list back to JSON:

def add_ipfs_hash(file_path: str, new_hash: str, description: str) -> bool:
    hashes_list = load_ipfs_hashes(file_path)
    
    if is_hash_duplicate(hashes_list, new_hash):
        print(f"Error: Hash {new_hash} already exists in the list!")
        return False
    
    # Add the new entry to the list
    hashes_list.append({
        "hash": new_hash,
        "description": description
    })
    
    # Save the updated list back to JSON with indentation for readability
    with open(file_path, 'w') as f:
        json.dump(hashes_list, f, indent=2)
    
    print(f"Successfully added hash: {new_hash}")
    return True

Step 4: Test It Out!

Use the functions like this to start adding entries:

# Example usage
if __name__ == "__main__":
    IPFS_FILE = "ipfs_hashes.json"
    # Add a new valid entry
    add_ipfs_hash(IPFS_FILE, "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", "Test content for IPFS")
    # Try adding the same hash again (should trigger duplicate error)
    add_ipfs_hash(IPFS_FILE, "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", "Duplicate test")

Ideas for Future Expansion

Since you want to expand this later, here are some easy, modular next steps:

  • Search Function: Add a function to look up entries by hash or description (e.g., search_hashes(hashes_list, keyword="backup"))
  • Command-Line Interface: Use argparse to let you add/search hashes directly from the terminal, like python ipfs_tracker.py add QmXYZ... "My new project file"
  • IPFS Integration: Use the ipfshttpclient library to automatically generate hashes from local files and add them to your list in one step
  • Hash Validation: Add checks to ensure the input is a valid IPFS hash (e.g., starts with Qm for CIDv0 or bafybe for CIDv1)
  • Backup System: Add a function to create timestamped backups of your JSON file before making changes

This setup keeps everything decoupled, so you can add new features without breaking existing functionality.

内容的提问来源于stack exchange,提问作者Troy Wilson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:43:01