diff --git a/src/block.js b/src/block.js index 22449fd..18b49c7 100644 --- a/src/block.js +++ b/src/block.js @@ -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() { diff --git a/test/block.spec.ts b/test/block.spec.ts index 0f74392..e93420c 100644 --- a/test/block.spec.ts +++ b/test/block.spec.ts @@ -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); + } }); }); diff --git a/test/fixtures/block.json b/test/fixtures/block.json index c60685e..8ea521c 100644 --- a/test/fixtures/block.json +++ b/test/fixtures/block.json @@ -133,7 +133,10 @@ "prevHash": "8980ebb11236bacc66c447d5ad961bc546c0f9cc385a08000000000000000000", "timestamp": 1537429727, "valid": true, - "version": 536870912 + "version": 536870912, + "size": 2355, + "strippedSize": 2209, + "weight": 8982 } ], "invalid": [ diff --git a/ts_src/block.ts b/ts_src/block.ts index cf4ed51..0792edf 100644 --- a/ts_src/block.ts +++ b/ts_src/block.ts @@ -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) ); } diff --git a/types/block.d.ts b/types/block.d.ts index d77bb1b..7d8309c 100644 --- a/types/block.d.ts +++ b/types/block.d.ts @@ -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;