Move Block Class from ES6 PR

This commit is contained in:
junderw 2018-12-27 17:49:53 +09:00
parent 91d3037cf3
commit 2eb9534939
No known key found for this signature in database
GPG key ID: B256185D3A971908
3 changed files with 198 additions and 148 deletions

View file

@ -5,174 +5,224 @@ const typeforce = require('typeforce')
const types = require('./types') const types = require('./types')
const varuint = require('varuint-bitcoin') const varuint = require('varuint-bitcoin')
const errorMerkleNoTxes = new TypeError('Cannot compute merkle root for zero transactions')
const errorWitnessNotSegwit = new TypeError('Cannot compute witness commit for non-segwit block')
const errorBufferTooSmall = new Error('Buffer too small (< 80 bytes)')
function txesHaveWitness (transactions: Array<any>): boolean {
return transactions !== undefined &&
transactions instanceof Array &&
transactions[0] &&
transactions[0].ins &&
transactions[0].ins instanceof Array &&
transactions[0].ins[0] &&
transactions[0].ins[0].witness &&
transactions[0].ins[0].witness instanceof Array &&
transactions[0].ins[0].witness.length > 0
}
const Transaction = require('./transaction') const Transaction = require('./transaction')
function Block () { export class Block {
this.version = 1 version: number
this.prevHash = null prevHash: Buffer
this.merkleRoot = null merkleRoot: Buffer
this.timestamp = 0 timestamp: number
this.bits = 0 witnessCommit: Buffer
this.nonce = 0 bits: number
} nonce: number
transactions: Array<any>
Block.fromBuffer = function (buffer) { constructor () {
if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)') this.version = 1
this.timestamp = 0
let offset = 0 this.bits = 0
function readSlice (n) { this.nonce = 0
offset += n
return buffer.slice(offset - n, offset)
} }
function readUInt32 () { static fromBuffer (buffer: Buffer): Block {
const i = buffer.readUInt32LE(offset) if (buffer.length < 80) throw errorBufferTooSmall
offset += 4
return i let offset: number = 0
const readSlice = (n: number): Buffer => {
offset += n
return buffer.slice(offset - n, offset)
}
const readUInt32 = (): number => {
const i = buffer.readUInt32LE(offset)
offset += 4
return i
}
const readInt32 = (): number => {
const i = buffer.readInt32LE(offset)
offset += 4
return i
}
const block = new Block()
block.version = readInt32()
block.prevHash = readSlice(32)
block.merkleRoot = readSlice(32)
block.timestamp = readUInt32()
block.bits = readUInt32()
block.nonce = readUInt32()
if (buffer.length === 80) return block
const readVarInt = (): number => {
const vi = varuint.decode(buffer, offset)
offset += varuint.decode.bytes
return vi
}
const readTransaction = (): any => {
const tx = Transaction.fromBuffer(buffer.slice(offset), true)
offset += tx.byteLength()
return tx
}
const nTransactions = readVarInt()
block.transactions = []
for (var i = 0; i < nTransactions; ++i) {
const tx = readTransaction()
block.transactions.push(tx)
}
// This Block contains a witness commit
if (block.hasWitnessCommit()) {
// The merkle root for the witness data is in an OP_RETURN output.
// There is no rule for the index of the output, so use filter to find it.
// The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed
// If multiple commits are found, the output with highest index is assumed.
let witnessCommits = block.transactions[0].outs
.filter(out => out.script.slice(0, 6).equals(Buffer.from('6a24aa21a9ed', 'hex')))
.map(out => out.script.slice(6, 38))
// Use the commit with the highest output (should only be one though)
block.witnessCommit = witnessCommits[witnessCommits.length - 1]
}
return block
} }
function readInt32 () { static fromHex (hex: string): Block {
const i = buffer.readInt32LE(offset) return Block.fromBuffer(Buffer.from(hex, 'hex'))
offset += 4
return i
} }
const block = new Block() static calculateTarget (bits: number): Buffer {
block.version = readInt32() const exponent = ((bits & 0xff000000) >> 24) - 3
block.prevHash = readSlice(32) const mantissa = bits & 0x007fffff
block.merkleRoot = readSlice(32) const target = Buffer.alloc(32, 0)
block.timestamp = readUInt32() target.writeUIntBE(mantissa, 29 - exponent, 3)
block.bits = readUInt32() return target
block.nonce = readUInt32()
if (buffer.length === 80) return block
function readVarInt () {
const vi = varuint.decode(buffer, offset)
offset += varuint.decode.bytes
return vi
} }
function readTransaction () { static calculateMerkleRoot (transactions: Array<any>, forWitness: boolean | void): Buffer {
const tx = Transaction.fromBuffer(buffer.slice(offset), true) typeforce([{ getHash: types.Function }], transactions)
offset += tx.byteLength() if (transactions.length === 0) throw errorMerkleNoTxes
return tx if (forWitness && !txesHaveWitness(transactions)) throw errorWitnessNotSegwit
const hashes = transactions.map(transaction => transaction.getHash(forWitness))
const rootHash = fastMerkleRoot(hashes, bcrypto.hash256)
return forWitness
? bcrypto.hash256(Buffer.concat([rootHash, transactions[0].ins[0].witness[0]]))
: rootHash
} }
const nTransactions = readVarInt() hasWitnessCommit (): boolean {
block.transactions = [] return txesHaveWitness(this.transactions)
for (var i = 0; i < nTransactions; ++i) {
const tx = readTransaction()
block.transactions.push(tx)
} }
return block byteLength (headersOnly: boolean): number {
} if (headersOnly || !this.transactions) return 80
Block.prototype.byteLength = function (headersOnly) { return 80 + varuint.encodingLength(this.transactions.length) +
if (headersOnly || !this.transactions) return 80 this.transactions.reduce((a, x) => a + x.byteLength(), 0)
return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) {
return a + x.byteLength()
}, 0)
}
Block.fromHex = function (hex) {
return Block.fromBuffer(Buffer.from(hex, 'hex'))
}
Block.prototype.getHash = function () {
return bcrypto.hash256(this.toBuffer(true))
}
Block.prototype.getId = function () {
return this.getHash().reverse().toString('hex')
}
Block.prototype.getUTCDate = function () {
const date = new Date(0) // epoch
date.setUTCSeconds(this.timestamp)
return date
}
// TODO: buffer, offset compatibility
Block.prototype.toBuffer = function (headersOnly) {
const buffer = Buffer.allocUnsafe(this.byteLength(headersOnly))
let offset = 0
function writeSlice (slice) {
slice.copy(buffer, offset)
offset += slice.length
} }
function writeInt32 (i) { getHash (): Buffer {
buffer.writeInt32LE(i, offset) return bcrypto.hash256(this.toBuffer(true))
offset += 4
}
function writeUInt32 (i) {
buffer.writeUInt32LE(i, offset)
offset += 4
} }
writeInt32(this.version) getId (): string {
writeSlice(this.prevHash) return Buffer.from(this.getHash().reverse()).toString('hex')
writeSlice(this.merkleRoot) }
writeUInt32(this.timestamp)
writeUInt32(this.bits)
writeUInt32(this.nonce)
if (headersOnly || !this.transactions) return buffer getUTCDate (): Date {
const date = new Date(0) // epoch
date.setUTCSeconds(this.timestamp)
varuint.encode(this.transactions.length, buffer, offset) return date
offset += varuint.encode.bytes }
this.transactions.forEach(function (tx) { // TODO: buffer, offset compatibility
const txSize = tx.byteLength() // TODO: extract from toBuffer? toBuffer (headersOnly: boolean): Buffer {
tx.toBuffer(buffer, offset) const buffer: Buffer = Buffer.allocUnsafe(this.byteLength(headersOnly))
offset += txSize
})
return buffer let offset: number = 0
const writeSlice = (slice: Buffer): void => {
slice.copy(buffer, offset)
offset += slice.length
}
const writeInt32 = (i: number): void => {
buffer.writeInt32LE(i, offset)
offset += 4
}
const writeUInt32 = (i: number): void => {
buffer.writeUInt32LE(i, offset)
offset += 4
}
writeInt32(this.version)
writeSlice(this.prevHash)
writeSlice(this.merkleRoot)
writeUInt32(this.timestamp)
writeUInt32(this.bits)
writeUInt32(this.nonce)
if (headersOnly || !this.transactions) return buffer
varuint.encode(this.transactions.length, buffer, offset)
offset += varuint.encode.bytes
this.transactions.forEach(tx => {
const txSize = tx.byteLength() // TODO: extract from toBuffer?
tx.toBuffer(buffer, offset)
offset += txSize
})
return buffer
}
toHex (headersOnly: boolean): string {
return this.toBuffer(headersOnly).toString('hex')
}
checkMerkleRoot (): boolean {
if (!this.transactions) throw errorMerkleNoTxes
const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions)
return this.merkleRoot.compare(actualMerkleRoot) === 0
}
checkWitnessCommit (): boolean {
if (!this.transactions) throw errorMerkleNoTxes
if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit
const actualWitnessCommit = Block.calculateMerkleRoot(this.transactions, true)
return this.witnessCommit.compare(actualWitnessCommit) === 0
}
checkProofOfWork (): boolean {
const hash: Buffer = Buffer.from(this.getHash().reverse())
const target = Block.calculateTarget(this.bits)
return hash.compare(target) <= 0
}
} }
Block.prototype.toHex = function (headersOnly) {
return this.toBuffer(headersOnly).toString('hex')
}
Block.calculateTarget = function (bits) {
const exponent = ((bits & 0xff000000) >> 24) - 3
const mantissa = bits & 0x007fffff
const target = Buffer.alloc(32, 0)
target.writeUIntBE(mantissa, 29 - exponent, 3)
return target
}
Block.calculateMerkleRoot = function (transactions) {
typeforce([{ getHash: types.Function }], transactions)
if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions')
const hashes = transactions.map(function (transaction) {
return transaction.getHash()
})
return fastMerkleRoot(hashes, bcrypto.hash256)
}
Block.prototype.checkMerkleRoot = function () {
if (!this.transactions) return false
const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions)
return this.merkleRoot.compare(actualMerkleRoot) === 0
}
Block.prototype.checkProofOfWork = function () {
const hash = this.getHash().reverse()
const target = Block.calculateTarget(this.bits)
return hash.compare(target) <= 0
}
module.exports = Block
export {}

View file

@ -1,6 +1,6 @@
const opcodes = require('bitcoin-ops') const opcodes = require('bitcoin-ops')
import * as Block from './block' import { Block } from './block'
import * as ECPair from './ecpair' import * as ECPair from './ecpair'
import * as Transaction from './transaction' import * as Transaction from './transaction'
import * as TransactionBuilder from './transaction_builder' import * as TransactionBuilder from './transaction_builder'

View file

@ -1,6 +1,6 @@
const { describe, it, beforeEach } = require('mocha') const { describe, it, beforeEach } = require('mocha')
const assert = require('assert') const assert = require('assert')
const Block = require('../dist/src/block') const Block = require('..').Block
const fixtures = require('./fixtures/block') const fixtures = require('./fixtures/block')