区块链和以太坊用于 JavaScript 和 React 开发(Blockchain and Ethereum for JavaScript and React developers)

Web应用开发 William 284浏览 0评论

Blockchain is a technology for building decentralized apps. We are used to storing data in centralised databases. For the sake of fault tolerance, we may have clusters of databases distributed geographically. But that does not make traditional databases decentralized. All of the databases are controlled by a single company. Blockchain makes the data politically decentralized. There is no single authority that controls all of data. Instead, a group of distributed servers (also called nodes) have a copy of the actual data. Even if one node goes down, no problem. The rest of the nodes can continue to process the transactions. How is it possible?

How does Blockchain work?

I am going to present a simplified version of how the Blockchain works. My explanation is very similar to how a physicist explains Quantum theory to you.

区块链上的任何交易都将广播到整个网络。其中一个节点准备一个块,交易发生在同一时间。该块被发送到整个网络时产生一个难题。难题是弄清楚交易在块中出现的顺序。单个计算机难以解决难题,需要反复试验或蛮力解决方案。网络中的一台计算机都可以在短时间内找出难题。那块被证实。网络中的两台计算机可能会同时解决这个难题(具有不同的顺序)。在这种情况下,两个块都会被传送到网络。

网络中的每个确认的块被链接到网络中的前一个块。有些时候,这些链可能会在个别节点发散。再次通过共识,随着时间的推移,较长的连锁胜出。因此,单个区块链就会成为真相的来源。

由于这些复杂的计算,区块链上的任何交易都需要一些时间来确认。如果交易被6个或12个后续块确认,那么它永远是区块链的一部分。虽然区块链是一种技术,但是以不同的技术的平台,实现方式也不尽相同。比特币和以太坊是区块链的两个流行实现。在比特币网络中,交易需要15分钟才能确认。而以太坊协议有一个简单的难题,所以一个交易只需要几秒钟来确认。

More on Ethereum and Geth

Ethereum protocol is quite popular these days. It was announced to the world in 2013. It has a good developer ecosystem. Ethereum protocol is implemented by many programs. One of the popular program that implements Ethereum is Geth. It is implemented using Go language. If you run geth on your system, it will download the entire public blockchain. But for practice, we like to create our own private blockchain, running just only on our system. Download Geth from the official source. Install in any folder on your Mac. And add the folder to the $PATH variable.

To create a private blockchain, we need to initialise Geth with a genesis block (or the first block).

{
    "coinbase"   : "0x0000000000000000000000000000000000000001",
    "difficulty" : "0x20000",
    "extraData"  : "",
    "gasLimit"   : "0x8000000",
    "nonce"      : "0x0000000000000042",
    "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
    "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
    "timestamp"  : "0x00",
    "alloc": {},
    "config": {
          "chainId": 15,
          "homesteadBlock": 0,
          "eip155Block": 0,
          "eip158Block": 0
      }
  }

更多关于以太坊和Geth

以太坊协议近来颇受欢迎。它在2013年向全世界宣布。它拥有一个良好的开发者生态系统。以太坊协议由许多程序实现。实施以太坊的流行程序之一就是Geth。它使用Go语言来实现。 如果你在你的系统上运行geth,它会下载整个公共区块链。 但实践中,我们喜欢创建自己的私人区块链,只在我们的系统上运行。 从官方来源下载Geth。 安装在Mac上的任何文件夹中。 并将该文件夹添加到$PATH变量中。

要创建一个私人区块链,我们需要初始化一个创世区块(第一个区块)。

{
    "coinbase"   : "0x0000000000000000000000000000000000000001",
    "difficulty" : "0x20000",
    "extraData"  : "",
    "gasLimit"   : "0x8000000",
    "nonce"      : "0x0000000000000042",
    "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
    "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
    "timestamp"  : "0x00",
    "alloc": {},
    "config": {
          "chainId": 15,
          "homesteadBlock": 0,
          "eip155Block": 0,
          "eip158Block": 0
      }
  }

Use the above file contents in a genesis.json file. Also create another folder called chaindata where Geth will store all the blocks. And do a init.

geth --datadir=./chaindata/ init ./genesis.json

After Geth initialises, run Geth to start your private blockchain.

geth --datadir=./chaindata/

Right now, geth is running in only your computer. But with ethereum public chain, geth will run on a lot of computers. You are free to start and stop geth any time. If geth is started, it will download the latest chain data from other nodes in the network. In that way, blockchain is truly decentralized with no single node controlling the network.

在 geneis.json 文件中使用上述文件内容。 另外创建另一个名为 chaindata 的文件夹,Geth 将存储所有的块。 并做一个 init (初始化)。

geth --datadir=./chaindata/ init ./genesis.json

初始化 Geth 之后,就可以创建你的个人项目了。

geth --datadir=./chaindata/ init ./genesis.json

现在,geth 只在你的电脑上运行。 但是,以太坊公共链通过 geth 会运行在很多电脑上。 你随时可以自由地开始和停止。 如果 geth 启动,它将从网络中的其他节点下载最新的链式数据。 这样一来,区块链就真正分散了,没有一个节点控制网络。在 Geth 初始化之后,运行 Geth 开始你的私人区块链。

Blockchain terminology

I like to explain the terminology involved in Blockchain by showing you transactions and blocks in etherchain. Consider a single transaction.

Transaction in EtherChain

The properties of transactions has a lot of detail. From and To are two accounts in the public chain. These accounts may represent two real people, Joe and Mike. In this transaction, Joe is transferring 7.53 Ether or $ 3501.45 to Mike. When you create an account in any Blockchain, you create a private key and public key pair. I won’t explain how cryptography works. But at high level, you share your public key with others. And keep your private key with you. A sender can encrypt data with your public key. And you can decrypt the data with your private key. Private key is kept secure. And if you lose your private key, you lose access to your Blockchain account. It is that important. The From and To properties in the transaction details represent public key hash of two accounts (Joe and Mike) in the Blockchain.

区块链术语

我将通过以太坊的交易和区块来解释区块链中的术语。考虑如下一个交易

以太坊的交易。

上边交易的属性有很多细节。From和To是公共链的两个账户。假设这两个账户分别是Joe和Mike,在这个交易中Joe将7.53个以太币或者3501.45美元转改Mike。当创建任何区块链账户的时候会生成一个公私钥对。这里不会说明加解密是怎样工作的,但是在上层你会和别人分享你的公钥,自己保存自己的私钥。私钥必须安全保存,如果私钥丢失就无法登陆到你的区块链账户,这一点很重要。交易中From和To属性代表区块链中两个账户(Joe和Mike)的公钥做哈希的值。

The transaction also has a hash. And it is part of a block (4642361). There is two confirmations. This means that there are two more confirmed blocks in the blockchain following the block. Then down below, the Amount property, we have a few more properties related to transaction price. Every transaction requires computations or processing power. And so, it has a charge. When you are sending a transaction, we can also send two additional parameters, gas price and gas limit. Gas limit indicates the maximum computation. And gas price indicates the price for each computation. The product of gas price and total gas used is the transaction price.

You might notice that gas price (or the price for each computation) is denoted by 10 GWei. Wei is an ether denomination.

Ether denominations

交易本身也有一个哈希值,并且该交易是块的一部分(4642361)。上边的交易记录里面有两个确认说明在区块链中这个块下边还有另外两个块。接着往下是属性Amount,以及一些属性和交易金额有关。每一次交易都需要计算和处理,所以每一次交易都要收费。当发起一次交易的时候会发送两个额外的参数燃料价格和燃料供给上限,燃料供给上限代表可提供的最大的计算,燃料价格代表每一次计算的价格,燃料价格和交易中燃料使用量的乘积就是交易费用。

你可能注意到燃料价格(每次计算的价格)用10GWei表示,Wei是一个以太币面值单位。

以太币面值。

One ether is 10^18 Wei and 10^9 GWei. Transaction amount is 10 GWei multiplied by 21,000 which is 210,000 GWei or 0.00021 Ether.

Now, that you understood the transaction properties, let us look into block properties. Consider a block.

Block in Etherchain

I won’t discuss each property of the block. But I want to point out three properties: difficulty, miner and reward. When preparing a block, there is a difficulty associated with the block. The difficulty indicates how difficult it is to mine the block. The miner is the node (Geth node) which solved the puzzle for the block. And it gets the reward which is the sum of all transaction charges in the block.

一个以太币值10^18个Wei,值10^9个GWei,交易金额是10GWei乘以21000等于210000GWei或者0.00021以太币。

现在已经理解了交易属性,我们看一下块属性,考虑一个如下:

以太链里边的块

我不会讲块的每一个属性,但是我会提到三个属性:难度值、矿工和奖励。当准备一个块的时候难度值表示挖这个块的难度。矿工就是一个为该块解谜的以太节点,该矿工获得该块里面所有交易费用。

Mining in action

When we start Geth, it opens an IPC endpoint. Retrieve the IPC endpoint using the last line of the log.

INFO [11-29|13:12:06] IPC endpoint opened: /Users/vijayst/documents/react/vijay/blockchain/assignment_2/chaindata/geth.ipc

Start a Geth Javascript console using the following command.


geth attach /Users/vijayst/documents/react/vijay/blockchain/assignment_2/chaindata/geth.ipc

Within the JavaScript console, we can execute JavaScript methods to start and stop mining.


miner.start(1);

We create the primary account using a wallet program called Mist. Mist is a Meteor app based on electron. Download and install it from the official source. Add the installation folder to the $PATH variable. Usually it is /Applications/Mist.app/Contents/MacOS. Start Mist using the following command. (Supply the IPC endpoint of Geth)The above command starts the miner in one thread. Now, our node participates in a mining process. Mining is what confirms transactions. In addition, mining generates ether out of thin air and adds it to primary account of the node (also known as coinbase).

mist --rpc /Users/vijayst/documents/react/vijay/blockchain/assignment_2/chaindata/geth.ipc

挖矿行动

当打开Geth的时候会开启一个IPC终端,通过日志的最后一行可以检索该IPC终端。

INFO [11-29|13:12:06] IPC endpoint opened: /Users/vijayst/documents/react/vijay/blockchain/assignment_2/chaindata/geth.ipc

使用下面的命令打开Geth JavaScript控制台:

geth attach /Users/vijayst/documents/react/vijay/blockchain/assignment_2/chaindata/geth.ipc

在改JavaScript控制台里面可以通过执行JavaScript方法来开始或停止挖矿:

miner.start(1);

上边的命令在一个线程里面开启了一个矿工。现在我们的节点已经参与到挖矿的过程中,挖矿就是确认交易。另外,挖矿也会产生以太币(coinbase)并且把该以太币添加到该节点的账户中。

我们通过钱包程序Mist创建主账户,Mist是一个基于电子Meteor应用。从官方源下载并安装该程序并且将安装路径添加到$PATH变量里面,安装路径通常是/Applications/Mist.app/Contents/MacOS。使用下面的命令启动Mist:

mist --rpc /Users/vijayst/documents/react/vijay/blockchain/assignment_2/chaindata/geth.ipc

Create an account in Mist. This will create the private / public key pair. And now when you start miner, your account will generate ether in your account.

Mist with primary account

My account has 1,245 Ether. It is the reward for running Geth in my system and using it for mining. Not bad, right? (This Ether is useful only for your private network!)

Stop the miner by issuing miner.stop() in the JavaScript console.

在Mist里面创建一个账户会生成公私钥对并且当你启动挖矿的时候,你的账户里面会产生以太币。

Mist和主账户

我的账户里面有1245个以太币,这些是我的系统挖矿的奖励。不错,对吧?(这只适用于你的私有网络)

在JavaScript控制台里面调用miner.stop()停止挖矿。

React app for interacting with Blockchain

We are all set to write our React app which will interact with the Blockchain. We will continue to use our private network. Create a new react app using create-react-app.

create-react-app blockchaindemo
cd blockchaindemo
yarn start

Next, we want to start the Ethereum node on a private blockchain. I mentioned Ethereum node because we are not going to use Geth for our development. Geth has a mining component which is processor intensive. Thankfully, developers at ethereum have built a simple ethereum node for testing called testrpc.The local server starts at port 3000. If we navigate to http://localhost:3000, we should see our React app.

yarn global add ethereumjs-testrpc

Start testrpc using testrpc –secure. By default, testrpc creates 10 accounts in a sandboxed environment. It runs as a http server in port 8545

使用React应用与区块链进行交互

我们开始准备写React应用程序,它将与区块链互动。 我们将继续使用我们的私人网络。 使用create-react-app创建一个新的react应用程序。

create-react-app blockchaindemo
cd blockchaindemo
yarn start

本地服务器从端口3000开始。如果我们导航到http//localhost:3000,就可以看到我们的React应用程序。

接下来,我们要在私有区块链上启动以太坊节点。 我提到以太坊节点,因为我们不打算使用Geth来进行开发。 Geth是一个CPU占用率很高的挖掘组件。 值得庆幸的是,以太坊的开发者已经构建了一个简单的ethereum节点来测试testrpc。

yarn global add ethereumjs-testrpc

使用testrpc –secure启动testrpc。 默认情况下,testrpc在沙箱环境中创建10个帐户。 它在8545端口中作为http服务器运行。

转载请注明:AspxHtml学习分享网 » 区块链和以太坊用于 JavaScript 和 React 开发(Blockchain and Ethereum for JavaScript and React developers)

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址