In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
Today, the editor will share with you the relevant knowledge points about how to achieve a small blockchain in Javascript. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.
Block chain concept
In a narrow sense: chunk chain is a kind of chained data structure which combines data blocks in chronological order and ensures by password that can not be tampered with and can not be forged.
(1) Mining (creating new blocks)
First of all, the block chain is formed by the connection of each block, and there must be an initial block, also known as the Genesis block, before a new block is generated. Through this creation block, the eligible blocks are calculated constantly by changing random numbers (nonce). The following is the basic information of the Genesis Block:
Const initBlock = {index: 0, data: 'hey,this is a block chain', previousHash:' 0mm, timestamp: '1551806536961, nonce: 80490, hash:' 0000352fb27dd1141fa7265833190a53e5776b1111e275db0d9a77bf840081e6'}
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Index: refers to the serial number of each block
Data: here stores all the information in the block, such as money transfer, balance, etc.
PreviousHash: refers to the hash value of the previous block. If there is no previous one in the Genesis block, you can display 0.
Timestamp: refers to the time when the block was created
Nonce: this is a random number. Mining is to calculate the qualified hash by constantly transforming the nonce.
Hash: the hash value of this block, which is obtained by hash from the information of the previous five fields.
Then, through the continuous hash operation to calculate the hash that meets the conditions, that is, mining. Mining can also adjust the difficulty, for example, the calculated hash value must be 1 in the first 3 digits or 1 in the last 3 digits, etc., which can be defined on its own, as long as a control switch is left to facilitate control. You can define a variable
Hash calculation:
.createHash ('sha256') .update (index + data + previousHash + timestamp + nonce) .digest (' hex') _ that.difficulty = 3 / / that is, the first three digits or the last three digits must be 1. The more the number, the more difficult it is.
After the qualified hash is generated, a new block is generated, but the block has to be checked to see if it is valid, because it may be an illegal block that has been tampered with, or a block that has nothing to do with the chain and just complies with the above hash rules. So, we need to check the validity of the front and rear blocks.
IsValidaBlock (newBlock,lastBlock) {if (newBlock.index! = = lastBlock.index+1) return false if (newBlock.previousHash! = = lastBlock.hash) return false if (newBlock.timestamp {_ that.remotePeerInfo = res.data.data / / 1 _ that.addPeersList (res.peersList) / / 2 _ that.boardCast (_ that.remotePeerInfo) / / 3 _ that.blockChainUpdate (blockChain) BlockData) / / 4} addPeersList (peers) {peers.forEach (peer = > {if (! _ that.peers.find (v = > _ that.isEqualPeer (peer, v) {_ that.peers.push (peer)}})} boardCast (remotePeerInfo) {this.peers.forEach (v = > {this.send (action, v.port) V.address)} blockChainUpdate (blockChain,blockData) {if (newChain.length = 1) {return} if (_ that.isValidaChain (newChain) & & newChain.length > _ that.blockchain.length) {_ that.blockchain = Object.assign ({}) NewChain)} else {console.log ('error') return} if (trans.every (v = > _ that.isValidTransfer (v) {_ that.data = trans}}
1. Save the information from the seed node for this new node, including ip and port number, because the ip and port number of the new node will change.
two。 Accept the node list from the seed node, traverse the nodes in the list, and write anything that is not the same in the list.
3. Broadcast the information of the new node to all nodes, while the node that receives the information updates the node list.
4. Synchronize the information on the block chain locally, and carry on the information of each block to the blockchain sent by the seed node.
III. Transfer transaction
BTC's trading model uses UTXO.
In the block chain, an encryption algorithm is needed to record and transfer transactions. All the information is encrypted and then push to the data in the new block to complete the record of a new transaction. Take BTC as an example. BTC's encryption algorithm uses the elliptic encryption algorithm. Elliptic is an asymmetric encryption algorithm. The characteristic of the asymmetric encryption algorithm is that the private key is unique, and only the owner can check with the public key corresponding to his private key. Nodejs also has a corresponding library to search for elliptic on github.
{"privateKey": "34a425df3eb1f22fb6cb74b0e7298b16ffd7f3fb", "publicKey": "ac208623a38d2906b090dbcf3a09378dfe79b77bf39c2b753ef98ea94fe08dc3995a1bd05c917"}
The above is a generated key pair format, only as a demonstration, I deleted part of the length.
When using a bank card for transfer transactions, there will be a transferred account and a transferred account, and the account in the block chain will also have this account. This account is the public key in the generated key pair above, and the public key is the address, or the public key represents your wallet.
The method of verification is to first use the parameters of fields "from", "to" and "amount" to sign sign, and then use verify () to verify each mining (bookkeeping), through the first three parameters and sig.
Verify (type,data) {swtich (type) {case 'sign': const bufferMsg = Buffer.from (`${data.from}-${data.to}-${data.amount}`) let signature = Buffer.from (keypair.sign (bufferMsg). ToDER ()) .toString (' hex') this.signature = signature break Case 'verify': const keypairTemp = ec.keyFromPublic (pub,' hex') const bufferMsg = Buffer.from (`${data.from}-${data.to}-${data.amount}`) this.keypair = keypairTemp.verify (bufferMsg, sig) break; default;}}
Three steps are needed to transfer the account, which is to verify whether there is enough money in the transfer account. The transfer account is the local public key. If so, it is billed and packed with two addresses, amounts, times, and signatures, followed by an all-node broadcast. After other nodes receive this message, the * thing is also to verify the validity of the new chunk. After passing the verification, it will be written to the data.
Transfer (data) {const timestamp = new Date (). GetTime () const sig = rsa.sign ({data.from, data.to, data.amount, timestamp}) const sigTrans = {data.from, data.to, data.amount, timestamp, sig} / / non-creation block if (trans.from! = ='0') {/ / check balance if (! (_ that.blance)
< amount)) { //_that.blance 当前账户余额 //全节点广播 _that.send('trans', sigTrans) }else{ console.log('not enough blance') return } } this.data.push(sigTrans) return sigTrans } 其他节点收到消息之后,先进行去重校验,然后再更新数据。 四、查询余额 这个链的查询方法比较简单,就是将区块中的每一条交易的信息进行校验和匹配,满足条件的就进行增减,同时忽略精度上的问题。 this.blance = blance(address) blance(address) { let blance = 0; this.blockchain.forEach(block =>{block.data.forEach (trans = > {if (address = = trans.from) {blance-= trans.amount} if (address = = trans.to) {blance + = trans.amount}})}) Return blance} these are all the contents of the article "how to implement a small blockchain in Javascript". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.