NodeJS写一个简单区块链

1. 指数

2. 时间戳

3. 交易清单

4. 证明

5. 上一个块的哈希

const block = {

'index': 1,

'timestamp': 1506057125.900785,

'transactions': [

{

'sender': "8527147fe1f5426f9dd545de4b27ee00",

'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",

'amount': 5,

}

],

'proof': 324984774000,

'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

}

通过这种方式,区块链的想法变得更加清晰。是一组连接到前一个的顺序块(索引),并使用加密(previous_hash)进行保护。区块内的previous_hash是整个区块链的关键。它使我们能够保证整个链条的安全性和不变性。如果攻击者可以在该块之后立即修改链的块,则所有哈希都是错误的。显然,它可能会尝试重新计算整个链条的哈希值,这就是为什么更多的区块更多的区块链是安全的。此外,在每个节点中都存在(相同的)区块链副本(在这种情况下,NodeJS的实例)这使得黑客几乎不可能同时修改所有副本。

所以在我们的例子中创建一个新块非常简单。我们只需要将一个新对象推送到链中。该函数将接收证明(然后我们将讨论它是什么)和前一个块哈希并将返回块。该函数还将向块中添加尚未保存的所有事务并清理变量current_transactions

3.1.1哈希函数

用于我们的Chiccocoin的哈希函数是一个简单的SHA256,但您可以使用您喜欢的哈希函数。重要的是要执行前一个块的哈希,为此我们将执行序列化对象的哈希

3.2创建交易

添加新事务的功能非常简单。是添加到current_transaction数组的事务。交易是由发件人,收件人和金额组成的对象。它将是在块内存储事务的挖掘功能。对于实用程序,我们将确保该函数向我们返回将保存它的块的索引

class Blockchain {

constructor () {

// Create chain and transaction

this.chain = []

this.current_transactions = []

// Binding of this

this.newBlock = this.newBlock.bind(this)

this.newTransaction = this.newTransaction.bind(this)

this.lastBlock = this.lastBlock.bind(this)

this.proofOfWork = this.proofOfWork.bind(this)

}

newBlock (proof, previousHash) {

const block = {

index: this.chain.length + 1,

timestamp: new Date(),

transactions: this.current_transactions,

proof: proof,

previous_hash: previousHash

}

this.current_transactions = []

this.chain.push(block)

return block

}

newTransaction (sender, recipient, amount) {

this.current_transactions.push({

sender: sender,

recipient: recipient,

amount: amount

})

return this.lastBlock()['index'] + 1

}

hash (block) {

const blockString = JSON.stringify(block)

const hash = crypto.createHmac(process.env.HASH_TYPE, process.env.CRYPTO_SECRET)

.update(blockString)

.digest('hex')

return hash

}

lastBlock () {

return this.chain.slice(-1)[0]

}

}

module.exports = Blockchain

4.工作证明

通常,工作证明是发明并用于阻止拒绝服务攻击的功能或协议,但区块链使用它来确定如何在自己上创建或挖掘新块。POW的目标是发现一个解决问题的数字。这个数字一定很难找到 但很容易验证,就像素数的计算一样,我们发现的数字越多,找到一个就越困难,但是理解它是否是非常平庸的努力。

为了挖掘Chiccocoin,我们决定创建一个c4ff3。我们的POW将是这样的:

c4ff3e9373e...5e3600155e860

我们来编码吧。必要的功能是两个:

1. validProof:给出之前的POW和ap编号检查问题的解决方案是否正确

2. proofOfWork:循环直到找到解决方案

validProof (lastProof, proof) {

const guessHash = crypto.createHmac(process.env.HASH_TYPE, process.env.CRYPTO_SECRET)

.update(`${lastProof}${proof}`)

.digest('hex')

return guessHash.substr(0, 5) === process.env.RESOLUTION_HASH

}

proofOfWork (lastProof) {

let proof = 0

while (true) {

if (!this.validProof(lastProof, proof)) {

proof++

} else {

break

}

}

return proof

}

5.通过API服务

通过API为expressjs服务我们的区块链开始项目将非常简单。

我们将创建三个API:

1. /transactions/new 为块创建新事务

2. /mine 告诉我们的服务器挖掘一个新块。

3. /chain 返回完整的区块链。

我在里面创建了一个Chiccocoin支持类,/middleware/chiccocoin.js其中包含API的所有必要中间件并实例化一个新的区块链

5.1链端点

这个端点非常简单。只需返回存储在区块链内的链数组

5.2交易终点

事务端点将检查传递的数据,并将调用区块链的newTransaction函数。将来我们可以使用这个中间件来检查实际的发件人和收件人是否正确和/或交易是否可以完成。我们将使用newTransaction函数返回的信息来通知用户将保存事务的块。

5.3采矿终点

我们的采矿终点是chiccocoin成为现实的地方。它必须做四件事:

计算工作证明

通过添加授予我们1个硬币的交易来奖励矿工(我们)

添加所有待处理的交易

通过将新块添加到链中来构造新块

const Blockchain = require('./blockchain')

const { validationResult } = require('express-validator/check')

class Chiccocoin {

constructor () {

this.blockchain = new Blockchain()

this.getChain = this.getChain.bind(this)

this.mine = this.mine.bind(this)

this.newTransaction = this.newTransaction.bind(this)

}

getChain (req, res, next) {

req.responseValue = {

message: 'Get Chain',

chain: this.blockchain.chain

}

return next()

}

mine (req, res, next) {

const lastBlock = this.blockchain.lastBlock()

const lastProof = lastBlock.proof

const proof = this.blockchain.proofOfWork(lastProof)

// Create a new transaction with from 0 (this node) to our node (NODE_NAME) of 1 Chiccocoin

this.blockchain.newTransaction('0', process.env.NODE_NAME, 1)

// Forge the new Block by adding it to the chain

const previousHash = this.blockchain.hash(lastProof)

const newBlock = this.blockchain.newBlock(proof, previousHash)

const responseValue = Object.assign({

message: 'New Block mined'

}, newBlock)

req.responseValue = responseValue

return next()

}

newTransaction (req, res, next) {

const errors = validationResult(req)

if (!errors.isEmpty()) {

return res.status(422).json({ errors: errors.mapped() })

}

const trans = req.body

const index = this.blockchain.newTransaction(trans['sender'], trans['recipient'], trans['amount'])

const responseValue = {

message: `Transaction will be added to Block ${index}`

}

req.responseValue = responseValue

return next()

}

}

module.exports = new Chiccocoin()

我们可以通过curl或Postman测试我们所有的API。我在存储库中添加了postman_collection.json,以简化邮递员的使用。

牛逼的blockchain他背后的想法是什么新的或复杂的,因为我们都看到了。Banally开发人员每天使用区块链而没有意识到它(git)。然而,这是一个非常古老的概念,在新的观点下重新焕发生机,正在改变对经济的思考方式,创造泡沫(在我看来)和从“金融时代”开始的“更安全”经济的新可能性。常识观。有能力控制交易的时间和方式,这种情况正在悄然发生,但具有巨大的潜力。

我们创建的是一个简单的区块链,它只与一个节点一起工作,只有一个节点可以制作它(有基于此的加密货币)。当然,关于这个主题的多节点和所有问题的管理同样有趣。

我希望这篇文章能让你超越比特币交易本身,并让你对区块链真正做的事感兴趣。


分享到:


相關文章: