属性'height'
未保存到levelDB。我是第一次使用诺言。请在这里原谅我的纯真。我能够理解为什么数据没有保存到levelDB中。
这是区块链的代码:
class Block{
constructor(data){
this.hash = "",
this.height = 0,
this.body = data,
this.time = 0,
this.previousBlockHash = ""
}
}
class Blockchain{
constructor(){
//Get block height from levelDB
levelDB.getDBBlockHeight().then(height => {
//Check if block height is 0
if (height === -1) {
//Create the Genesis Block - The first block in the blockchain
this.addBlock(
new Block('First block in the chain - Genesis block')
).then(() => console.log('Genesis Block created!'))
}
})
}
// Add new block
async addBlock(newBlock){
//Get block height from levelDB
newBlock.height = await parseInt(this.getBlockHeight()) + 1
//Generate block timestamp
newBlock.time = new Date().getTime().toString().slice(0, -3)
//Check if the Block is not Genesis Block
if (newBlock.height > 0) {
//Get the block
const prevBlock = await this.getBlock(newBlock.height)
//Get previous block's hash
newBlock.previousBlockHash = prevBlock.hash
console.log('Previous Hash: ' + newBlock.previousBlockHash)
}
//Generate hash for the new block.
newBlock.hash = SHA256(JSON.stringify(newBlock)).toString()
console.log('New Hash: ' + newBlock.hash)
//Save the block created to levelDB
await levelDB.addDBBlock(newBlock.height, JSON.stringify(newBlock))
}
使用promises保存数据的levelDB代码:
module.exports = {
//Saving blocks to LevelDB
addDBBlock: (key, value) => {
return new Promise((resolve, reject) => {
db.put(key, value, error => {
if (error) reject(error)
resolve('Added block #' + key)
})
})
},
//Getting blockchain height from levelDB
getDBBlockHeight: () => {
return new Promise((resolve, reject) => {
let height = 0
db.createReadStream()
.on('data', data => {
height++
})
.on('error', error => {
reject(error)
})
.on('close', () => {
resolve(height)
})
})
},
请告诉我是否有错误的promises结构问题,我对数据类型输入有误。