简体   繁体   English

NodeJs私有以太坊上的区块链

[英]NodeJs blockchain on private ethereum

I have created simple blockchain application using NodeJS. 我使用NodeJS创建了简单的区块链应用程序。 The blockchain data file is getting stored on local File System. 区块链数据文件存储在本地文件系统中。 There is no mining blocks, no difficulty level involved in this blockchain. 没有采矿区块,这个区块链没有任何难度级别。

Please suggest, if I can host this application on private ethereum / hyperledge, and what all changes I would need to do for this? 请建议,如果我可以在私人以太坊/ hyperledge上托管这个应用程序,以及我需要为此做些什么改变? Below code I'm using for creating blocks. 下面我用于创建块的代码。

Sample Genesis Block 样本创世纪块

[{"index":0,"previousHash":"0","timestamp":1465154705,"transaction":{"id":"0","transactionHash":"0","type":"","data":{"StudInfo":[{"id":"","studentId":"","parenterId":"","schemeId":"","batchId":"","instructorId":"","trainingId":"","skillId":""}]},"fromAddress":""},"hash":"816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7"}]

Sample Code(NodeJS) 示例代码(NodeJS)

var generateNextBlock = (blockData) => {
    var previousBlock = getLatestBlock();
    var nextIndex = previousBlock.index + 1;
    var nextTimestamp = new Date().getTime() / 1000;
    var nextHash = calculateHash(nextIndex, previousBlock.hash, nextTimestamp, blockData);

    return new Block(nextIndex, previousBlock.hash, nextTimestamp, blockData, nextHash);
};

var calculateHashForBlock = (block) => {
    return calculateHash(block.index, block.previousHash, block.timestamp, block.transaction);
};

var calculateHash = (index, previousHash, timestamp, transaction) => {
    return CryptoJS.SHA256(index + previousHash + timestamp + transaction).toString();
};

var addBlock = (newBlock) => {
    if (isValidNewBlock(newBlock, getLatestBlock())) {
        blockchain.push(newBlock);
        blocksDb.write(blockchain);
    }
};

var isValidNewBlock = (newBlock, previousBlock) => {
    if (previousBlock.index + 1 !== newBlock.index) {
        console.log('invalid index');
        return false;
    } else if (previousBlock.hash !== newBlock.previousHash) {
        console.log('invalid previoushash');
        return false;
    } else if (calculateHashForBlock(newBlock) !== newBlock.hash) {
        console.log(typeof (newBlock.hash) + ' ' + typeof calculateHashForBlock(newBlock));
        console.log('invalid hash: ' + calculateHashForBlock(newBlock) + ' ' + newBlock.hash);
        return false;
    }
    return true;
};

Congratulations if you have gotten this far you have successfully setup Geth on AWS. 恭喜你,如果你已经到目前为止,你已成功在AWS上设置Geth。 Now we will go over how to configure an Ethereum node. 现在我们将讨论如何配置以太坊节点。 Make sure you are in your home directory on your cloud server with the pwd command and then create a new folder called whatever you want to create the genesis block of your Ethereum blockchain. 使用pwd命令确保您位于云服务器上的主目录中,然后创建一个名为“您想要创建以太坊区块链的创世块”的新文件夹。 You can do this with the following commands. 您可以使用以下命令执行此操作。 The first command is to create the folder, change directory into the folder and then create a file called genesis.json. 第一个命令是创建文件夹,将目录更改到文件夹中,然后创建一个名为genesis.json的文件。

mkdir mlg-ethchain cd mlg-ethchain nano genesis.json mkdir mlg-ethchain cd mlg-ethchain nano genesis.json

To create a private blockchain you need to define the genesis block. 要创建私有区块链,您需要定义创世块。 Genesis blocks are usually embedded in the client but with Ethereum you are able to configure a genesis block using a json object. Genesis块通常嵌入客户端,但使用Ethereum,您可以使用json对象配置genesis块。 Paste the following JSON object into your genesis.json file and we explain each variable in the following section. 将以下JSON对象粘贴到您的genesis.json文件中,我们将在下一节中解释每个变量。

 { "nonce": "0xdeadbeefdeadbeef", "timestamp": "0x0", "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000", "extraData": "0x0", "gasLimit": "0x8000000", "difficulty": "0x400", "Mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000", "coinbase": "0x3333333333333333333333333333333333333333", "alloc": { } } 

The coinbase is the default address of the mining address. coinbase是挖掘地址的默认地址。 Because you have not created a wallet yet this can be set to whatever you want provided that it is a valid Ethereum address. 因为您尚未创建钱包,但只要它是有效的以太坊地址,就可以将其设置为您想要的任何内容。 Difficulty is how hard it is for a miner to create a new block. 困难在于矿工创建新区块的难度。 For testing and development purposes it is recommended that you start with a low difficulty and then increase it. 出于测试和开发目的,建议您从较低难度开始,然后增加它。 The parentHash is the hash of the parent block which doesnt exist because this is the first block in the chain. parentHash是父块的哈希,它不存在,因为这是链中的第一个块。 The gasLimit is the maximum amount of gas that is required to execute a transaction or send tokens from one account to another. gasLimit是执行交易或将令牌从一个帐户发送到另一个帐户所需的最大气体量。 The nonce is a random number for this block. nonce是该块的随机数。 This is the number that every miner has to guess to define the block but for the first block it must be hardcoded. 这是每个矿工必须猜测以定义块的数字,但对于第一个块,它必须是硬编码的。 You are able to provide any extraData is the extraData section. 您可以提供任何extraData是extraData部分。 In the alloc section you can allocate a number of premined tokens or ether to certain addresses at the beginning of the blockchain. 在alloc部分,您可以在区块链的开头为某些地址分配一些预先设置的令牌或以太网。 We do not want to do this so we will keep it blank. 我们不想这样做,所以我们会把它留空。

After you have confirmed this you can check the file to make sure it has been configured correctly with the cat command. 确认后,您可以检查文件以确保已使用cat命令正确配置该文件。 From the same directory input this command. 从同一目录输入此命令。

cat genesis.json cat genesis.json

From what I understand, your JS code does some sort of low-level block generation (albeit in a centralised/standalone way). 根据我的理解,您的JS代码会执行某种低级别的块生成(尽管是以集中/独立的方式)。 I'm not sure of the purpose of that code, but it's not an app that you could "port to" Ethereum or Hyperledger [Fabric], since the role of those blockchain engines is precisely to implement the block generation logic for you. 我不确定该代码的用途,但它不是一个可以“移植到”以太坊或Hyperledger [Fabric]的应用程序,因为这些区块链引擎的作用正是为您实现块生成逻辑。

A JS app designed to work with Ethereum wouldn't do any of the block management. 设计用于与以太坊合作的JS应用程序不会执行任何块管理。 At the contrary, it would perform high-level and client-level interaction with a smart contract, which is basically a class (similar to Java classes) available on the whole network and whose methods are guaranteed by the network to do what they're meant to. 相反,它将执行与智能合约的高级和客户端级交互,智能合约基本上是整个网络上可用的类(类似于Java类),并且其方法由网络保证做他们所做的事情。为了。 Your JS app would essentially call the smart contract's methods as a client without caring about any block production issues. 您的JS应用程序基本上将智能合约的方法称为客户端,而无需关心任何块生产问题。

In other, more vague but maybe more familiar terms: 在其他更模糊但可能更熟悉的术语中:

  • Client: the JS app 客户端:JS应用程序
  • Server/backend: the smart contract 服务器/后端:智能合约
  • Infrastructure/engine: Ethereum 基础设施/发动机:以太坊

On Ethereum, the way you get to the smart contract as a client is by sending RPC calls in JSON (hence the name JSON-RPC) to the contract's methods. 在以太坊上,您作为客户端获得智能合约的方式是通过将JSON中的RPC调用(因此名称为JSON-RPC)发送到合同的方法。 The communication is done by embedding that JSON over HTTP to an Ethereum node, preferably your own. 通过HTTP将JSON嵌入到以太网节点(最好是您自己的节点)来完成通信。 In Javascript, a few libraries such as web3 give you a higher-level abstraction view so that you don't need to care about JSON-RPC and you can think of your contract's methods as normal Javascript functions. 在Javascript中,一些库(如web3)为您提供了更高级别的抽象视图,因此您无需关心JSON-RPC,您可以将合约的方法视为正常的Javascript函数。

Also, since you're asking about private Ethereum: another consequence of that distribution of layers is that client code and smart contracts don't need to care about whether the Ethereum network is a public or a private one, ie what consensus protocol is in place. 此外,既然你在询问私有的以太坊:层次分布的另一个后果是客户代码和智能合约不需要关心以太坊网络是公共网络还是私有网络,即共识协议是什么地点。 To make a bold analogy, it's similar to how SQL queries or schemas stay the same no matter how the database is persisted on disk. 粗略地说,无论数据库如何在磁盘上持久存在,它都与SQL查询或模式保持相同的方式类似。

Interaction with Hyperledger Fabric is similar in concept, except that you do plain REST calls to an HTTP endpoint exposed by the network. 与Hyperledger Fabric的交互在概念上类似,只是您对网络公开的HTTP端点进行简单的REST调用。 I'm not sure what client-level abstraction libraries are available. 我不确定哪些客户端级抽象库可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM