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)。然而,這是一個非常古老的概念,在新的觀點下重新煥發生機,正在改變對經濟的思考方式,創造泡沫(在我看來)和從“金融時代”開始的“更安全”經濟的新可能性。常識觀。有能力控制交易的時間和方式,這種情況正在悄然發生,但具有巨大的潛力。

我們創建的是一個簡單的區塊鏈,它只與一個節點一起工作,只有一個節點可以製作它(有基於此的加密貨幣)。當然,關於這個主題的多節點和所有問題的管理同樣有趣。

我希望這篇文章能讓你超越比特幣交易本身,並讓你對區塊鏈真正做的事感興趣。


分享到:


相關文章: