@@ -19,14 +19,14 @@ use std::io;
1919
2020use bitcoin;
2121use bitcoin:: blockdata:: script:: Script ;
22- use bitcoin:: { BitcoinHash , BlockHash } ;
22+ use bitcoin:: { BitcoinHash , BlockHash , VarInt } ;
2323use bitcoin:: hashes:: { Hash , sha256} ;
2424#[ cfg( feature = "serde" ) ] use serde:: { Deserialize , Deserializer , Serialize , Serializer } ;
2525#[ cfg( feature = "serde" ) ] use std:: fmt;
2626
2727use dynafed;
2828use Transaction ;
29- use encode:: { self , Encodable , Decodable } ;
29+ use encode:: { self , Encodable , Decodable , serialize } ;
3030
3131/// Data related to block signatures
3232#[ derive( Clone , Debug , Eq , Hash , PartialEq ) ]
@@ -354,6 +354,23 @@ pub struct Block {
354354serde_struct_impl ! ( Block , header, txdata) ;
355355impl_consensus_encoding ! ( Block , header, txdata) ;
356356
357+ impl Block {
358+ /// Get the size of the block
359+ pub fn get_size ( & self ) -> usize {
360+ // The size of the header + the size of the varint with the tx count + the txs themselves
361+ let base_size = serialize ( & self . header ) . len ( ) + VarInt ( self . txdata . len ( ) as u64 ) . len ( ) ;
362+ let txs_size: usize = self . txdata . iter ( ) . map ( Transaction :: get_size) . sum ( ) ;
363+ base_size + txs_size
364+ }
365+
366+ /// Get the weight of the block
367+ pub fn get_weight ( & self ) -> usize {
368+ let base_weight = 4 * ( serialize ( & self . header ) . len ( ) + VarInt ( self . txdata . len ( ) as u64 ) . len ( ) ) ;
369+ let txs_weight: usize = self . txdata . iter ( ) . map ( Transaction :: get_weight) . sum ( ) ;
370+ base_weight + txs_weight
371+ }
372+ }
373+
357374impl BitcoinHash < BlockHash > for Block {
358375 fn bitcoin_hash ( & self ) -> BlockHash {
359376 self . header . bitcoin_hash ( )
@@ -391,6 +408,8 @@ mod tests {
391408 assert_eq ! ( block. header. version, 0x20000000 ) ;
392409 assert_eq ! ( block. header. height, 2 ) ;
393410 assert_eq ! ( block. txdata. len( ) , 1 ) ;
411+ assert_eq ! ( block. get_size( ) , serialize( & block) . len( ) ) ;
412+ assert_eq ! ( block. get_weight( ) , 1089 ) ;
394413
395414 // Block with 3 transactions ... the rangeproofs are very large :)
396415 let block: Block = hex_deserialize ! (
@@ -601,6 +620,7 @@ mod tests {
601620 assert_eq ! ( block. header. version, 0x20000000 ) ;
602621 assert_eq ! ( block. header. height, 1 ) ;
603622 assert_eq ! ( block. txdata. len( ) , 3 ) ;
623+ assert_eq ! ( block. get_size( ) , serialize( & block) . len( ) ) ;
604624
605625 // 2-of-3 signed block from Liquid integration tests
606626 let block: Block = hex_deserialize ! (
0 commit comments