以太坊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 EthereumIPFS哈希值写在以太坊上

涉及的技术栈 (Tech Stack Involved)

  • React — Front end library

    React —前端库

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

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

  • IPFS — Decentralized storage

    IPFS —分散存储

  • Infura —API access to Ethereum network and IPFS

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

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

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

确保您已经下载了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 https://faucet.metamask.io/.

要部署智能合约,我们需要以太币。 要获取Ropsten测试网的以太币,请访问https://faucet.metamask.io/ 。

To deploy the smart contract, go to https://remix.ethereum.org.

要部署智能合约,请访问https://remix.ethereum.org 。

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(<App />, 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 (        <div className="App">          <header className="App-header">            <h1>Ethereum and IPFS using Infura</h1>          </header>
<hr/><grid>          <h3> Choose file to send to IPFS </h3>          <form onSubmit={this.onSubmit}>            <input              type = "file"              onChange = {this.captureFile}            />             <Button             bsStyle="primary"             type="submit">             Send it             </Button>          </form><hr/> <Button onClick = {this.onClick}> Get Transaction Receipt </Button> <hr/>  <table bordered responsive>                <thead>                  <tr>                    <th>Tx Receipt Category</th>                    <th> </th>                    <th>Values</th>                  </tr>                </thead>
<tbody>                  <tr>                    <td>IPFS Hash stored on Ethereum</td>                    <td> : </td>                    <td>{this.state.ipfsHash}</td>                  </tr>                  <tr>                    <td>Ethereum Contract Address</td>                    <td> : </td>                    <td>{this.state.ethAddress}</td>                  </tr>                  <tr>                    <td>Tx # </td>                    <td> : </td>                    <td>{this.state.transactionHash}</td>                  </tr>                </tbody>            </table>        </grid>     </div>      );    }}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: https://gateway.ipfs.io/ipfs/QmbyizSHLirDfZhms75tdrrdiVkaxKvbcLpXzjB5k34a31

我的是在: https : //gateway.ipfs.io/ipfs/QmbyizSHLirDfZhms75tdrrdiVkaxKvbcLpXzjB5k34a31

To know more about IPFS, see my other articles:

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

Learn by doing: a nice and easy intro to the Inter Planetary File SystemPrimer on IPFSmedium.freecodecamp.orgIPFS ? and Merkle Forest?What is IPFS?hackernoon.com

边做边学: IPFS medium.freecodecamp.org IPFS “ Inter Planetary File System Primer”的 一个很好的简单介绍 和默克尔·森林(Merkle Forest)? W h 是IPFS?哈哈 ckernoon.com

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

翻译自: https://www.freecodecamp.org/news/hands-on-get-started-with-infura-and-ipfs-on-ethereum-b63635142af0/

以太坊ipfs

以太坊ipfs_动手:Infura和以太坊上的IPFS入门相关推荐

  1. 使用web3和infura开发以太坊ethereum区块链

    web3 Github: https://github.com/ethereum/web3.js/ web3.js是以太坊提供的一个Javascript库,它封装了以太坊的RPC通信API,提供了一系 ...

  2. 以太坊 node data write error_以太坊的新时代将要到来,DeFi会是最大的收益吗?

    今日热点 以太坊 的存款合约终于部署并启用,这也就意味着以太坊离 的第 0 阶段只有一步之遥了.只要能吸引超过 万个验证人参与质押, 0 阶段网络就会在 12 月 1 日正式上线. 以太坊基金会在博客 ...

  3. 以太坊钱包_最大的以太坊钱包币数量还在增加

    持币最多的以太坊钱包地址,现在又开始继续增加持币量. ETH从累积中看到涨的迹象 以太坊价格在232.07美元,没有跌破200美元的支撑位.现在市场更多的信号在表明,大型钱包地址币的数量在累积,也间接 ...

  4. 基于以太坊网络的智能合约开发、部署和测试(入门)

    为什么80%的码农都做不了架构师?>>>    基本概念: 以太坊是一个开放的.公开的区块链平台,允许用户构建自己的去中心化应用在上面运行 Solidity是一种语法类似JavaSc ...

  5. 以太坊在哪里买_DeFi只是以太坊的开胃小菜,以太坊2.0才是重头戏

    最近宝二爷表示"我之前是100%只玩比特币,现在改为50%比特币50%以太坊". 在币圈时间比较久的人都知道宝二爷以前每次谈到数字货币都只把比特币奉为正宗,把其它的币都说成山寨,不 ...

  6. 以太坊2.0文档------以太坊2.0阶段(一)

    以太坊2.0阶段 由于以太坊2.0正在进行大量的研究和开发,这一页可能会自动过时.它是在尽力而为的基础上不断更新的.最近更新日期为2019年11月16日. 介绍 以太坊主网的升级,被称为Ethereu ...

  7. eth geth 安卓_零基础学习以太坊开发--安装和使用以太坊客户端geth

    一.预备知识 想从事区块链开发,了解以太坊开发的程序员,在刚开始接触以太坊的时候,发现有很多的新名词: EVM solidity go-ethereum(geth) pyethereum Testrp ...

  8. 以太坊源码分析(2)——以太坊APP对象

    前言 从这一节开始,我将开始以太坊代码全覆盖讲解,讲解的流程是: 以太坊程序入口 基本框架 以太坊协议 发送一笔交易后发生了什么 启动挖矿 以太坊共识 p2p 网络 阅读本系列文章,将默认读者具备一定 ...

  9. 投资地瓜坊,品香缘地瓜坊八大支持,创业无忧!

    投资地瓜坊,品香缘地瓜坊八大支持,创业无忧! [品香缘地瓜坊无忧启业支持] 总部提供包括店铺选址.店面设计.店员服装.形象事务等开店一步到位的支持,助您以最快之速度开店经营. [品香缘地瓜坊系统培训支 ...

最新文章

  1. 博士笔记 | 深入理解深度学习语义分割
  2. python迭代器和生成器_python中迭代器和生成器。
  3. linux shell read 从键盘或标准输入中读取文本
  4. Bootstrap排版中地址与引用详解
  5. 用python做数据分析,安装包一次到位
  6. 支付宝商户代扣2.0文档
  7. 报告!钉钉宜搭的8月总结,请查收~
  8. iOS中的图像处理(一)——基础滤镜
  9. 2021年中宁中学高考成绩查询,2021宁夏中卫市重点高中排名
  10. Android学习笔记——Menu(二)
  11. Python使用多进程批量判断素数
  12. get函数和getline函数
  13. mysql不安装在c_MySQL 的模块不能安装的解决方法
  14. 使用Javascript 实现 分享到 新浪微博 QQ 空间等
  15. Oracle 校验统一社会信用代码函数
  16. ccf练习题 F1方程式冠军
  17. iOS 苹果官方Demo合集
  18. 圆周率一千万亿位_目前圆周率已经达到十万亿位了,为何还要算?有什么用处?...
  19. 电单车中的N车模长得啥样呢?
  20. IDEA SVN 提交时提示failed: is out of date

热门文章

  1. 安卓开发面试书籍,每个程序员都必须掌握的8种数据结构!面试必会
  2. 我了解到的面试的一些小内幕!附面试题答案
  3. 让内核突破512字节的限制
  4. docker在Centos上的安装
  5. React 与 可视化
  6. webstorm环境安装配置(less+autoprefixer)
  7. Kotlin的Lambda表达式以及它们怎样简化Android开发(KAD 07)
  8. 基于批处理技术的重启桌面-explorer.exe的实验(转)
  9. Oracle优化检查表
  10. RUNOOB python练习题24 斐波那契数列的衍生问题