test-iso8583-old.py 29.6 KB
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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
"""Threaded ISO8583 socket tester.

Usage (Windows/Linux):

  python test-iso8583.py --host 10.31.224.200 --port 10002 --threads 10 --count 100

What it does:
- Opens one TCP connection.
- Sends one optional sign-on (0800, bit70=301).
- Then sends N transaction tests (0200).

Framing matches the logs you shared:
- 4 ASCII digits length prefix (payload length)
- ISO payload as ASCII
- Trailing ETX byte 0x03
"""

from __future__ import annotations

import argparse
import queue
import socket
import statistics
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple


ASCII_FIELD_SPECS: Dict[int, Tuple[str, int]] = {
    2: ("llvar", 2),
    3: ("fixed", 6),
    4: ("fixed", 12),
    7: ("fixed", 10),
    11: ("fixed", 6),
    12: ("fixed", 6),
    13: ("fixed", 4),
    15: ("fixed", 4),
    18: ("fixed", 4),
    22: ("fixed", 3),
    32: ("llvar", 2),
    33: ("llvar", 2),
    35: ("llvar", 2),
    37: ("fixed", 12),
    39: ("fixed", 2),
    41: ("fixed", 8),
    42: ("fixed", 15),
    43: ("fixed", 40),
    49: ("fixed", 3),
    59: ("lllvar", 3),
    60: ("lllvar", 3),
    61: ("lllvar", 3),
    62: ("lllvar", 3),
    63: ("lllvar", 3),
    70: ("fixed", 3),
    102: ("llvar", 2),
    107: ("lllvar", 3),
}


ETX = b"\x03"


def load_invoices_from_file(path: str) -> List[str]:
    raw = open(path, "rb").read()

    # BOM-aware decoding: supports common encodings seen on Windows.
    if raw.startswith(b"\xff\xfe") or raw.startswith(b"\xfe\xff"):
        text = raw.decode("utf-16")
    elif raw.startswith(b"\xef\xbb\xbf"):
        text = raw.decode("utf-8-sig")
    else:
        try:
            text = raw.decode("utf-8")
        except UnicodeDecodeError:
            # Many editors save plain "Unicode" as UTF-16 without an obvious BOM.
            text = raw.decode("utf-16")

    invoices: List[str] = []
    for line in text.splitlines():
        s = line.strip()
        if not s or s.startswith("#"):
            continue
        invoices.append(s)
    return invoices


class InvoicePicker:
    def __init__(self, invoices: List[str], *, mode: str):
        if not invoices:
            raise ValueError("invoices must not be empty")
        self._invoices = invoices
        self._mode = mode
        self._lock = threading.Lock()
        self._rr_index = 0

    def pick(self, *, thread_id: int) -> str:
        if self._mode == "single":
            return self._invoices[0]
        if self._mode == "thread":
            return self._invoices[thread_id % len(self._invoices)]
        if self._mode == "roundrobin":
            with self._lock:
                invoice = self._invoices[self._rr_index % len(self._invoices)]
                self._rr_index += 1
            return invoice
        raise ValueError(f"unknown inv mode: {self._mode}")


def now_bit7(dt: Optional[datetime] = None) -> str:
    if dt is None:
        dt = datetime.now()
    return dt.strftime("%m%d%H%M%S")


class StanCounter:
    def __init__(self, start: Optional[int] = None):
        self._lock = threading.Lock()
        if start is None:
            start = int(datetime.now().strftime("%H%M%S"))
        self._value = start % 1_000_000

    def next(self) -> str:
        with self._lock:
            value = self._value
            self._value = (self._value + 1) % 1_000_000
        return str(value).zfill(6)


def recv_exact(sock: socket.socket, n: int) -> bytes:
    chunks: List[bytes] = []
    remaining = n
    while remaining > 0:
        chunk = sock.recv(remaining)
        if not chunk:
            raise ConnectionError("socket closed while reading")
        chunks.append(chunk)
        remaining -= len(chunk)
    return b"".join(chunks)


def send_frame(
    sock: socket.socket,
    payload: bytes,
    *,
    use_etx: bool = True,
    debug: bool = False,
) -> None:
    # Some endpoints use a 4-digit ASCII length prefix + ETX trailer (0x03).
    # Others use only the length prefix with no ETX. Make this selectable.
    trailer = ETX if use_etx else b""
    frame_len = len(payload) + len(trailer)
    length = str(frame_len).zfill(4).encode("ascii")
    if debug:
        try:
            mode = "etx" if use_etx else "no-etx"
            # print(f"SEND[{mode}] len={length.decode('ascii')} payload={payload!r}")
        except Exception:
            pass

        try:
            parsed = parse_network_0810(payload)
            mti = parsed.get(0)
            bit7 = parsed.get(7)
            bit11 = parsed.get(11)
            bit41 = parsed.get(41)
            bit61 = parsed.get(61)
            bit70 = parsed.get(70)
            info = []
            if mti:
                info.append(f"mti={mti}")
            if bit7:
                info.append(f"bit7={bit7}")
            # if bit11:
            #     info.append(f"bit11={bit11}")
            # # if bit41:
            #     info.append(f"bit41={bit41.rstrip()}")
            if bit61:
                info.append(f"bit61={bit61}")
            # if bit70:
            #     info.append(f"bit70={bit70}")
            if info:
                print("SEND INFO " + " ".join(info))
        except Exception:
            pass
    sock.sendall(length + payload + trailer)


def recv_frame(sock: socket.socket, *, expect_etx: bool = True, debug: bool = False) -> bytes:
    length_raw = recv_exact(sock, 4)
    try:
        length = int(length_raw.decode("ascii"))
    except ValueError as e:
        raise ValueError(f"invalid length prefix: {length_raw!r}") from e
    data = recv_exact(sock, length)
    if expect_etx:
        if not data.endswith(ETX):
            raise ValueError(
                f"invalid frame trailer (expected ETX 0x03): {data[-1:]!r}"
            )
        payload = data[:-1]
    else:
        # No ETX expected: payload is the whole body.
        payload = data

    if debug:
        try:
            mode = "etx" if expect_etx else "no-etx"
            # print(f"RECV[{mode}] len={str(length).zfill(4)} payload={payload!r}")
        except Exception:
            pass

        try:
            parsed = parse_network_0810(payload)
            mti = parsed.get(0)
            bit7 = parsed.get(7)
            bit11 = parsed.get(11)
            rc39 = parsed.get(39)
            info = []
            if mti:
                info.append(f"mti={mti}")
            if bit7:
                info.append(f"bit7={bit7}")
            # if bit11:
            #     info.append(f"bit11={bit11}")
            if rc39:
                info.append(f"rc39={rc39}")
            if info:
                print("RECV INFO " + " ".join(info))
        except Exception:
            pass

    return payload


def bits_from_hex_bitmap(hex16: str, offset: int) -> List[int]:
    """Return ISO bit numbers set in a 64-bit bitmap represented as 16 hex chars."""
    b = bytes.fromhex(hex16)
    out: List[int] = []
    for byte_index, byte_value in enumerate(b):
        for bit_index in range(8):
            mask = 1 << (7 - bit_index)
            if byte_value & mask:
                out.append(offset + byte_index * 8 + bit_index + 1)
    return out


def parse_network_0810(payload: bytes) -> Dict[int, str]:
    """Parse a minimal subset of fields from an ASCII ISO8583 response.

    Uses bitmap + a small field spec table so we can reliably reach bit 39 for 0210.
    """
    s = payload.decode("ascii", errors="replace")
    if len(s) < 4 + 16:
        raise ValueError(f"payload too short: {payload!r}")

    mti = s[:4]
    pmap = s[4:20]
    bits = bits_from_hex_bitmap(pmap, 0)
    index = 20
    if 1 in bits:
        smap = s[index: index + 16]
        bits += bits_from_hex_bitmap(smap, 64)
        index += 16

    values: Dict[int, str] = {0: mti}
    for bit in sorted(bits):
        if bit == 1:
            continue
        spec = ASCII_FIELD_SPECS.get(bit)
        if spec is None:
            break

        kind, n = spec
        if kind == "fixed":
            values[bit] = s[index: index + n]
            index += n
        elif kind == "llvar":
            length = int(s[index: index + n])
            index += n
            values[bit] = s[index: index + length].rstrip()
            index += length
        elif kind == "lllvar":
            length = int(s[index: index + n])
            index += n
            values[bit] = s[index: index + length].rstrip()
            index += length
        else:
            break

        if bit == 39:
            break

    return values


def build_0800_network(stan: str, code70: str) -> bytes:
    """Build an ASCII 0800 network management message with bits 7, 11, 70."""
    mti = "0800"
    # Primary bitmap: bit 1,7,11 set => 0x8220000000000000
    # Secondary bitmap: bit 70 set => 0x0400000000000000
    primary = "8220000000000000"
    secondary = "0400000000000000"
    bit7 = now_bit7()
    return f"{mti}{primary}{secondary}{bit7}{stan}{code70}".encode("ascii")


def build_0200_transaction(
    stan: str,
    amount12: str = "000000000000",
    bit61: str = "3275050002008001801990",
) -> bytes:
    """Build an ASCII 0200 transaction (BJB-style) matching the reference log."""
    dt = datetime.now()
    mti = "0200"
    bitmap = "F23A4401A8E0803A0000000004200000"

    pan = "622011444444444444"
    proc_code = "341019"
    bit7 = dt.strftime("%m%d%H%M%S")
    bit11 = stan
    bit12 = dt.strftime("%H%M%S")
    bit13 = dt.strftime("%m%d")
    bit15 = (dt + timedelta(days=1)).strftime("%m%d")

    bit18 = "6010"
    bit22 = "021"
    bit32 = "110"
    bit33 = "00110"
    bit35 = "622011444444444444=9912"
    bit37 = ("000000" + stan)[-12:]
    bit41 = "N703".ljust(8)
    bit42 = "02N703".ljust(15)
    bit43 = "TLR     N703".ljust(40)
    bit49 = "360"
    bit59 = "PAY"
    bit60 = "120"
    bit63 = "214"
    bit102 = "0010823214360".ljust(20)
    bit107 = "0010"

    parts = [
        mti,
        bitmap,
        f"{len(pan):02d}{pan}",
        proc_code,
        amount12,
        bit7,
        bit11,
        bit12,
        bit13,
        bit15,
        bit18,
        bit22,
        f"{len(bit32):02d}{bit32}",
        f"{len(bit33):02d}{bit33}",
        f"{len(bit35):02d}{bit35}",
        bit37,
        bit41,
        bit42,
        bit43,
        bit49,
        f"{len(bit59):03d}{bit59}",
        f"{len(bit60):03d}{bit60}",
        f"{len(bit61):03d}{bit61}",
        f"{len(bit63):03d}{bit63}",
        f"{len(bit102):02d}{bit102}",
        f"{len(bit107):03d}{bit107}",
    ]
    return "".join(parts).encode("ascii")


@dataclass
class WorkerResult:
    thread_id: int
    ok: int = 0
    fail: int = 0
    latencies_ms: List[float] = field(default_factory=list)
    errors: Dict[str, int] = field(default_factory=dict)

    def record_error(self, msg: str) -> None:
        self.fail += 1
        self.errors[msg] = self.errors.get(msg, 0) + 1


class ResponseDispatcher:
    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._pending: Dict[str, Tuple[int, "queue.Queue[bytes]"]] = {}
        self._dead = threading.Event()
        self._dead_exc: Optional[BaseException] = None

    def register(self, stan: str, *, thread_id: int) -> "queue.Queue[bytes]":
        q: "queue.Queue[bytes]" = queue.Queue(maxsize=1)
        with self._lock:
            self._pending[stan] = (thread_id, q)
        return q

    def unregister(self, stan: str) -> None:
        with self._lock:
            self._pending.pop(stan, None)

    def mark_dead(self, exc: BaseException) -> None:
        with self._lock:
            self._dead_exc = exc
        self._dead.set()

    def deliver(self, stan: str, payload: bytes) -> bool:
        with self._lock:
            item = self._pending.get(stan)
        if item is None:
            return False
        _, q = item
        try:
            q.put_nowait(payload)
        except queue.Full:
            return True
        return True

    def thread_id_for(self, stan: str) -> Optional[int]:
        with self._lock:
            item = self._pending.get(stan)
        if item is None:
            return None
        return item[0]

    def wait(self, q: "queue.Queue[bytes]", timeout: float) -> bytes:
        if self._dead.is_set():
            exc = self._dead_exc
            raise ConnectionError(f"receiver stopped: {exc}")
        try:
            return q.get(timeout=timeout)
        except queue.Empty as e:
            if self._dead.is_set():
                exc = self._dead_exc
                raise ConnectionError(f"receiver stopped: {exc}") from e
            raise TimeoutError("timed out waiting for response") from e


def receiver_loop(
    s1socket: socket.socket,
    dispatcher: ResponseDispatcher,
    *,
    expect_etx: bool,
    debug_raw: bool,
    stop_event: threading.Event,
) -> None:
    payload_queue: "queue.Queue[Optional[bytes]]" = queue.Queue()

    def process_loop() -> None:
        try:
            while True:
                payload = payload_queue.get()
                if payload is None:
                    break

                try:
                    parsed = parse_network_0810(payload)
                    stan = parsed.get(11)
                except Exception:
                    parsed = {}
                    stan = None

                if stan:
                    if debug_raw:
                        tid = dispatcher.thread_id_for(stan)
                        mti = parsed.get(0)
                        bit7 = parsed.get(7)
                        rc39 = parsed.get(39)
                        tlabel = f"T{tid}" if tid is not None and tid >= 0 else "SIGNON"
                        mode = "etx" if expect_etx else "no-etx"
                        # print(
                            # f"RECV DATA[{mode}] {tlabel} bit11={stan} len={len(payload)} payload={payload!r}"
                        # )
                        info = []
                        if mti:
                            info.append(f"mti={mti}")
                        if bit7:
                            info.append(f"bit7={bit7}")
                        if rc39:
                            info.append(f"rc39={rc39}")
                        print(
                            f"RECV {tlabel} bit11={stan}"
                            + (" " + " ".join(info) if info else "")
                        )

                    ok = dispatcher.deliver(stan, payload)
                    if not ok and debug_raw:
                        print(f"RECV WARN unregistered stan={stan}")
                else:
                    if debug_raw:
                        print(f"RECV WARN no bit11/STAN in response payload={payload!r}")
        except Exception as e:
            dispatcher.mark_dead(e)
            stop_event.set()

    proc_thread = threading.Thread(target=process_loop, name="receiver_process", daemon=True)
    proc_thread.start()

    try:
        while not stop_event.is_set():
            payload = recv_frame(s1socket, expect_etx=expect_etx, debug=False)
            payload_queue.put(payload)
    except Exception as e:
        dispatcher.mark_dead(e)
    finally:
        try:
            payload_queue.put(None)
        except Exception:
            pass


def worker(
    thread_id: int,
    s1socket: socket.socket,
    send_lock: threading.Lock,
    count: int,
    stan_counter: StanCounter,
    result: WorkerResult,
    debug_raw: bool,
    use_etx: bool,
    invoice_picker: InvoicePicker,
    dispatcher: ResponseDispatcher,
    timeout: float,
    stop_event: threading.Event,
    stop_at: Optional[float],
) -> None:
    try:
        sent = 0
        while not stop_event.is_set():
            if stop_at is not None and time.perf_counter() >= stop_at:
                break
            if count > 0 and sent >= count:
                break

            stan = stan_counter.next()
            bit61 = invoice_picker.pick(thread_id=thread_id)
            payload = build_0200_transaction(stan, bit61=bit61)
            q = dispatcher.register(stan, thread_id=thread_id)
            try:
                t0 = time.perf_counter()
                with send_lock:
                    if debug_raw:
                        print(f"SEND T{thread_id} bit11={stan}")
                    send_frame(s1socket, payload, use_etx=use_etx, debug=debug_raw)
                resp = dispatcher.wait(q, timeout=timeout)
                dt_ms = (time.perf_counter() - t0) * 1000.0
            finally:
                dispatcher.unregister(stan)

            sent += 1

            parsed = parse_network_0810(resp)
            if parsed.get(0) == "0210" and parsed.get(39) == "00":
                result.ok += 1
                result.latencies_ms.append(dt_ms)
            else:
                result.record_error(f"bad_resp:{parsed}")
    except Exception as e:
        if debug_raw:
            result.record_error(f"{type(e).__name__}:{e}")
        else:
            result.record_error(type(e).__name__)



def percentile(sorted_values: List[float], p: float) -> float:
    if not sorted_values:
        return 0.0
    if p <= 0:
        return sorted_values[0]
    if p >= 100:
        return sorted_values[-1]
    k = (len(sorted_values) - 1) * (p / 100.0)
    f = int(k)
    c = min(f + 1, len(sorted_values) - 1)
    if f == c:
        return sorted_values[f]
    d0 = sorted_values[f] * (c - k)
    d1 = sorted_values[c] * (k - f)
    return d0 + d1


def main(argv: Optional[List[str]] = None) -> int:
    parser = argparse.ArgumentParser(
        description="Threaded ISO8583 (BJB-style) socket tester")
    parser.add_argument("--host", required=True)
    parser.add_argument("--port", required=True, type=int)
    parser.add_argument("--threads", type=int, default=1)
    parser.add_argument("--count", type=int, default=10,
                        help="test count per thread")
    parser.add_argument(
        "--loop",
        action="store_true",
        help="loop forever (ignores --count unless --duration is set)",
    )
    parser.add_argument(
        "--duration",
        type=float,
        default=None,
        help="run for N seconds then stop (works with --loop)",
    )
    parser.add_argument("--timeout", type=float, default=5.0)
    parser.add_argument(
        "--inv",
        "--bit61",
        dest="bit61",
        action="append",
        default=[],
        help=(
            "field 61 (bit61) / invoice profile string. "
            "Can be provided multiple times to spread requests across invoices."
        ),
    )
    parser.add_argument(
        "--inv-file",
        default=None,
        help=(
            "path to a text file with one invoice per line (blank lines and lines starting with # are ignored)"
        ),
    )
    parser.add_argument(
        "--inv-mode",
        choices=("single", "thread", "roundrobin"),
        default=None,
        help=(
            "how to choose invoice when multiple are provided: "
            "single=always first, thread=one invoice per thread, roundrobin=cycle globally"
        ),
    )
    parser.add_argument(
        "--no-etx",
        action="store_true",
        help="use ASCII length prefix only (no trailing ETX byte)",
    )
    parser.add_argument("--no-signon", action="store_true",
                        help="skip initial 0800/301")
    parser.add_argument("--debug-raw", action="store_true", help="print raw frames sent")
    args = parser.parse_args(argv)

    invoices: List[str] = []
    if args.bit61:
        invoices.extend(args.bit61)
    if args.inv_file:
        invoices.extend(load_invoices_from_file(args.inv_file))
    if not invoices:
        invoices = ["3275050002008001801990"]

    inv_mode = args.inv_mode
    if inv_mode is None:
        inv_mode = "roundrobin" if len(invoices) > 1 else "single"
    invoice_picker = InvoicePicker(invoices, mode=inv_mode)

    stop_at: Optional[float] = None
    if args.duration is not None:
        if args.duration <= 0:
            raise SystemExit("--duration must be > 0")
        stop_at = time.perf_counter() + args.duration

    effective_count = 0 if args.loop else args.count
    total_planned = (
        None
        if args.loop
        else (args.threads * effective_count + (0 if args.no_signon else 1))
    )
    frame_mode = "no-etx" if args.no_etx else "etx"
    if total_planned is None:
        planned_str = "total_requests~=unbounded"
    else:
        planned_str = f"total_requests~={total_planned}"
    run_mode = "loop" if args.loop else "fixed"
    dur_str = "" if args.duration is None else f" duration={args.duration}s"
    print(
        f"Target {args.host}:{args.port} mode={frame_mode} run={run_mode}{dur_str} "
        f"threads={args.threads} count/thread={effective_count} {planned_str}"
    )

    stan_counter = StanCounter()
    results: List[WorkerResult] = [WorkerResult(
        thread_id=i) for i in range(args.threads)]
    threads: List[threading.Thread] = []

    s1socket = socket.create_connection((args.host, args.port), timeout=args.timeout)
    s1socket.settimeout(args.timeout)
    send_lock = threading.Lock()
    dispatcher = ResponseDispatcher()
    stop_event = threading.Event()
    recv_thread = threading.Thread(
        target=receiver_loop,
        args=(
            s1socket,
            dispatcher,
        ),
        kwargs={
            "expect_etx": not args.no_etx,
            "debug_raw": args.debug_raw,
            "stop_event": stop_event,
        },
        daemon=True,
    )
    recv_thread.start()

    if not args.no_signon:
        stan = stan_counter.next()
        payload = build_0800_network(stan, "301")
        q = dispatcher.register(stan, thread_id=-1)
        try:
            with send_lock:
                if args.debug_raw:
                    print(f"SEND SIGNON bit11={stan}")
                send_frame(
                    s1socket,
                    payload,
                    use_etx=not args.no_etx,
                    debug=args.debug_raw,
                )
            resp = dispatcher.wait(q, timeout=args.timeout)
            parsed = parse_network_0810(resp)
        except Exception as e:
            print(f"Sign-on error: {type(e).__name__}: {e}")
            try:
                dispatcher.unregister(stan)
                stop_event.set()
                s1socket.close()
            finally:
                return 2
        finally:
            dispatcher.unregister(stan)

        if not (parsed.get(0) == "0810" and parsed.get(39) == "00"):
            print(f"Sign-on failed: {parsed}")
            try:
                stop_event.set()
                s1socket.close()
            finally:
                return 2

    t_start = time.perf_counter()
    try:
        for i in range(args.threads):
            t = threading.Thread(
                target=worker,
                args=(
                    i,
                    s1socket,
                    send_lock,
                    effective_count,
                    stan_counter,
                    results[i],
                    args.debug_raw,
                    not args.no_etx,
                    invoice_picker,
                    dispatcher,
                    args.timeout,
                    stop_event,
                    stop_at,
                ),
                daemon=True,
            )
            threads.append(t)
            t.start()

        try:
            for t in threads:
                t.join()
        except KeyboardInterrupt:
            print("\nInterrupted: stopping threads...")
            stop_event.set()
            try:
                s1socket.close()
            except Exception:
                pass
            for t in threads:
                t.join(timeout=1.0)

        elapsed = time.perf_counter() - t_start
    finally:
        try:
            stop_event.set()
            s1socket.close()
        except Exception:
            pass

    ok = sum(r.ok for r in results)
    fail = sum(r.fail for r in results)
    latencies = [x for r in results for x in r.latencies_ms]
    latencies_sorted = sorted(latencies)
    rps = ok / elapsed if elapsed > 0 else 0.0

    print("\nSummary")
    print(f"  elapsed: {elapsed:.3f}s")
    print(f"  ok:      {ok}")
    print(f"  fail:    {fail}")
    print(f"  rps(ok): {rps:.2f}/s")
    if latencies_sorted:
        print(
            f"  latency_ms: avg={statistics.mean(latencies_sorted):.2f} p50={percentile(latencies_sorted, 50):.2f} p95={percentile(latencies_sorted, 95):.2f} max={latencies_sorted[-1]:.2f}")

    merged_errors: Dict[str, int] = {}
    for r in results:
        for msg, cnt in r.errors.items():
            merged_errors[msg] = merged_errors.get(msg, 0) + cnt
    if merged_errors:
        print("\nErrors")
        for msg, cnt in sorted(merged_errors.items(), key=lambda kv: (-kv[1], kv[0])):
            print(f"  {cnt}x {msg}")

    return 0


if __name__ == "__main__":
    raise SystemExit(main())


REFERENCE_LOG = """ Test ISO8583 BJB
Open connection
2026-04-18 01:57:33,883 INFO ISO8583 10.31.224.200 bjb 139792218643952 connect to port 10002
signon
2026-04-18 01:57:38,885 INFO ISO8583 10.31.224.200 bjb 139792218643952 Encode MTI 0800 Data {7: '0418015738', 11: '015730', 70: '301'}
2026-04-18 01:57:38,886 INFO ISO8583 10.31.224.200 bjb 139792218643952 ISO8583 to raw [b'0800822000000000000004000000000000000418015738015730301']
2026-04-18 01:57:38,886 INFO ISO8583 10.31.224.200 bjb 139792218643952 Send [b'00560800822000000000000004000000000000000418015738015730301\x03']
2026-04-18 01:57:38,920 INFO ISO8583 10.31.224.200 bjb 139792218643952 Receive [b'0058081082200000020000000400000000000000041718573901573000301\x03']
2026-04-18 01:57:38,920 INFO ISO8583 10.31.224.200 bjb 139792218643952 Raw to ISO8583 [b'081082200000020000000400000000000000041718573901573000301']
2026-04-18 01:57:38,923 INFO ISO8583 10.31.224.200 bjb 139792218643952 -> 139792218855264 Decode MTI 0810 Data {7: '0417185739', 11: '015730', 39: '00', 70: '301'}
network test
2026-04-18 01:57:38,924 INFO ISO8583 10.31.224.200 bjb 139792218643952 Encode MTI 0800 Data {7: '0418015738', 11: '015732', 70: '001'}
2026-04-18 01:57:38,924 INFO ISO8583 10.31.224.200 bjb 139792218643952 ISO8583 to raw [b'0800822000000000000004000000000000000418015738015732001']
2026-04-18 01:57:38,925 INFO ISO8583 10.31.224.200 bjb 139792218643952 Send [b'00560800822000000000000004000000000000000418015738015732001\x03']
2026-04-18 01:57:39,923 INFO ISO8583 10.31.224.200 bjb 139792218643952 Receive [b'0058081082200000020000000400000000000000041718573901573200001\x03']
2026-04-18 01:57:39,924 INFO ISO8583 10.31.224.200 bjb 139792218643952 Raw to ISO8583 [b'081082200000020000000400000000000000041718573901573200001']
2026-04-18 01:57:39,926 INFO ISO8583 10.31.224.200 bjb 139792218643952 -> 139792218855264 Decode MTI 0810 Data {7: '0417185739', 11: '015732', 39: '00', 70: '301'}
transaction
2026-04-17 10:52:40,576 INFO ISO8583 10.31.224.200 bjb 139781348025040 -> 139781375402896 Encode MTI 0200 Data {2: '622011444444444444', 3: '341019', 4: '000000000000', 7: '0417105240', 11: '398086', 12: '105240', 13: '0417', 15: '0418', 18: '6010', 22: '021', 32: '110', 33: '00110', 35: '622011444444444444=9912', 37: '000000358002', 41: 'N703', 42: '02N703', 43: 'TLR     N703', 49: '360', 59: 'PAY', 60: '120', 61: '3275010003031084002000', 63: '214', 102: '0010823214360', 107: '0010'}
2026-04-17 10:52:40,569 INFO ISO8583 10.31.224.200 bjb 139781348025040 ISO8583 to raw [b'0200F23A4401A8E0803A000000000420000018622011444444444444341019000000000000041710524039808610524004170418601002103110050011023622011444444444444=9912000000358002N703    02N703         TLR     N703                            360003PAY0031200223275010003031084002000003214200010823214360       0040010']
2026-04-17 10:52:40,569 INFO ISO8583 10.31.224.200 bjb 139781348025040 Send [b'02990200F23A4401A8E0803A000000000420000018622011444444444444341019000000000000041710524039808610524004170418601002103110050011023622011444444444444=9912000000358002N703    02N703         TLR     N703                            360003PAY0031200223275010003031084002000003214200010823214360       0040010\x03']
2026-04-17 10:52:40,625 INFO ISO8583 10.31.224.200 bjb 139781348025040 Receipt [b'05810210f23a4401aae0803e000000000420000018622011444444444444341019000000010233041710524039808610524004170418601002103110050011023622011444444444444=991200000035800200N703    02N703         TLR     N703                            360003PAY00312002232750100030310840020002773275010003031084002000DRS S KRISTIONO HARYANTO           JATIWARINGIN ASRI II,T NO.18,RT 001JATIWARINGIN                       PONDOK GEDE                        JAWA BARAT                         00000000018800000000013220000930000000078708000000037780000000116488000000106255003214200010823214360       0040010\x03']
2026-04-17 10:52:40,625 INFO ISO8583 10.31.224.200 bjb 139781348025040 Raw to ISO8583 [b'0210f23a4401aae0803e000000000420000018622011444444444444341019000000010233041710524039808610524004170418601002103110050011023622011444444444444=991200000035800200N703    02N703         TLR     N703                            360003PAY00312002232750100030310840020002773275010003031084002000DRS S KRISTIONO HARYANTO           JATIWARINGIN ASRI II,T NO.18,RT 001JATIWARINGIN                       PONDOK GEDE                        JAWA BARAT                         00000000018800000000013220000930000000078708000000037780000000116488000000106255003214200010823214360       0040010']
2026-04-17 10:52:40,624 INFO ISO8583 10.31.224.200 bjb 139781348025040 Decode MTI 0210 Data {2: '622011444444444444', 3: '341019', 4: '000000010233', 7: '0417105240', 11: '398086', 12: '105240', 13: '0417', 15: '0418', 18: '6010', 22: '021', 32: '110', 33: '00110', 35: '622011444444444444=9912', 37: '000000358002', 39: '00', 41: 'N703', 42: '02N703', 43: 'TLR     N703', 49: '360', 59: 'PAY', 60: '120', 61: '3275010003031084002000', 62: '3275010003031084002000DRS S KRISTIONO HARYANTO           JATIWARINGIN ASRI II,T NO.18,RT 001JATIWARINGIN                       PONDOK GEDE                        JAWA BARAT                         00000000018800000000013220000930000000078708000000037780000000116488000000106255', 63: '214', 102: '0010823214360', 107: '0010'}
"""