Open j4m3sb0mb opened 4 years ago
I've written a small piece of code to have block number and prevHash in state:
const crypto = require('crypto')
const { stringify } = require('deterministic-json')
const BigNumber = require('bignumber.js');
module.exports = function () {
return [
{
type: 'initializer',
middleware: function (state) {
state.block = {
number: '0',
prevHash: '',
}
}
},
{
type: 'tx',
middleware: function (state, transaction) {
if (!state.block._tx_bytes) {
state.block._tx_bytes = Buffer.from(stringify(transaction))
} else {
const curr__tx_bytes = Buffer.from(stringify(transaction))
state.block._tx_bytes = Buffer.concat([state.block._tx_bytes, curr__tx_bytes])
}
}
},
{
type: 'block',
middleware: function (state) {
const blockHash = crypto.createHash('sha256')
.update(state.block.number)
.update(state.block.prevHash)
if (state.block._tx_bytes) {
blockHash.update(state.block._tx_bytes)
delete state.block._tx_bytes
}
state.block = {
number: new BigNumber(state.block.number).plus(1).toFixed(),
prevHash: blockHash.digest('hex'),
}
}
}
]
}
Block informations as blockHeight, blockHash, prevBlockHash should be available to use pseudo-random functions in handlers