经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 其他 » 区块链 » 查看文章
基于Web3.0的区块链图片上传
来源:cnblogs  作者:阿珏酱  时间:2024/6/19 15:17:46  对本文有异议

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

需求:开发一个基于Python的Web 3.0图片上传系统。这个系统将允许用户上传图片,并将图片存储在去中心化的网络上,同时记录交易信息在区块链上。
本就是写着玩的,想过要写成用户认证文件操作集成全套管理的,让他‘终将成为图片上传服务的最终解决方案’
实际下来却发现不是很实际,就作罢了,奈何我一直以来对图片这么执着

步骤概述

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

详细步骤

1. 环境设置

安装所需的Python库:

  1. pip install flask web3 ipfshttpclient

2. IPFS集成

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

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

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

  1. import ipfshttpclient
  2. def upload_to_ipfs(file_path):
  3. client = ipfshttpclient.connect('/ip4/127.0.0.1/tcp/5001')
  4. res = client.add(file_path)
  5. return res['Hash']

3. 区块链集成

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

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

  1. pragma solidity ^0.8.0;
  2. contract IPFSStorage {
  3. mapping(address => string[]) public userCIDs;
  4. function storeCID(string memory cid) public {
  5. userCIDs[msg.sender].push(cid);
  6. }
  7. function getCIDs() public view returns (string[] memory) {
  8. return userCIDs[msg.sender];
  9. }
  10. }

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

  1. from web3 import Web3
  2. # 连接到以太坊节点
  3. w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
  4. # 合约地址和ABI(在部署合约后获取)
  5. contract_address = 'YOUR_CONTRACT_ADDRESS'
  6. contract_abi = 'YOUR_CONTRACT_ABI'
  7. contract = w3.eth.contract(address=contract_address, abi=contract_abi)
  8. def store_cid_on_blockchain(cid, account, private_key):
  9. txn = contract.functions.storeCID(cid).buildTransaction({
  10. 'from': account,
  11. 'nonce': w3.eth.getTransactionCount(account),
  12. 'gas': 2000000,
  13. 'gasPrice': w3.toWei('50', 'gwei')
  14. })
  15. signed_txn = w3.eth.account.sign_transaction(txn, private_key=private_key)
  16. txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
  17. return txn_hash.hex()

4. Web接口

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

  1. from flask import Flask, request, jsonify
  2. import os
  3. app = Flask(__name__)
  4. @app.route('/upload', methods=['POST'])
  5. def upload_file():
  6. if 'file' not in request.files:
  7. return jsonify({'error': 'No file part'})
  8. file = request.files['file']
  9. if file.filename == '':
  10. return jsonify({'error': 'No selected file'})
  11. if file:
  12. file_path = os.path.join('/path/to/save/uploads', file.filename)
  13. file.save(file_path)
  14. # 上传到IPFS
  15. cid = upload_to_ipfs(file_path)
  16. # 存储到区块链
  17. account = 'YOUR_ETHEREUM_ACCOUNT'
  18. private_key = 'YOUR_PRIVATE_KEY'
  19. txn_hash = store_cid_on_blockchain(cid, account, private_key)
  20. return jsonify({'cid': cid, 'transaction_hash': txn_hash})
  21. if __name__ == '__main__':
  22. 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),并编写你的智能合约代码:

  1. // IPFSStorage.sol
  2. pragma solidity ^0.8.0;
  3. contract IPFSStorage {
  4. mapping(address => string[]) public userCIDs;
  5. function storeCID(string memory cid) public {
  6. userCIDs[msg.sender].push(cid);
  7. }
  8. function getCIDs() public view returns (string[] memory) {
  9. return userCIDs[msg.sender];
  10. }
  11. }

2. 编译智能合约

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

  1. npm install -g solc

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

  1. solc --abi --bin IPFSStorage.sol -o build/

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

3. 部署智能合约

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

首先,安装web3.py

  1. pip install web3

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

  1. from web3 import Web3
  2. # 连接到以太坊节点(使用Ganache本地节点为例)
  3. w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:7545'))
  4. # 读取合约的ABI和字节码
  5. with open('build/IPFSStorage.abi', 'r') as abi_file:
  6. contract_abi = abi_file.read()
  7. with open('build/IPFSStorage.bin', 'r') as bin_file:
  8. contract_bytecode = bin_file.read()
  9. # 设置部署账号和私钥(使用Ganache提供的账号)
  10. deployer_account = '0xYourAccountAddress'
  11. private_key = 'YourPrivateKey'
  12. # 创建合约对象
  13. IPFSStorage = w3.eth.contract(abi=contract_abi, bytecode=contract_bytecode)
  14. # 构建交易
  15. transaction = IPFSStorage.constructor().buildTransaction({
  16. 'from': deployer_account,
  17. 'nonce': w3.eth.getTransactionCount(deployer_account),
  18. 'gas': 2000000,
  19. 'gasPrice': w3.toWei('50', 'gwei')
  20. })
  21. # 签署交易
  22. signed_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)
  23. # 发送交易并获取交易哈希
  24. txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
  25. print(f'Transaction hash: {txn_hash.hex()}')
  26. # 等待交易确认
  27. txn_receipt = w3.eth.waitForTransactionReceipt(txn_hash)
  28. print(f'Contract deployed at address: {txn_receipt.contractAddress}')

总结

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

原文链接:https://www.cnblogs.com/Ajue/p/18252860

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号