3.1.JS手写一个迷你区块链实战(1)

153 阅读2分钟

创世区块定义和生成哈希值

项目初始化

项目创建步骤

第 1 步,创建项目

mkdir node-chain
cd node-chain

第 2 步,初始化项目

npm init -y

第 3 步,在项目目录下新建入口文件

image.png

代码实现

先来分析一下思路

1.区块是什么结构? 这里我们使用一个对象来定义一个区块
举个例子:
  {
    index:0,
    data:"hello world"
  }
2.整条区块链怎么装? 这里我们使用一个数组结构来模拟

具体实现步骤

第 1 步,搭建结构

class BlockChain {
  constructor() {
    // 创世区块
    this.firstBlock = {
      index: 0,
      data: 'hello world',
      prevHash: '0',
      timestamp: 1679234322447,
      hash: 'f0c40a6c9ea4b9ae794c89744b45a2aa10af6d6d561046d039db981f94a5073b'
    }
    // 存整个区块链
    this.blockchin = [this.firstBlock]
  }
}

第 2 步,编写生成哈希值的函数

// 这里我们使用nodejs自带的加密模块
const crypto = require('crypto')
class BlockChain {
  constructor() {
    // 创世区块
    this.firstBlock = {
      index: 0,
      data: 'hello world',
      prevHash: '0',
      timestamp: 1679234322447,
      hash: 'f0c40a6c9ea4b9ae794c89744b45a2aa10af6d6d561046d039db981f94a5073b'
    }
    // 存整个区块链
    this.blockchin = [this.firstBlock]
  }
  // 生成区块的hash值
  createHash({ index, prevHash, timestamp, data, nonce }) {
    return crypto
      .createHash('sha256')
      .update(index + prevHash + timestamp + data + nonce)
      .digest('hex')
  }
}

第 3 步,测试哈希函数

let b = new BlockChain()
let hash = b.createHash({
  index: 0,
  prevHash: '0',
  timestamp: 1679234322447,
  data: 'hello world',
  nonce: 0
})
console.log('Hash: ' + hash) // f0c40a6c9ea4b9ae794c89744b45a2aa10af6d6d561046d039db981f94a5073b

这里我们测试出来的哈希值就是我们填写到创世区块里面的值