博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
以太坊ipfs_动手:Infura和以太坊上的IPFS入门
阅读量:2519 次
发布时间:2019-05-11

本文共 9751 字,大约阅读时间需要 32 分钟。

以太坊ipfs

by Niharika Singh

由Niharika Singh

动手:Infura和以太坊上的IPFS入门 (Hands On: Get Started With Infura and the IPFS on Ethereum)

为什么选择Infura? (Why Infura?)

There are a lot of pain points being faced by blockchain which may be solved by Infura and/or the InterPlanetary File System (IPFS), to some extent. These are the main challenges:

区块链面临很多难题,Infura和/或行星际文件系统(IPFS)可以在一定程度上解决这些难题。 这些是主要挑战:

  1. It’s expensive to store data on the Ethereum blockchain

    在以太坊区块链上存储数据非常昂贵
  2. It’s tough to configure an Ethereum geth client

    配置以太坊geth客户端很困难
  3. It’s tough to scale the infrastructure

    扩展基础架构非常困难

If you use Infura, access to the Ethereum network and the IPFS becomes a lot faster. It no longer takes hours to sync up the geth client which uses up a huge chunk of memory and bandwidth while the entire blockchain gets downloaded.

如果您使用Infura,则访问以太坊网络和IPFS的速度将大大提高。 同步geth客户端不再花费数小时,该客户端在下载整个区块链时会占用大量内存和带宽。

Here are some other advantages that come with using Infura:

以下是使用Infura的其他一些优点:

  • Huge amounts of data can be stored on the IPFS, and just the hash of the file can be stored on Ethereum.

    大量数据可以存储在IPFS上,而只是文件的哈希可以存储在以太坊上。
  • Infura provides secure, reliable, scalable, and easy to use APIs to access the Ethereum network and the IPFS. Developers do not have to worry about the infrastructure of an Ethereum node or an IPFS node. That is taken care of by Infura.

    Infura提供安全,可靠,可扩展且易于使用的API来访问以太坊网络和IPFS。 开发人员不必担心以太坊节点或IPFS节点的基础架构。 这由Infura负责。
  • Infura provides TLS enabled public endpoints.

    Infura提供启用TLS的公共端点。
  • The code is portable on Ethereum’s interface using JSON RPC, Web3.

    该代码可使用JSON RPC Web3在以太坊的界面上移植。
  • Infura is practically a developer’s Swiss Army knife, and also saves the deployment team from the hell of scalability issues.

    Infura实际上是开发人员的瑞士军刀,也使部署团队免于遭受可扩展性问题的困扰。
  • And finally, Infura is trusted:

    最后,Infura值得信赖:

dApp说明 (dApp Description)

Our dApp will take a file as input from a user and upload it to the IPFS by invoking an Ethereum contract. The hash of the file will be stored on Ethereum.

我们的dApp将从用户那里获取文件作为输入,并通过调用以太坊合约将其上传到IPFS。 文件的哈希值将存储在以太坊上。

This is the process we’ll go through:

这是我们要经历的过程:

  1. Take file as an input

    将文件作为输入
  2. Convert file to buffer

    将文件转换为缓冲区
  3. Upload buffer to IPFS

    将缓冲区上传到IPFS
  4. Store hash of file returned by IPFS

    存储IPFS返回的文件的哈希
  5. Get user’s Metamask Ethereum address

    获取用户的Metamask以太坊地址
  6. User confirms transaction to Ethereum via Metamask

    用户通过Metamask确认与以太坊的交易
  7. IPFS hash is written on Ethereum

    IPFS哈希值写在以太坊上

涉及的技术栈 (Tech Stack Involved)

  • — Front end library

    —前端库

  • — The language used to build smart contracts that runs on Ethereum

    -用于构建在以太坊上运行的智能合约的语言

  • — Decentralized storage

    —分散存储

  • —API access to Ethereum network and IPFS

    对以太坊网络和IPFS的API访问

让我们编码! (Let’s Code!)

Make sure you already have Metamask downloaded. If not, download it from .

确保您已经下载了Metamask。 如果没有,请从下载。

Also, keep your Node and NPM up to date.

另外,保持您的节点和NPM为最新。

安装以下依赖项: (Install the following dependencies:)

$ npm i -g create-react-app$ npm install react-bootstrap$ npm install fs-extra$ npm install ipfs-api$ npm install web3

After you’re done, run the following command on your CLI to create a sample React project. I’ll name my project ipfs.

完成后,在CLI上运行以下命令以创建示例React项目。 我将项目命名为ipfs

$ create-react-app ipfs

在Ropsten Testnet上部署智能合约 (Deploy the Smart Contract on Ropsten Testnet)

.Make sure you’re on Ropsten testnet on metamask.

确保在元掩码上使用Ropsten测试网。

To deploy the smart contract, we need ether. To get ether for Ropsten testnet, go to .

要部署智能合约,我们需要以太币。 要获取Ropsten测试网的以太币,请访问 。

To deploy the smart contract, go to .

要部署智能合约,请访问 。

pragma solidity ^0.4.17;
contract Contract { string ipfsHash;  function setHash(string x) public {   ipfsHash = x; } function getHash() public view returns (string x) {   return ipfsHash; }
}

Save the address of smart contract. Mine is: 0x610DD75057738B73e3F17A9D607dB16A44f962F1

保存智能合约的地址。 我的是:0x610DD75057738B73e3F17A9D607dB16A44f962F1

Also, save the Application Binary Interface (ABI) in JSON. It can be found in the ‘compile’ tab, under ‘details’.

另外,将应用程序二进制接口(ABI)保存为JSON。 可以在“详细信息”下的“编译”选项卡中找到。

Mine is the following:

我的是:

[ {  "constant": false,  "inputs": [   {    "name": "x",    "type": "string"   }  ],  "name": "sendHash",  "outputs": [],  "payable": false,  "stateMutability": "nonpayable",  "type": "function" }, {  "constant": true,  "inputs": [],  "name": "getHash",  "outputs": [   {    "name": "x",    "type": "string"   }  ],  "payable": false,  "stateMutability": "view",  "type": "function" }]

In the “ipfs/src” directory, create the following files: web3.js, ipfs.js, and storehash.js.

在“ ipfs / src”目录中,创建以下文件: web3.jsipfs.jsstorehash.js

文件1 — Web3.js (File 1 — Web3.js)

import Web3 from 'web3';
const web3 = new Web3(window.web3.currentProvider);
export default web3;

文件2 — Storehash.js (File 2 — Storehash.js)

import web3 from './web3';
//Your contract addressconst address = '0x610dd75057738b73e3f17a9d607db16a44f962f1';
//Your contract ABIconst abi = [ {  "constant": false,  "inputs": [   {    "name": "x",    "type": "string"   }  ],  "name": "sendHash",  "outputs": [],  "payable": false,  "stateMutability": "nonpayable",  "type": "function" }, {  "constant": true,  "inputs": [],  "name": "getHash",  "outputs": [   {    "name": "x",    "type": "string"   }  ],  "payable": false,  "stateMutability": "view",  "type": "function" }]
export default new web3.eth.Contract(abi, address);

文件3 — Ipfs.js (File 3 — Ipfs.js)

const IPFS = require('ipfs-api');const ipfs = new IPFS({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' });
export default ipfs;

编辑— Index.js (Edit — Index.js)

import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import registerServiceWorker from './registerServiceWorker';import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(
, document.getElementById('root'));registerServiceWorker();

文件4 — App.js (File 4 — App.js)

import React, { Component } from 'react';import web3 from './web3';import ipfs from './ipfs';import storehash from './storehash';import { Button } from 'reactstrap';
class App extends Component {
state = {      ipfsHash:null,      buffer:'',      ethAddress:'',      transactionHash:'',      txReceipt: ''    };
//Take file input from usercaptureFile =(event) => {        event.stopPropagation()        event.preventDefault()        const file = event.target.files[0]        let reader = new window.FileReader()        reader.readAsArrayBuffer(file)        reader.onloadend = () => this.convertToBuffer(reader)      };
//Convert the file to buffer to store on IPFS convertToBuffer = async(reader) => {      //file is converted to a buffer for upload to IPFS        const buffer = await Buffer.from(reader.result);      //set this buffer-using es6 syntax        this.setState({buffer});    };
//ES6 async functiononClick = async () => {try{        this.setState({blockNumber:"waiting.."});        this.setState({gasUsed:"waiting..."});
await web3.eth.getTransactionReceipt(this.state.transactionHash, (err, txReceipt)=>{          console.log(err,txReceipt);          this.setState({txReceipt});        });      }catch(error){      console.log(error);    }}
onSubmit = async (event) => {      event.preventDefault();
//bring in user's metamask account address      const accounts = await web3.eth.getAccounts();    //obtain contract address from storehash.js      const ethAddress= await storehash.options.address;      this.setState({ethAddress});    //save document to IPFS,return its hash#, and set hash# to state      await ipfs.add(this.state.buffer, (err, ipfsHash) => {        console.log(err,ipfsHash);        //setState by setting ipfsHash to ipfsHash[0].hash        this.setState({ ipfsHash:ipfsHash[0].hash });        // call Ethereum contract method "sendHash" and .send IPFS hash to etheruem contract        //return the transaction hash from the ethereum contract        storehash.methods.sendHash(this.state.ipfsHash).send({          from: accounts[0]        }, (error, transactionHash) => {          console.log(transactionHash);          this.setState({transactionHash});        });      })    };
render() {
return (        

Ethereum and IPFS using Infura


Choose file to send to IPFS



Tx Receipt Category Values
                                      IPFS Hash stored on Ethereum                     :                     {this.state.ipfsHash}                                                        Ethereum Contract Address                     :                     {this.state.ethAddress}                                                        Tx #                      :                     {this.state.transactionHash}                                                                 );    }}export default App;

And that is all!

仅此而已!

Access your dApp at localhost:3000. Upload a file and you will see a hash generated. To make sure your file is uploaded, access it via the IPFS gateway. Make sure you accept the Metamask requests.

通过localhost:3000访问您的dApp。 上载文件,您将看到生成的哈希。 要确保文件已上传,请通过IPFS网关访问它。 确保您接受Metamask请求。

Access your file at: https://gateway.ipfs.io/ipfs/your IPFS hash

通过以下网址访问文件:https://gateway.ipfs.io/ipfs/您的IPFS哈希

Mine is at:

我的是在: :

To know more about IPFS, see my other articles:

要了解有关IPFS的更多信息,请参阅其他文章:

感谢您的阅读。 如果您喜欢这个,请鼓掌! 在Twitter上关注我 Niharika3297 (Thank you for reading. If you liked this, please clap! Follow me on Twitter Niharika3297)

翻译自:

以太坊ipfs

转载地址:http://eugwd.baihongyu.com/

你可能感兴趣的文章
几道面试题
查看>>
【转】使用 WebGL 进行 3D 开发,第 1 部分: WebGL 简介
查看>>
js用正则表达式控制价格输入
查看>>
chromium浏览器开发系列第三篇:chromium源码目录结构
查看>>
java开发操作系统内核:由实模式进入保护模式之32位寻址
查看>>
第五讲:单例模式
查看>>
Python编程语言的起源
查看>>
Azure ARMTemplate模板,VM扩展命令
查看>>
(转)arguments.callee移除AS3匿名函数的侦听
查看>>
onNewIntent调用时机
查看>>
MYSQL GTID使用运维介绍(转)
查看>>
04代理,迭代器
查看>>
解决Nginx+PHP-FPM出现502(Bad Gateway)错误问题
查看>>
Java 虚拟机:互斥同步、锁优化及synchronized和volatile
查看>>
2.python的基本数据类型
查看>>
python学习笔记-day10-01-【 类的扩展: 重写父类,新式类与经典的区别】
查看>>
查看端口被占用情况
查看>>
浅谈css(块级元素、行级元素、盒子模型)
查看>>
Ubuntu菜鸟入门(五)—— 一些编程相关工具
查看>>
PHP开源搜索引擎
查看>>