github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-core-master/cli/sawtooth_cli/transaction.py (about)

     1  # Copyright 2017 Intel Corporation
     2  #
     3  # Licensed under the Apache License, Version 2.0 (the 'License');
     4  # you may not use this file except in compliance with the License.
     5  # You may obtain a copy of the License at
     6  #
     7  #     http://www.apache.org/licenses/LICENSE-2.0
     8  #
     9  # Unless required by applicable law or agreed to in writing, software
    10  # distributed under the License is distributed on an "AS IS" BASIS,
    11  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  # See the License for the specific language governing permissions and
    13  # limitations under the License.
    14  # ------------------------------------------------------------------------------
    15  
    16  import argparse
    17  from base64 import b64decode
    18  from sawtooth_cli import format_utils as fmt
    19  from sawtooth_cli.rest_client import RestClient
    20  from sawtooth_cli.exceptions import CliException
    21  from sawtooth_cli.parent_parsers import base_http_parser
    22  from sawtooth_cli.parent_parsers import base_list_parser
    23  from sawtooth_cli.parent_parsers import base_show_parser
    24  
    25  
    26  def add_transaction_parser(subparsers, parent_parser):
    27      """Adds argument parsers for the transaction list and show commands
    28  
    29          Args:
    30              subparsers: Add parsers to this subparser object
    31              parent_parser: The parent argparse.ArgumentParser object
    32      """
    33      parser = subparsers.add_parser(
    34          'transaction',
    35          help='Shows information on transactions in the current chain',
    36          description='Provides subcommands to display information about '
    37          'the transactions in the current blockchain.')
    38  
    39      grand_parsers = parser.add_subparsers(
    40          title='subcommands',
    41          dest='subcommand')
    42  
    43      grand_parsers.required = True
    44  
    45      grand_parsers.add_parser(
    46          'list',
    47          description='Lists all transactions in the current blockchain.',
    48          parents=[base_http_parser(), base_list_parser()],
    49          formatter_class=argparse.RawDescriptionHelpFormatter)
    50  
    51      show_parser = grand_parsers.add_parser(
    52          'show',
    53          description='Displays information for the specified transaction.',
    54          parents=[base_http_parser(), base_show_parser()],
    55          formatter_class=argparse.RawDescriptionHelpFormatter)
    56  
    57      show_parser.add_argument(
    58          'transaction_id',
    59          type=str,
    60          help='id (header_signature) of the transaction')
    61  
    62  
    63  def do_transaction(args):
    64      """Runs the transaction list or show command, printing to the console
    65  
    66          Args:
    67              args: The parsed arguments sent to the command at runtime
    68      """
    69      rest_client = RestClient(args.url, args.user)
    70  
    71      if args.subcommand == 'list':
    72          transactions = rest_client.list_transactions()
    73          keys = ('transaction_id', 'family', 'version', 'size', 'payload')
    74          headers = tuple(k.upper() if k != 'version' else 'VERS' for k in keys)
    75  
    76          def parse_txn_row(transaction, decode=True):
    77              decoded = b64decode(transaction['payload'])
    78              return (
    79                  transaction['header_signature'],
    80                  transaction['header']['family_name'],
    81                  transaction['header']['family_version'],
    82                  len(decoded),
    83                  str(decoded) if decode else transaction['payload'])
    84  
    85          if args.format == 'default':
    86              fmt.print_terminal_table(headers, transactions, parse_txn_row)
    87  
    88          elif args.format == 'csv':
    89              fmt.print_csv(headers, transactions, parse_txn_row)
    90  
    91          elif args.format == 'json' or args.format == 'yaml':
    92              data = [{k: d for k, d in zip(keys, parse_txn_row(b, False))}
    93                      for b in transactions]
    94  
    95              if args.format == 'yaml':
    96                  fmt.print_yaml(data)
    97              elif args.format == 'json':
    98                  fmt.print_json(data)
    99              else:
   100                  raise AssertionError('Missing handler: {}'.format(args.format))
   101  
   102          else:
   103              raise AssertionError('Missing handler: {}'.format(args.format))
   104  
   105      if args.subcommand == 'show':
   106          output = rest_client.get_transaction(args.transaction_id)
   107  
   108          if args.key:
   109              if args.key == 'payload':
   110                  output = b64decode(output['payload'])
   111              elif args.key in output:
   112                  output = output[args.key]
   113              elif args.key in output['header']:
   114                  output = output['header'][args.key]
   115              else:
   116                  raise CliException(
   117                      'Key "{}" not found in transaction or header'.format(
   118                          args.key))
   119  
   120          if args.format == 'yaml':
   121              fmt.print_yaml(output)
   122          elif args.format == 'json':
   123              fmt.print_json(output)
   124          else:
   125              raise AssertionError('Missing handler: {}'.format(args.format))