通过App的演示深入理解区块链运行原理

下载安装

如果没有安装nodejs,需要先安装 nodejs

# Clone this repository
$ git clone https://github.com/seanseany/blockchain-cli

# Go into the repository
$ cd blockchain-cli

# Install dependencies
$ npm install

# Run the app
$ npm start

运行结果:

image

创建区块

在 blockchian ->后面输入 bc查看创始区块结构。

image

当一个区块挖矿时都发生了什么?

在 blockchian ->后面输入 mine kongyixueyuan.com 挖矿并创建一个新的模块。

image

Hash是怎么计算的?

Hash值是一个十六进制固定长度为64位的唯一的标识。

hash值是由index, previous block hash, timestamp, block datanonce 作为输入数据计算而得。

CryptoJS.SHA256(index + previousHash + timestamp + data + nonce)
The SHA256 algorithm will calculate a unique hash, given those inputs. The same inputs will always return the same hash.

SHA256算法将根据给出的输入数据计算出一个唯一的hash值,只要输入值不变,永远返回相同的结果。

image

在线演示:
https://anders.com/blockchain/hash.html

你是否注意到块哈希中的四个前导0?

四个前导0是有效散列的最低要求。 所需的前导0的数量称为难度

下面的方法验证hash难度是否有效。

function isValidHashDifficulty(hash, difficulty) {
  for (var i = 0, b = hash.length; i < b; i ++) {
      if (hash[i] !== '0') {
          break;
      }
  }
  return i >= difficulty;
}

这就是我们所熟知的工作量证明系统 - Proof-of-Work system

什么是nonce?

nonce是一个用来找到满足条件的hash值的数字。

let nonce = 0;
let hash;
let input;
while(!isValidHashDifficulty(hash)) {     
  nonce = nonce + 1;
  input = index + previousHash + timestamp + data + nonce;
  hash = CryptoJS.SHA256(input)
}

nonce 值一直迭代,直到 hash 值有效为止。在我们案例中一个有效的hash 值是最少有4个前导0。找到nonce 值以满足合适条件的hash值的过程就叫做挖矿。

随着难度的增加,可能的有效散列数减少。 使用较少可能的有效散列,需要更多的处理能力才能找到有效的散列。

nonce%E5%80%BC.gif

在线地址:

https://anders.com/blockchain/block.html

猜你喜欢

转载自blog.csdn.net/luckydog612/article/details/80396368