File: send.py

package info (click to toggle)
python-ledgercomm 1.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 164 kB
  • sloc: python: 297; makefile: 2
file content (83 lines) | stat: -rwxr-xr-x 2,964 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""ledgercomm.cli.send module."""

import argparse
from pathlib import Path
import re
from typing import Iterator, Optional

from ledgercomm import Transport, __version__


def parse_file(filepath: Path, condition: Optional[str]) -> Iterator[str]:
    """Filter with `condition` and yield line of `filepath`."""
    with open(filepath, "r", encoding="utf-8") as f:
        for line in f:
            if condition and line.startswith(condition):
                yield line.replace(condition, "").strip()
            else:
                yield line.strip()


def main():
    """Entrypoint of ledgercomm-parse binary."""
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(help="sub-command help", dest="command")
    # file subparser
    parser_file = subparsers.add_parser("file", help="send APDUs from file")
    parser_file.add_argument("filepath", help="path of the file within APDUs")
    # stdin subparser
    _ = subparsers.add_parser("stdin", help="send APDUs from stdin")
    # stdin subparser
    parser_log = subparsers.add_parser("log", help="send APDUs from Ledger Live log file")
    parser_log.add_argument("filepath", help="path of the Ledger Live log file within APDUs")
    # args for main parser
    parser.add_argument("--hid", help="Use HID instead of TCP client", action="store_true")
    parser.add_argument("--server",
                        help="IP server of the TCP client (default: 127.0.0.1)",
                        default="127.0.0.1")
    parser.add_argument("--port", help="Port of the TCP client (default: 9999)", default=9999)
    parser.add_argument("--startswith",
                        help="Only send APDUs which starts with STARTSWITH (default: None)",
                        default=None)
    parser.add_argument("--version",
                        "-v",
                        help="Print LedgerComm package current version",
                        default=False,
                        action="store_true")

    args = parser.parse_args()

    if args.version:
        print(__version__)
        return 0

    transport = (Transport(interface="hid", debug=True) if args.hid else Transport(
        interface="tcp", server=args.server, port=args.port, debug=True))

    if args.command == "file":
        filepath: Path = Path(args.filepath)

        for apdu in parse_file(filepath, args.startswith):  # type: str
            if apdu:
                transport.exchange_raw(re.sub(r"[^a-fA-F0-9]", "", apdu))

    if args.command == "stdin":
        apdu: str = input()

        if args.startswith:
            apdu = apdu.replace(args.startswith, "").strip()

        if apdu:
            transport.exchange_raw(re.sub(r"[^a-fA-F0-9]", "", apdu))

    if args.command == "log":
        # TODO: implement Ledger Live log parser
        raise NotImplementedError("Ledger Live log parser is not yet available!")

    transport.close()

    return 0


if __name__ == "__main__":
    main()