From 39280443391f1cfa76d221dc2cd0362f390df20f Mon Sep 17 00:00:00 2001 From: The MMGen Project Date: Sat, 20 Mar 2021 12:16:29 +0000 Subject: [PATCH] mmnode-blocks-info: support JSON output --- mmgen/node_tools/BlocksInfo.py | 32 +++++++++++++++++++++++++++++++- mmnode-blocks-info | 8 ++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/mmgen/node_tools/BlocksInfo.py b/mmgen/node_tools/BlocksInfo.py index f5ce4e8..61e7731 100644 --- a/mmgen/node_tools/BlocksInfo.py +++ b/mmgen/node_tools/BlocksInfo.py @@ -20,7 +20,7 @@ mmgen.node_tools.BlocksInfo: Display information about a block or range of blocks """ -import re +import re,json from collections import namedtuple from time import strftime,gmtime from decimal import Decimal @@ -494,3 +494,33 @@ class BlocksInfo: 'utxo_increase': 1, 'utxo_size_inc': 117 } + +class JSONBlocksInfo(BlocksInfo): + + def __init__(self,cmd_args,opt,rpc): + super().__init__(cmd_args,opt,rpc) + Msg_r('{') + + async def process_blocks(self): + Msg_r('"block_data": [') + await super().process_blocks() + Msg_r(']') + + def output_block(self,data,n): + Msg_r( (', ','')[n==0] + json.dumps(data._asdict()) ) + + async def output_stats(self,res): + name,data = await res + def gen(data): + for d in data: + if len(d) == 2: + for k,v in d[1].items(): + yield (k,v) + else: + yield (d[1],d[2]) + Msg_r(', "{}_data": {}'.format(name,json.dumps(dict(gen(data))))) + + def process_stats_pre(self,i): pass + + def finalize_output(self): + Msg('}') diff --git a/mmnode-blocks-info b/mmnode-blocks-info index 4b5e9c5..7fb9966 100755 --- a/mmnode-blocks-info +++ b/mmnode-blocks-info @@ -21,7 +21,7 @@ mmnode-blocks-info: Display information about a block or range of blocks """ from mmgen.common import * -from mmgen.node_tools.BlocksInfo import BlocksInfo +from mmgen.node_tools.BlocksInfo import BlocksInfo,JSONBlocksInfo opts_data = { 'sets': [ @@ -29,6 +29,7 @@ opts_data = { ('hashes', True, 'stats', 'none'), ('stats', 'none', 'stats_only', False), ('stats_only', True, 'no_header', True), + ('json', True, 'no_header', True), ], 'text': { 'desc': 'Display information about a block or range of blocks', @@ -42,6 +43,7 @@ opts_data = { -h, --help Print this help message --, --longhelp Print help message for long options (common options) -H, --hashes Display only block numbers and hashes +-j, --json Produce JSON output -m, --miner-info Display miner info in coinbase transaction -M, --raw-miner-info Display miner info in uninterpreted form -n, --no-header Don’t print the column header @@ -122,7 +124,9 @@ async def main(): proto = init_proto_from_opts() - m = BlocksInfo( cmd_args, opt, await rpc_init(proto) ) + cls = JSONBlocksInfo if opt.json else BlocksInfo + + m = cls( cmd_args, opt, await rpc_init(proto) ) if not opt.no_header: m.print_header()