Add weight and ability to get strippedsize

This commit is contained in:
junderw 2019-11-29 15:30:23 +09:00
parent 29e319525f
commit 48bf08c0d3
No known key found for this signature in database
GPG key ID: B256185D3A971908
5 changed files with 28 additions and 6 deletions

View file

@ -127,12 +127,18 @@ class Block {
hasWitness() {
return anyTxHasWitness(this.transactions);
}
byteLength(headersOnly) {
weight() {
const base = this.byteLength(false, false);
const total = this.byteLength(false, true);
return base * 3 + total;
}
byteLength(headersOnly, allowWitness = true) {
if (headersOnly || !this.transactions) return 80;
return (
80 +
varuint.encodingLength(this.transactions.length) +
this.transactions.reduce((a, x) => a + x.byteLength(), 0)
// @ts-ignore using the __byteLength private method on Transaction
this.transactions.reduce((a, x) => a + x.__byteLength(allowWitness), 0)
);
}
getHash() {

View file

@ -48,6 +48,11 @@ describe('Block', () => {
assert.strictEqual(block.bits, f.bits);
assert.strictEqual(block.nonce, f.nonce);
assert.strictEqual(!block.transactions, f.hex.length === 160);
if (f.size && f.strippedSize && f.weight) {
assert.strictEqual(block.byteLength(false, true), f.size);
assert.strictEqual(block.byteLength(false, false), f.strippedSize);
assert.strictEqual(block.weight(), f.weight);
}
});
});

View file

@ -133,7 +133,10 @@
"prevHash": "8980ebb11236bacc66c447d5ad961bc546c0f9cc385a08000000000000000000",
"timestamp": 1537429727,
"valid": true,
"version": 536870912
"version": 536870912,
"size": 2355,
"strippedSize": 2209,
"weight": 8982
}
],
"invalid": [

View file

@ -148,13 +148,20 @@ export class Block {
return anyTxHasWitness(this.transactions!);
}
byteLength(headersOnly?: boolean): number {
weight(): number {
const base = this.byteLength(false, false);
const total = this.byteLength(false, true);
return base * 3 + total;
}
byteLength(headersOnly?: boolean, allowWitness: boolean = true): number {
if (headersOnly || !this.transactions) return 80;
return (
80 +
varuint.encodingLength(this.transactions.length) +
this.transactions.reduce((a, x) => a + x.byteLength(), 0)
// @ts-ignore using the __byteLength private method on Transaction
this.transactions.reduce((a, x) => a + x.__byteLength(allowWitness), 0)
);
}

3
types/block.d.ts vendored
View file

@ -15,7 +15,8 @@ export declare class Block {
getWitnessCommit(): Buffer | null;
hasWitnessCommit(): boolean;
hasWitness(): boolean;
byteLength(headersOnly?: boolean): number;
weight(): number;
byteLength(headersOnly?: boolean, allowWitness?: boolean): number;
getHash(): Buffer;
getId(): string;
getUTCDate(): Date;