基于Web3.0的区块链图片上传

开始前,我们先简单了解一下基本的概念,我大致归纳为以下几个点
什么是Web3.0,和区块链又有什么关系?(上回的文章不就派上用场了)

需求:开发一个基于Python的Web 3.0图片上传系统。这个系统将允许用户上传图片,并将图片存储在去中心化的网络上,同时记录交易信息在区块链上。

本就是写着玩的,想过要写成用户认证文件操作集成全套管理的,让他'终将成为图片上传服务的最终解决方案'

实际下来却发现不是很实际,就作罢了,奈何我一直以来对图片这么执着

步骤概述

  1. 环境设置:使用Python开发,安装必要的Python库。
  2. IPFS集成:将图片上传到IPFS,获取图片的CID(Content Identifier)。
  3. 区块链集成:将IPFS CID记录在区块链上。
  4. Web接口:使用Flask创建一个Web接口,允许用户上传图片。

详细步骤

1. 环境设置

安装所需的Python库:

bash 复制代码
pip install flask web3 ipfshttpclient

2. IPFS集成

IPFS(InterPlanetary File System)是一种点对点的文件存储协议。我们可以使用ipfshttpclient库来与IPFS网络交互。

首先,确保你已经安装并运行了IPFS节点。如果还没有安装IPFS,可以在IPFS官网找到安装指南。

以下是上传图片到IPFS的代码示例:

python 复制代码
import ipfshttpclient

def upload_to_ipfs(file_path):
    client = ipfshttpclient.connect('/ip4/127.0.0.1/tcp/5001')
    res = client.add(file_path)
    return res['Hash']

3. 区块链集成

使用web3.py库将IPFS CID记录到区块链上。我们将以太坊(Ethereum)作为示例区块链。

以下是一个简单的智能合约示例,用于存储IPFS CID:

solidity 复制代码
pragma solidity ^0.8.0;

contract IPFSStorage {
    mapping(address => string[]) public userCIDs;

    function storeCID(string memory cid) public {
        userCIDs[msg.sender].push(cid);
    }

    function getCIDs() public view returns (string[] memory) {
        return userCIDs[msg.sender];
    }
}

编译并部署该合约后,使用以下Python代码与智能合约交互:

python 复制代码
from web3 import Web3

# 连接到以太坊节点
w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))

# 合约地址和ABI(在部署合约后获取)
contract_address = 'YOUR_CONTRACT_ADDRESS'
contract_abi = 'YOUR_CONTRACT_ABI'

contract = w3.eth.contract(address=contract_address, abi=contract_abi)

def store_cid_on_blockchain(cid, account, private_key):
    txn = contract.functions.storeCID(cid).buildTransaction({
        'from': account,
        'nonce': w3.eth.getTransactionCount(account),
        'gas': 2000000,
        'gasPrice': w3.toWei('50', 'gwei')
    })

    signed_txn = w3.eth.account.sign_transaction(txn, private_key=private_key)
    txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    return txn_hash.hex()

4. Web接口

使用Flask创建一个Web接口来上传图片。

python 复制代码
from flask import Flask, request, jsonify
import os

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'})
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'})

    if file:
        file_path = os.path.join('/path/to/save/uploads', file.filename)
        file.save(file_path)

        # 上传到IPFS
        cid = upload_to_ipfs(file_path)

        # 存储到区块链
        account = 'YOUR_ETHEREUM_ACCOUNT'
        private_key = 'YOUR_PRIVATE_KEY'
        txn_hash = store_cid_on_blockchain(cid, account, private_key)

        return jsonify({'cid': cid, 'transaction_hash': txn_hash})

if __name__ == '__main__':
    app.run(debug=True)

上传成功后会返回一个HASH的值,这个就是图片在ipfs上的ID。

本地网关访问:ipfs://QmVJGX3FJPZsAgGMtJZoTt14XBj8QKhPwaaP4UfCcvYaN2 、ipfs://QmRF9mejyfq89vAJ5yfsBbmVY3RUcLqfSsVTAmAbS8U2xD

外网网关:https://ipfs.crossbell.io/ipfs/QmVJGX3FJPZsAgGMtJZoTt14XBj8QKhPwaaP4UfCcvYaN2https://ipfs.crossbell.io/ipfs/QmRF9mejyfq89vAJ5yfsBbmVY3RUcLqfSsVTAmAbS8U2xD

智能合约

我们将使用Solidity编写智能合约,用solc编译器编译合约,并使用web3.py库部署合约到以太坊网络。

1. 编写智能合约代码

首先,创建一个Solidity文件(如IPFSStorage.sol),并编写你的智能合约代码:

solidity 复制代码
// IPFSStorage.sol
pragma solidity ^0.8.0;

contract IPFSStorage {
    mapping(address => string[]) public userCIDs;

    function storeCID(string memory cid) public {
        userCIDs[msg.sender].push(cid);
    }

    function getCIDs() public view returns (string[] memory) {
        return userCIDs[msg.sender];
    }
}

2. 编译智能合约

要编译Solidity智能合约,我们可以使用solc编译器。你可以通过以下命令安装Solidity编译器:

bash 复制代码
npm install -g solc

然后,使用以下命令编译智能合约:

bash 复制代码
solc --abi --bin IPFSStorage.sol -o build/

这将生成两个文件:IPFSStorage.abi(合约的ABI)和IPFSStorage.bin(合约的字节码)。

3. 部署智能合约

使用web3.py库部署合约。确保你已经运行了一个以太坊节点(如使用Ganache本地开发环境)。

首先,安装web3.py

bash 复制代码
pip install web3

然后,编写并运行以下Python脚本来部署合约:

python 复制代码
from web3 import Web3

# 连接到以太坊节点(使用Ganache本地节点为例)
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:7545'))

# 读取合约的ABI和字节码
with open('build/IPFSStorage.abi', 'r') as abi_file:
    contract_abi = abi_file.read()

with open('build/IPFSStorage.bin', 'r') as bin_file:
    contract_bytecode = bin_file.read()

# 设置部署账号和私钥(使用Ganache提供的账号)
deployer_account = '0xYourAccountAddress'
private_key = 'YourPrivateKey'

# 创建合约对象
IPFSStorage = w3.eth.contract(abi=contract_abi, bytecode=contract_bytecode)

# 构建交易
transaction = IPFSStorage.constructor().buildTransaction({
    'from': deployer_account,
    'nonce': w3.eth.getTransactionCount(deployer_account),
    'gas': 2000000,
    'gasPrice': w3.toWei('50', 'gwei')
})

# 签署交易
signed_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)

# 发送交易并获取交易哈希
txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
print(f'Transaction hash: {txn_hash.hex()}')

# 等待交易确认
txn_receipt = w3.eth.waitForTransactionReceipt(txn_hash)
print(f'Contract deployed at address: {txn_receipt.contractAddress}')

总结

编译智能合约生成的ABI和字节码用于与合约交互,部署合约则涉及到创建交易、签署交易并将交易发送到以太坊网络。部署成功后,可以通过交易回执获取合约地址,并使用这个地址与合约进行交互。

相关推荐
日更嵌入式的打工仔8 小时前
LAN9253中文注释第七章
笔记·原文翻译
Li emily11 小时前
如何获取港股实时行情数据API接口
api·fastapi·港股
山岚的运维笔记12 小时前
SQL Server笔记 -- 第53章:INSERT 第54章:主键
数据库·笔记·sql·microsoft·sqlserver
weixin_4481199413 小时前
Datawhale 大模型算法全栈基础篇 202602第1次笔记
笔记
柳鲲鹏13 小时前
股市赚钱学概论:自序
笔记
烟花落o14 小时前
算法的时间复杂度和空间复杂度
开发语言·数据结构·笔记·算法
Blue16°15 小时前
Day28:英语翻译 + 单词打卡
笔记
xian_wwq16 小时前
【学习笔记】OAuth 2.0 安全攻防:从 Portswigger 六大实验看认证漏洞挖掘
笔记·学习·安全
山野万里_16 小时前
B站DR_CAN【Advanced控制理论】课程笔记
笔记
2501_9011478316 小时前
粉刷房子问题:从DP基础到空间极致优化学习笔记
笔记·学习·动态规划