wallet-privacy-testkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Adversarial network tests for wallets and indexers."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,213 @@
1
+ """Record observable TLS lengths and timing while forwarding bytes unchanged."""
2
+
3
+ import json
4
+ import selectors
5
+ import socket
6
+ import socketserver
7
+ import threading
8
+ import time
9
+ from pathlib import Path
10
+
11
+ TLS_HEADER_BYTES = 5
12
+ TLS_MAX_CIPHERTEXT_BYTES = 18_432
13
+ TLS_CONTENT_TYPES = frozenset((20, 21, 22, 23, 24))
14
+ TLS_APPLICATION_DATA = 23
15
+ VALID_DIRECTIONS = ("c2s", "s2c")
16
+
17
+
18
+ class TLSRecordParser:
19
+ """Reassemble visible TLS record headers across arbitrary TCP reads."""
20
+
21
+ def __init__(self):
22
+ self.buffer = bytearray()
23
+ self.invalid = False
24
+
25
+ def feed(self, payload):
26
+ if self.invalid:
27
+ return []
28
+ self.buffer.extend(payload)
29
+ records = []
30
+ while len(self.buffer) >= TLS_HEADER_BYTES:
31
+ content_type = self.buffer[0]
32
+ major_version = self.buffer[1]
33
+ ciphertext_bytes = int.from_bytes(self.buffer[3:5], "big")
34
+ if (
35
+ content_type not in TLS_CONTENT_TYPES
36
+ or major_version != 3
37
+ or ciphertext_bytes > TLS_MAX_CIPHERTEXT_BYTES
38
+ ):
39
+ self.buffer.clear()
40
+ self.invalid = True
41
+ raise ValueError("stream does not have supported TLS record framing")
42
+ record_bytes = ciphertext_bytes + TLS_HEADER_BYTES
43
+ if len(self.buffer) < record_bytes:
44
+ break
45
+ records.append(
46
+ {"content_type": content_type, "record_bytes": record_bytes}
47
+ )
48
+ del self.buffer[:record_bytes]
49
+ return records
50
+
51
+
52
+ class TraceRecorder:
53
+ """Write metadata-only JSON Lines events to a new file."""
54
+
55
+ def __init__(self, path):
56
+ self.path = Path(path)
57
+ self.file = self.path.open("x", encoding="utf-8")
58
+ self.lock = threading.Lock()
59
+ self.connection_count = 0
60
+
61
+ def emit(self, event, connection, **fields):
62
+ with self.lock:
63
+ row = {
64
+ "event": event,
65
+ "connection": connection,
66
+ "t_ns": time.monotonic_ns(),
67
+ **fields,
68
+ }
69
+ self.file.write(json.dumps(row, separators=(",", ":")) + "\n")
70
+ self.file.flush()
71
+
72
+ def next_connection(self):
73
+ with self.lock:
74
+ self.connection_count += 1
75
+ return self.connection_count
76
+
77
+ def close(self):
78
+ with self.lock:
79
+ if not self.file.closed:
80
+ self.file.close()
81
+
82
+
83
+ class TLSForwarder(socketserver.ThreadingTCPServer):
84
+ allow_reuse_address = True
85
+ daemon_threads = False
86
+ block_on_close = True
87
+
88
+ def __init__(self, target, recorder, listen_host="127.0.0.1", listen_port=0):
89
+ self.target = target
90
+ self.recorder = recorder
91
+ self.stopping = threading.Event()
92
+ super().__init__((listen_host, listen_port), _ForwardHandler)
93
+ self.worker = threading.Thread(target=self.serve_forever, daemon=True)
94
+ self.worker.start()
95
+
96
+ def close(self):
97
+ self.stopping.set()
98
+ self.shutdown()
99
+ self.server_close()
100
+ self.worker.join()
101
+
102
+
103
+ class _ForwardHandler(socketserver.BaseRequestHandler):
104
+ def handle(self):
105
+ server = self.server
106
+ recorder = server.recorder
107
+ connection = recorder.next_connection()
108
+ recorder.emit("connect", connection)
109
+ try:
110
+ with socket.create_connection(server.target, timeout=5) as upstream:
111
+ endpoints = (self.request, upstream)
112
+ for endpoint in endpoints:
113
+ endpoint.settimeout(5)
114
+ endpoint.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
115
+ parsers = {direction: TLSRecordParser() for direction in VALID_DIRECTIONS}
116
+ with selectors.DefaultSelector() as selector:
117
+ selector.register(self.request, selectors.EVENT_READ, (upstream, "c2s"))
118
+ selector.register(upstream, selectors.EVENT_READ, (self.request, "s2c"))
119
+ while not server.stopping.is_set():
120
+ for key, _ in selector.select(timeout=0.1):
121
+ destination, direction = key.data
122
+ payload = key.fileobj.recv(65_536)
123
+ if not payload:
124
+ return
125
+ recorder.emit(
126
+ "chunk", connection, direction=direction, bytes=len(payload)
127
+ )
128
+ try:
129
+ for record in parsers[direction].feed(payload):
130
+ recorder.emit(
131
+ "tls_record", connection, direction=direction, **record
132
+ )
133
+ except ValueError:
134
+ recorder.emit("parse_error", connection, direction=direction)
135
+ destination.sendall(payload)
136
+ except OSError as error:
137
+ if not server.stopping.is_set():
138
+ recorder.emit(
139
+ "connection_error", connection, error=type(error).__name__
140
+ )
141
+ finally:
142
+ recorder.emit("close", connection)
143
+
144
+
145
+ def read_trace(path):
146
+ rows = []
147
+ with Path(path).open(encoding="utf-8") as source:
148
+ for line_number, line in enumerate(source, 1):
149
+ try:
150
+ row = json.loads(line)
151
+ except json.JSONDecodeError as error:
152
+ raise ValueError(f"invalid JSON at line {line_number}") from error
153
+ if not isinstance(row, dict) or "event" not in row:
154
+ raise ValueError(f"invalid trace event at line {line_number}")
155
+ rows.append(row)
156
+ if not rows:
157
+ raise ValueError("trace is empty")
158
+ return rows
159
+
160
+
161
+ def summarize_trace(path, require_complete=True):
162
+ events = read_trace(path)
163
+ failures = [
164
+ row for row in events if row["event"] in ("parse_error", "connection_error")
165
+ ]
166
+ if failures:
167
+ kinds = sorted({row["event"] for row in failures})
168
+ raise ValueError(f"trace contains capture failures: {', '.join(kinds)}")
169
+ chunks = [row for row in events if row["event"] == "chunk"]
170
+ records = [row for row in events if row["event"] == "tls_record"]
171
+ if not chunks or not records:
172
+ raise ValueError("trace has no captured TLS traffic")
173
+ totals = {}
174
+ for direction in VALID_DIRECTIONS:
175
+ chunk_bytes = sum(
176
+ row["bytes"] for row in chunks if row.get("direction") == direction
177
+ )
178
+ record_bytes = sum(
179
+ row["record_bytes"]
180
+ for row in records
181
+ if row.get("direction") == direction
182
+ )
183
+ if require_complete and chunk_bytes != record_bytes:
184
+ raise ValueError(
185
+ f"incomplete {direction} TLS record accounting: "
186
+ f"{chunk_bytes} chunk bytes, {record_bytes} complete record bytes"
187
+ )
188
+ totals[direction] = {
189
+ "chunk_bytes": chunk_bytes,
190
+ "complete_record_bytes": record_bytes,
191
+ }
192
+ application_records = [
193
+ row
194
+ for row in records
195
+ if row.get("direction") == "c2s"
196
+ and row.get("content_type") == TLS_APPLICATION_DATA
197
+ ]
198
+ if not application_records:
199
+ raise ValueError("trace has no client application-data record")
200
+ return {
201
+ "connections": sum(row["event"] == "connect" for row in events),
202
+ "client_bytes": totals["c2s"]["chunk_bytes"],
203
+ "server_bytes": totals["s2c"]["chunk_bytes"],
204
+ "largest_client_application_record": max(
205
+ row["record_bytes"] for row in application_records
206
+ ),
207
+ "complete_tls_records": len(records),
208
+ "complete_accounting": all(
209
+ totals[direction]["chunk_bytes"]
210
+ == totals[direction]["complete_record_bytes"]
211
+ for direction in VALID_DIRECTIONS
212
+ ),
213
+ }
@@ -0,0 +1,147 @@
1
+ """Command-line entry point for the privacy testkit."""
2
+
3
+ import argparse
4
+ import json
5
+ import time
6
+ from pathlib import Path
7
+
8
+ from . import __version__
9
+ from .capture import TLSForwarder, TraceRecorder, summarize_trace
10
+ from .fault_relay import FAULT_MODES, SendTransactionRelay
11
+ from .matching import evaluate_size_matching
12
+
13
+
14
+ def _port(value, *, allow_zero=False):
15
+ port = int(value)
16
+ minimum = 0 if allow_zero else 1
17
+ if not minimum <= port <= 65_535:
18
+ label = "0..65535" if allow_zero else "1..65535"
19
+ raise argparse.ArgumentTypeError(f"port must be in {label}")
20
+ return port
21
+
22
+
23
+ def _listen_port(value):
24
+ return _port(value, allow_zero=True)
25
+
26
+
27
+ def _write_new(path, value):
28
+ with Path(path).open("x", encoding="utf-8") as destination:
29
+ json.dump(value, destination, indent=2)
30
+ destination.write("\n")
31
+
32
+
33
+ def _capture(args):
34
+ recorder = TraceRecorder(args.output)
35
+ forwarder = TLSForwarder(
36
+ (args.target_host, args.target_port),
37
+ recorder,
38
+ args.listen_host,
39
+ args.listen_port,
40
+ )
41
+ print(
42
+ json.dumps(
43
+ {
44
+ "ready": True,
45
+ "listen_host": forwarder.server_address[0],
46
+ "listen_port": forwarder.server_address[1],
47
+ "trace": str(args.output),
48
+ }
49
+ ),
50
+ flush=True,
51
+ )
52
+ try:
53
+ while True:
54
+ time.sleep(0.2)
55
+ except KeyboardInterrupt:
56
+ pass
57
+ finally:
58
+ forwarder.close()
59
+ recorder.close()
60
+
61
+
62
+ def _summarize(args):
63
+ print(json.dumps(summarize_trace(args.trace, not args.allow_partial), indent=2))
64
+
65
+
66
+ def _match(args):
67
+ samples = json.loads(args.samples.read_text(encoding="utf-8"))
68
+ print(
69
+ json.dumps(
70
+ evaluate_size_matching(samples, training_batch=args.training_batch), indent=2
71
+ )
72
+ )
73
+
74
+
75
+ def _fault_relay(args):
76
+ if args.events.exists():
77
+ raise FileExistsError(f"event output already exists: {args.events}")
78
+ relay = SendTransactionRelay(
79
+ args.upstream,
80
+ args.mode,
81
+ upstream_ca=args.upstream_ca,
82
+ listen_host=args.listen_host,
83
+ listen_port=args.listen_port,
84
+ certificate=args.certificate,
85
+ private_key=args.private_key,
86
+ )
87
+ print(
88
+ json.dumps({"ready": True, "endpoint": relay.endpoint, "mode": args.mode}),
89
+ flush=True,
90
+ )
91
+ try:
92
+ while True:
93
+ time.sleep(0.2)
94
+ except KeyboardInterrupt:
95
+ pass
96
+ finally:
97
+ relay.close()
98
+ _write_new(args.events, relay.events)
99
+
100
+
101
+ def parser():
102
+ root = argparse.ArgumentParser(
103
+ prog="wpt", description="Adversarial network tests for Zcash wallets"
104
+ )
105
+ root.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
106
+ commands = root.add_subparsers(dest="command", required=True)
107
+
108
+ capture = commands.add_parser("capture", help="record passive TLS metadata")
109
+ capture.add_argument("--target-host", required=True)
110
+ capture.add_argument("--target-port", required=True, type=_port)
111
+ capture.add_argument("--listen-host", default="127.0.0.1")
112
+ capture.add_argument("--listen-port", default=0, type=_listen_port)
113
+ capture.add_argument("--output", required=True, type=Path)
114
+ capture.set_defaults(handler=_capture)
115
+
116
+ summarize = commands.add_parser("summarize", help="validate and summarize a trace")
117
+ summarize.add_argument("trace", type=Path)
118
+ summarize.add_argument("--allow-partial", action="store_true")
119
+ summarize.set_defaults(handler=_summarize)
120
+
121
+ matching = commands.add_parser("match", help="evaluate size-only candidate matching")
122
+ matching.add_argument("samples", type=Path)
123
+ matching.add_argument("--training-batch", default=0, type=int)
124
+ matching.set_defaults(handler=_match)
125
+
126
+ relay = commands.add_parser(
127
+ "fault-relay", help="inject SendTransaction delivery uncertainty"
128
+ )
129
+ relay.add_argument("--upstream", required=True, help="host:port")
130
+ relay.add_argument("--mode", required=True, choices=sorted(FAULT_MODES))
131
+ relay.add_argument("--upstream-ca", type=Path)
132
+ relay.add_argument("--listen-host", default="127.0.0.1")
133
+ relay.add_argument("--listen-port", default=0, type=_listen_port)
134
+ relay.add_argument("--certificate", type=Path)
135
+ relay.add_argument("--private-key", type=Path)
136
+ relay.add_argument("--events", required=True, type=Path)
137
+ relay.set_defaults(handler=_fault_relay)
138
+ return root
139
+
140
+
141
+ def main():
142
+ args = parser().parse_args()
143
+ args.handler(args)
144
+
145
+
146
+ if __name__ == "__main__":
147
+ main()
@@ -0,0 +1,155 @@
1
+ """A protocol-aware relay for uncertain SendTransaction delivery tests."""
2
+
3
+ import concurrent.futures
4
+ import hashlib
5
+ import threading
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import grpc
10
+
11
+ from .protocol import RawTransaction, SEND_TRANSACTION, SendResponse
12
+
13
+ FAULT_MODES = frozenset(("before-once", "after-once", "after-all"))
14
+ LIGHTWALLET_PROTOCOL_VERSION = "v0.5.0"
15
+ SERVER_STREAMING_METHODS = frozenset(
16
+ (
17
+ "GetBlockRange",
18
+ "GetBlockRangeNullifiers",
19
+ "GetTaddressTxids",
20
+ "GetTaddressTransactions",
21
+ "GetMempoolTx",
22
+ "GetMempoolStream",
23
+ "GetSubtreeRoots",
24
+ "GetAddressUtxosStream",
25
+ )
26
+ )
27
+ CLIENT_STREAMING_METHOD = "GetTaddressBalanceStream"
28
+
29
+
30
+ class SendTransactionRelay(grpc.GenericRpcHandler):
31
+ """Forward the service and fail acknowledgements at declared boundaries."""
32
+
33
+ def __init__(
34
+ self,
35
+ upstream,
36
+ mode,
37
+ *,
38
+ upstream_ca=None,
39
+ listen_host="127.0.0.1",
40
+ listen_port=0,
41
+ certificate=None,
42
+ private_key=None,
43
+ ready_timeout=15,
44
+ ):
45
+ if mode not in FAULT_MODES:
46
+ raise ValueError(f"unknown fault mode: {mode}")
47
+ if (certificate is None) != (private_key is None):
48
+ raise ValueError("certificate and private key must be supplied together")
49
+ self.mode = mode
50
+ self.events = []
51
+ self.lock = threading.Lock()
52
+ if upstream_ca is None:
53
+ self.channel = grpc.insecure_channel(upstream)
54
+ else:
55
+ roots = Path(upstream_ca).read_bytes()
56
+ self.channel = grpc.secure_channel(
57
+ upstream, grpc.ssl_channel_credentials(root_certificates=roots)
58
+ )
59
+ grpc.channel_ready_future(self.channel).result(timeout=ready_timeout)
60
+ self.server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=16))
61
+ self.server.add_generic_rpc_handlers((self,))
62
+ address = f"{listen_host}:{listen_port}"
63
+ if certificate is None:
64
+ self.port = self.server.add_insecure_port(address)
65
+ self.scheme = "http"
66
+ else:
67
+ credentials = grpc.ssl_server_credentials(
68
+ ((Path(private_key).read_bytes(), Path(certificate).read_bytes()),)
69
+ )
70
+ self.port = self.server.add_secure_port(address, credentials)
71
+ self.scheme = "https"
72
+ if not self.port:
73
+ self.channel.close()
74
+ raise RuntimeError(f"could not bind relay to {address}")
75
+ self.server.start()
76
+
77
+ @property
78
+ def endpoint(self):
79
+ return f"{self.scheme}://127.0.0.1:{self.port}"
80
+
81
+ def service(self, details):
82
+ method = details.method
83
+ name = method.rsplit("/", 1)[-1]
84
+ if name in SERVER_STREAMING_METHODS:
85
+ return grpc.unary_stream_rpc_method_handler(
86
+ lambda request, context: self._forward_stream(method, request, context)
87
+ )
88
+ if name == CLIENT_STREAMING_METHOD:
89
+ return grpc.stream_unary_rpc_method_handler(
90
+ lambda requests, context: self._forward_client_stream(
91
+ method, requests, context
92
+ )
93
+ )
94
+ return grpc.unary_unary_rpc_method_handler(
95
+ lambda request, context: self._forward_unary(method, request, context)
96
+ )
97
+
98
+ def _forward_stream(self, method, request, context):
99
+ try:
100
+ yield from self.channel.unary_stream(method)(request, timeout=120)
101
+ except grpc.RpcError as error:
102
+ context.abort(error.code(), error.details())
103
+
104
+ def _forward_client_stream(self, method, requests, context):
105
+ try:
106
+ return self.channel.stream_unary(method)(requests, timeout=120)
107
+ except grpc.RpcError as error:
108
+ context.abort(error.code(), error.details())
109
+
110
+ def _forward_unary(self, method, request, context):
111
+ event = None
112
+ if method == SEND_TRANSACTION:
113
+ transaction = RawTransaction.FromString(request)
114
+ with self.lock:
115
+ event = {
116
+ "attempt": len(self.events) + 1,
117
+ "time_ns": time.monotonic_ns(),
118
+ "transaction_sha256": hashlib.sha256(transaction.data).hexdigest(),
119
+ "transaction_bytes": len(transaction.data),
120
+ "height": transaction.height,
121
+ }
122
+ self.events.append(event)
123
+ if self.mode == "before-once" and event["attempt"] == 1:
124
+ event["forwarded"] = False
125
+ context.abort(
126
+ grpc.StatusCode.UNAVAILABLE,
127
+ "privacy-testkit: connection lost before upstream submission",
128
+ )
129
+ event["forwarded"] = True
130
+ try:
131
+ response = self.channel.unary_unary(method)(request, timeout=120)
132
+ except grpc.RpcError as error:
133
+ if event is not None:
134
+ event["upstream_grpc_error"] = error.code().name
135
+ context.abort(error.code(), error.details())
136
+ if event is not None:
137
+ decoded = SendResponse.FromString(response)
138
+ event["upstream_response"] = {
139
+ "error_code": decoded.errorCode,
140
+ "message": decoded.errorMessage,
141
+ }
142
+ lose_response = self.mode == "after-all" or (
143
+ self.mode == "after-once" and event["attempt"] == 1
144
+ )
145
+ event["response_lost"] = lose_response
146
+ if lose_response:
147
+ context.abort(
148
+ grpc.StatusCode.UNAVAILABLE,
149
+ "privacy-testkit: response lost after upstream submission",
150
+ )
151
+ return response
152
+
153
+ def close(self, grace=0):
154
+ self.server.stop(grace).wait()
155
+ self.channel.close()
@@ -0,0 +1,84 @@
1
+ """Conservative size-only matching with fractional credit for ties."""
2
+
3
+ import statistics
4
+
5
+ REQUIRED_FIELDS = frozenset(("id", "batch", "observed_bytes", "transaction_bytes"))
6
+
7
+
8
+ def evaluate_size_matching(samples, training_batch=0):
9
+ if not isinstance(samples, list) or not samples:
10
+ raise ValueError("samples must be a non-empty JSON array")
11
+ identifiers = set()
12
+ for index, sample in enumerate(samples):
13
+ if not isinstance(sample, dict):
14
+ raise ValueError(f"sample {index} is not an object")
15
+ missing = REQUIRED_FIELDS.difference(sample)
16
+ if missing:
17
+ raise ValueError(f"sample {index} is missing: {', '.join(sorted(missing))}")
18
+ if not isinstance(sample["id"], str) or not sample["id"]:
19
+ raise ValueError(f"sample {index} has an invalid id")
20
+ if sample["id"] in identifiers:
21
+ raise ValueError(f"duplicate sample id: {sample['id']}")
22
+ identifiers.add(sample["id"])
23
+ if type(sample["batch"]) is not int or sample["batch"] < 0:
24
+ raise ValueError(f"sample {index} has an invalid batch")
25
+ if not all(
26
+ type(sample[field]) is int and sample[field] >= 0
27
+ for field in ("observed_bytes", "transaction_bytes")
28
+ ):
29
+ raise ValueError(f"sample {index} has invalid byte counts")
30
+ training = [sample for sample in samples if sample["batch"] == training_batch]
31
+ if not training:
32
+ raise ValueError("training batch is absent")
33
+ held_out = [sample for sample in samples if sample["batch"] != training_batch]
34
+ if not held_out:
35
+ raise ValueError("held-out samples are absent")
36
+ offset = statistics.median(
37
+ sample["observed_bytes"] - sample["transaction_bytes"]
38
+ for sample in training
39
+ )
40
+ scores = []
41
+ for sample in held_out:
42
+ candidates = [row for row in samples if row["batch"] == sample["batch"]]
43
+ if len(candidates) < 2:
44
+ raise ValueError(f"batch {sample['batch']} has fewer than two candidates")
45
+ distances = [
46
+ abs(sample["observed_bytes"] - (candidate["transaction_bytes"] + offset))
47
+ for candidate in candidates
48
+ ]
49
+ best = min(distances)
50
+ tied = [
51
+ candidate
52
+ for candidate, distance in zip(candidates, distances)
53
+ if distance == best
54
+ ]
55
+ credit = 1 / len(tied) if sample["id"] in {row["id"] for row in tied} else 0
56
+ scores.append(
57
+ {
58
+ "id": sample["id"],
59
+ "batch": sample["batch"],
60
+ "credit": credit,
61
+ "tied_candidates": len(tied),
62
+ "absolute_size_error": abs(
63
+ sample["observed_bytes"]
64
+ - sample["transaction_bytes"]
65
+ - offset
66
+ ),
67
+ }
68
+ )
69
+ batch_sizes = {
70
+ sample["batch"]: sum(row["batch"] == sample["batch"] for row in samples)
71
+ for sample in held_out
72
+ }
73
+ random_reference = statistics.mean(
74
+ 1 / batch_sizes[sample["batch"]] for sample in held_out
75
+ )
76
+ return {
77
+ "training_batch": training_batch,
78
+ "training_samples": len(training),
79
+ "held_out_samples": len(held_out),
80
+ "learned_offset_bytes": offset,
81
+ "fractional_top1": statistics.mean(score["credit"] for score in scores),
82
+ "random_reference": random_reference,
83
+ "scores": scores,
84
+ }
@@ -0,0 +1,33 @@
1
+ """The small part of the lightwalletd protocol needed by the fault relay."""
2
+
3
+ from google.protobuf import descriptor_pb2, descriptor_pool, message_factory
4
+
5
+ SERVICE = "cash.z.wallet.sdk.rpc.CompactTxStreamer"
6
+ SEND_TRANSACTION = f"/{SERVICE}/SendTransaction"
7
+
8
+
9
+ def _message_classes():
10
+ schema = descriptor_pb2.FileDescriptorProto(
11
+ name="wallet_privacy_testkit.proto",
12
+ package="cash.z.wallet.sdk.rpc",
13
+ syntax="proto3",
14
+ )
15
+ definitions = (
16
+ ("RawTransaction", (("data", 1, 12), ("height", 2, 4))),
17
+ ("SendResponse", (("errorCode", 1, 5), ("errorMessage", 2, 9))),
18
+ )
19
+ for name, fields in definitions:
20
+ message = schema.message_type.add(name=name)
21
+ for field_name, number, field_type in fields:
22
+ message.field.add(name=field_name, number=number, type=field_type, label=1)
23
+ pool = descriptor_pool.DescriptorPool()
24
+ pool.Add(schema)
25
+ return tuple(
26
+ message_factory.GetMessageClass(
27
+ pool.FindMessageTypeByName(f"cash.z.wallet.sdk.rpc.{name}")
28
+ )
29
+ for name in ("RawTransaction", "SendResponse")
30
+ )
31
+
32
+
33
+ RawTransaction, SendResponse = _message_classes()
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: wallet-privacy-testkit
3
+ Version: 0.1.0
4
+ Summary: Adversarial network privacy and transaction-delivery tests for Zcash wallets
5
+ Author: Wallet Privacy Testkit contributors
6
+ License-Expression: MIT OR Apache-2.0
7
+ Project-URL: Homepage, https://github.com/ztsalexey/wallet-privacy-testkit
8
+ Project-URL: Repository, https://github.com/ztsalexey/wallet-privacy-testkit
9
+ Project-URL: Issues, https://github.com/ztsalexey/wallet-privacy-testkit/issues
10
+ Project-URL: Changelog, https://github.com/ztsalexey/wallet-privacy-testkit/blob/main/CHANGELOG.md
11
+ Keywords: zcash,wallet,privacy,testing,grpc,tls
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Testing
20
+ Classifier: Topic :: Security
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE-APACHE
24
+ License-File: LICENSE-MIT
25
+ Requires-Dist: grpcio<2,>=1.70
26
+ Requires-Dist: protobuf<8,>=5
27
+ Dynamic: license-file
28
+
29
+ # Wallet Privacy Testkit for Zcash
30
+
31
+ Wallet Privacy Testkit is an adversarial test layer for Zcash wallet-to-indexer traffic. It records the lengths and timing visible outside TLS, injects uncertainty around `SendTransaction`, and evaluates size-only transaction matching without awarding full credit to ties.
32
+
33
+ This is an independent project maintained at [ztsalexey/wallet-privacy-testkit](https://github.com/ztsalexey/wallet-privacy-testkit). It is not affiliated with or endorsed by the Zcash Foundation, Electric Coin Company, or any wallet or indexer maintainer.
34
+
35
+ Version 0.1.0 is a research preview. It supplies reusable test components and a verified Zingolib case study. It does not certify a wallet, assign a privacy score, inspect mainnet funds, or replace a wallet's existing integration tests.
36
+
37
+ ## Why this exists
38
+
39
+ A shielded transaction can hide its participants and value on-chain while its network behavior still leaks information. A second failure mode appears when a node accepts a payment but the wallet loses the response. The wallet must distinguish rejection from an unknown outcome and recover without creating another payment.
40
+
41
+ Existing projects already provision Zcash regtest networks and test wallet behavior. This testkit attaches to those environments and contributes two narrower capabilities:
42
+
43
+ - passive ciphertext metadata capture, without TLS keys or payload logging;
44
+ - protocol-aware failure injection before or after transaction submission.
45
+
46
+ The [methodology](docs/METHODOLOGY.md) defines what each result means. The [threat model](docs/THREAT_MODEL.md) states what it does not establish.
47
+
48
+ ## Install from a source checkout
49
+
50
+ Python 3.11 or newer is required.
51
+
52
+ ```sh
53
+ python3 -m venv .venv
54
+ source .venv/bin/activate
55
+ .venv/bin/python -m pip install -r requirements-dev.txt
56
+ .venv/bin/python -m pip install --no-deps -e .
57
+ .venv/bin/python -m unittest discover -s tests -v
58
+ ```
59
+
60
+ The release was developed with Python 3.12.9, gRPC 1.83.1, and protobuf 7.36.1. CI tests the pinned development environment on Python 3.11–3.13 on Linux and macOS. The broader runtime dependency ranges are not exhaustively tested.
61
+
62
+ Packaged wheels and source archives are available from [GitHub Releases](https://github.com/ztsalexey/wallet-privacy-testkit/releases). After activating a virtual environment, install a downloaded wheel with `python -m pip install ./wallet_privacy_testkit-0.1.0-py3-none-any.whl`.
63
+
64
+ ## Passive TLS metadata capture
65
+
66
+ Point a wallet at the printed local port while the target indexer remains at `localhost:9067`:
67
+
68
+ ```sh
69
+ wpt capture \
70
+ --target-host localhost \
71
+ --target-port 9067 \
72
+ --listen-port 7443 \
73
+ --output trace.jsonl
74
+ ```
75
+
76
+ Stop the capture with Ctrl-C, then validate that every captured TCP byte belongs to a complete TLS record:
77
+
78
+ ```sh
79
+ wpt summarize trace.jsonl
80
+ ```
81
+
82
+ The forwarder copies bytes unchanged. Its trace contains connection numbers, monotonic timestamps, directions, byte counts, TLS content types, and TLS record lengths. It does not terminate TLS, store addresses, or record packet contents. A process boundary supplied by the test operator is still side information and must be disclosed in a report.
83
+
84
+ ## Transaction delivery faults
85
+
86
+ The semantic relay terminates a test TLS connection and forwards the real gRPC service. It understands only enough of the lightwalletd protocol to identify and hash `RawTransaction.data`; it never writes signed transaction bytes. All other known RPCs are forwarded as opaque bytes using their required streaming cardinality.
87
+
88
+ The forwarding table was checked against canonical `lightwallet-protocol` v0.5.0. A later protocol version that adds a streaming RPC requires a testkit update before that RPC can pass through correctly.
89
+
90
+ For a TLS upstream and TLS-facing wallet:
91
+
92
+ ```sh
93
+ wpt fault-relay \
94
+ --upstream localhost:9067 \
95
+ --upstream-ca test-ca.pem \
96
+ --certificate localhost.pem \
97
+ --private-key localhost.key \
98
+ --mode after-once \
99
+ --events events.json
100
+ ```
101
+
102
+ The supported modes are:
103
+
104
+ | Mode | Behavior |
105
+ | --- | --- |
106
+ | `before-once` | Fail the first submission without forwarding it, then forward normally |
107
+ | `after-once` | Forward the first submission and discard its response, then forward normally |
108
+ | `after-all` | Forward every submission and discard every response |
109
+
110
+ Use the relay only with disposable wallets and isolated regtest funds. The tool deliberately changes transaction-delivery behavior. The test operator remains responsible for checking the node's mempool or chain and the wallet's eventual state.
111
+
112
+ An insecure local upstream or client can omit the certificate options. The relay binds to `127.0.0.1` by default. Supplying only one of `--certificate` and `--private-key` is rejected.
113
+
114
+ The printed endpoint uses `127.0.0.1`. When the wallet-facing side uses TLS, the server certificate must therefore contain the IP address `127.0.0.1` in its Subject Alternative Name. The upstream CA file is required for a TLS upstream; omitting it selects an insecure upstream channel.
115
+
116
+ ## Size-only matching
117
+
118
+ `wpt match samples.json` accepts a JSON array. Each row must contain a unique `id`, a `batch`, `observed_bytes`, and the corresponding public `transaction_bytes`. Batch 0 calibrates a single median byte offset by default. Every other observation is compared only with candidates in its own batch.
119
+
120
+ ```json
121
+ [
122
+ {"id":"train-a","batch":0,"observed_bytes":9207,"transaction_bytes":9165},
123
+ {"id":"train-b","batch":0,"observed_bytes":12363,"transaction_bytes":12321},
124
+ {"id":"test-a","batch":1,"observed_bytes":9207,"transaction_bytes":9165},
125
+ {"id":"test-b","batch":1,"observed_bytes":12363,"transaction_bytes":12321}
126
+ ]
127
+ ```
128
+
129
+ Nearest candidates share credit when their distance ties. A batch with fewer than two candidates is rejected because singleton identification says nothing about the matcher. The tool reports a random reference computed from each held-out batch's candidate count.
130
+
131
+ ## Verified case study
132
+
133
+ The included [Zingolib v5 regtest report](evidence/zingolib-v5-regtest/REPORT.md) records 18 newly constructed shielded payments and three delivery-fault transactions in the complete run. The wallet reported a payment as failed after its acknowledgement was lost even though Zebra had accepted it. Mining and synchronization corrected the status to confirmed. Current Zingolib development code already includes related duplicate and delivery-check handling, so this is regression evidence rather than a claim of an unresolved current bug.
134
+
135
+ The case study also found that encrypted lengths distinguished 1-, 2-, and 4-recipient transaction structures in a favorable observer model. Equal-structure payments tied at chance. The result does not estimate deanonymization in normal wallet traffic.
136
+
137
+ ## Project status
138
+
139
+ The release boundary is intentionally small. Z3, Zcash Integration Tests, Regchest, and wallet-specific suites already cover network provisioning and broad functional behavior. The testkit is designed to complement them. See the [competitive and overlap review](docs/COMPETITIVE_LANDSCAPE.md) and [release checklist](docs/RELEASE_CHECKLIST.md).
140
+
141
+ Upstream contributions should begin with a maintainer-acknowledged issue and a narrowly scoped regression, following the target repository's contribution policy.
142
+
143
+ ## License
144
+
145
+ Licensed under either the MIT License or Apache License 2.0, at your option.
@@ -0,0 +1,14 @@
1
+ wallet_privacy_testkit/__init__.py,sha256=XZ6wQk-Tc5hBm1soZH9U0w7mOejAdY55QR1MewqrPmE,81
2
+ wallet_privacy_testkit/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
3
+ wallet_privacy_testkit/capture.py,sha256=hT_PVZrDEIsluTWKCJi-EkE3tirI5sisW18nGZjl-As,7949
4
+ wallet_privacy_testkit/cli.py,sha256=VU1wCQuHSpiDZYSQso0vUmoos2Y6mFRHLY8s-TCM-NM,4565
5
+ wallet_privacy_testkit/fault_relay.py,sha256=0zYbKoFzsn3ZeluaXD3fNZHGDhjz_dltLlDPp15L0eY,5811
6
+ wallet_privacy_testkit/matching.py,sha256=wI6dJFcQXGaDgaS-AcRAbafmKX9HIbNDbR8XFhHwQ6k,3442
7
+ wallet_privacy_testkit/protocol.py,sha256=4U1BNq_-dw84_xCNCofDlrMN392_cgg0VUlJDTPz_HE,1164
8
+ wallet_privacy_testkit-0.1.0.dist-info/licenses/LICENSE-APACHE,sha256=uCShXdhKlwJs-I5TyaeSX3_A44xesj4tEb9NNjbFReQ,11365
9
+ wallet_privacy_testkit-0.1.0.dist-info/licenses/LICENSE-MIT,sha256=z5rJO6uPdxjtnRx9gWLdp8PgY-Uw4Bpp7bLubrif5C8,1092
10
+ wallet_privacy_testkit-0.1.0.dist-info/METADATA,sha256=s8NDpnf7byMo_-M3iOeGlSjunaIH3g7ZRkqv9UHlKdA,8574
11
+ wallet_privacy_testkit-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
12
+ wallet_privacy_testkit-0.1.0.dist-info/entry_points.txt,sha256=1hrkWScLyk1iycXspmMrKLFG2u9MBhsYFppMsej8b2o,56
13
+ wallet_privacy_testkit-0.1.0.dist-info/top_level.txt,sha256=PCqW9TEZdvkrjJbCaCKWiRal6cnTaW2ADy2HC5zxfHU,23
14
+ wallet_privacy_testkit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ wpt = wallet_privacy_testkit.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Wallet Privacy Testkit contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wallet Privacy Testkit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ wallet_privacy_testkit