verdock 0.3.1__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.
verdock/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """verdock: policy, approvals, invariants, outcomes, signed receipts and an egress gateway.
2
+
3
+ Import the submodules directly, for example::
4
+
5
+ from verdock.policy import load_policy, decide
6
+ from verdock.receipts import ReceiptLog, verify_log
7
+ """
8
+
9
+ from .errors import PolicyError, Refused
10
+
11
+ __version__ = "0.3.1"
12
+
13
+ from .guard import guard
14
+
15
+ __all__ = ["__version__", "PolicyError", "Refused", "guard"]
verdock/__main__.py ADDED
@@ -0,0 +1,173 @@
1
+ """Command line.
2
+
3
+ python -m verdock verify <file> --public-key <hex>
4
+ Prints one line per receipt and a summary. Exit status 0 when every line
5
+ passes, 1 when any line fails, 2 for usage or file errors. No network.
6
+
7
+ python -m verdock egress --policy <file> --listen <host:port> --receipts <file> --seed <file>
8
+ Runs the egress gateway for the policy's egress.allow_hosts and prints its
9
+ receipt public key. Creates the seed file if it does not exist.
10
+
11
+ python -m verdock demo [--scene all|payout|credit|data|unknown|exchange|fleet|approval|stop|credits] [--offline] [--currency usd|inr] [--out DIR]
12
+ Runs the demonstration. Without --scene it prints the double refund text.
13
+ --currency picks how amounts are shown and the currency code used (default usd).
14
+
15
+ python -m verdock keys [create NAME], exchange ..., exceptions, disclose
16
+ Per approver keys and the exchange, exceptions and disclosure commands.
17
+
18
+ python -m verdock licence [issue --dev ...], usage [export|verify]
19
+ The signed licence file and the offline usage meter. No network.
20
+
21
+ python -m verdock diag --redact
22
+ Hashes and counts of the policy, key and receipts. Nothing else is printed.
23
+ """
24
+
25
+ import argparse
26
+ import sys
27
+ import uuid
28
+ from pathlib import Path
29
+
30
+ from . import __version__, credits_cli, diag, exchange_cli
31
+ from .demo import CURRENCY_CHOICES, SCENE_CHOICES
32
+ from .receipts import verify_log
33
+
34
+ DEFAULT_POLICY = '''version: 1
35
+ operations:
36
+ refund:
37
+ level: Execute within Limits
38
+ max_amount_minor: 5000
39
+ approval_above_minor: 2000
40
+ currency: USD
41
+ retry: never
42
+ caps:
43
+ per_customer_per_day_minor: 10000
44
+ team_per_day_minor: 50000
45
+ egress:
46
+ allow_hosts: []
47
+ '''
48
+
49
+
50
+ def _init(args):
51
+ from .local import LocalState
52
+ path = Path("verdock.yaml")
53
+ with path.open("x", encoding="utf-8") as handle:
54
+ handle.write(DEFAULT_POLICY)
55
+ LocalState()
56
+ print("Created verdock.yaml and .verdock/. Keep .verdock/signing.seed private.")
57
+ return 0
58
+
59
+
60
+ def _check(args):
61
+ from .local import LocalState
62
+ from .policy import load_policy, decide, policy_hash
63
+ policy = load_policy("verdock.yaml")
64
+ decision = decide(policy, args.operation, args.amount, args.currency)
65
+ label = "blocked" if not decision.allowed else "needs approval" if decision.needs_approval else "allowed"
66
+ state = LocalState()
67
+ state.receipt(str(uuid.uuid4()), "policy.check", {
68
+ "operation": args.operation, "amount_minor": args.amount,
69
+ "currency": args.currency, "counterparty": args.counterparty},
70
+ decision.allowed and not decision.needs_approval,
71
+ {"decision": label, "reason": decision.reason, "policy_hash": policy_hash(policy)})
72
+ print(label + ": " + decision.reason)
73
+ print("Receipt: .verdock/receipts.ndjson. This check reserves no money and executes no action.")
74
+ return 0
75
+
76
+
77
+ def _verify(args):
78
+ try:
79
+ report = verify_log(args.file, args.public_key, args.manifest_root)
80
+ except OSError as exc:
81
+ print("error: cannot read %s: %s" % (args.file, exc.strerror or exc), file=sys.stderr)
82
+ return 2
83
+ except ValueError as exc:
84
+ print("error: %s" % exc, file=sys.stderr)
85
+ return 2
86
+ by_line = {}
87
+ for failure in report["failures"]:
88
+ by_line.setdefault(failure["line"], []).append(failure["reason"])
89
+ for number in range(1, report["count"] + 1):
90
+ reasons = by_line.get(number)
91
+ if reasons:
92
+ print("line %d: FAIL %s" % (number, "; ".join(reasons)))
93
+ else:
94
+ print("line %d: ok" % number)
95
+ if report["ok"]:
96
+ print("verified: %d lines, chain intact, signed by the trusted key" % report["count"])
97
+ return 0
98
+ print("failed: %d problems in %d lines" % (len(report["failures"]), report["count"]))
99
+ return 1
100
+
101
+
102
+ def main(argv=None):
103
+ parser = argparse.ArgumentParser(prog="verdock", epilog=(
104
+ "Feedback: https://getverdock.com/feedback/?source=pip\n"
105
+ "Issues: https://github.com/Sriharsan/verdock/issues"))
106
+ parser.add_argument("--version", action="version", version=__version__)
107
+ commands = parser.add_subparsers(dest="command", required=True)
108
+ commands.add_parser("init", help="create a local policy and signing key")
109
+ check = commands.add_parser("check", help="check policy and write a receipt; no action is executed")
110
+ check.add_argument("operation")
111
+ check.add_argument("amount", type=int, help="integer amount in minor units")
112
+ check.add_argument("--currency", required=True)
113
+ check.add_argument("--counterparty", required=True)
114
+ demo = commands.add_parser("demo", help="run the demonstration (default: the double refund and reconcile)")
115
+ demo.add_argument("--scene", choices=SCENE_CHOICES,
116
+ help="run one scene or all of them: payout, credit, data, unknown, exchange, fleet, approval, stop, credits")
117
+ demo.add_argument("--offline", action="store_true",
118
+ help="run every scene with all sockets blocked and report 0 network attempts")
119
+ demo.add_argument("--currency", type=str.lower, choices=CURRENCY_CHOICES, default="usd",
120
+ help="currency for amounts in the demo: usd shows $4,800, inr shows the rupee sign with Indian grouping (default usd)")
121
+ demo.add_argument("--out", help="keep receipts and trust.json for the run in this folder")
122
+ keys = commands.add_parser("keys", help="show your local public key, or create a named key")
123
+ keys.add_argument("action", nargs="?", choices=["create"], help="create NAME makes keys/NAME.seed (mode 0600) and NAME.pub")
124
+ keys.add_argument("name", nargs="?", help="key name for create")
125
+ keys.add_argument("--dir", default=".verdock", help="state folder for create (default .verdock)")
126
+ exchange_cli.add_parsers(commands)
127
+ credits_cli.add_parsers(commands)
128
+ diag.add_parsers(commands)
129
+ verify = commands.add_parser("verify", help="verify a receipt log")
130
+ verify.add_argument("file", help="NDJSON receipt log")
131
+ verify.add_argument("--public-key", required=True, help="trusted Ed25519 public key, 64 hex characters")
132
+ verify.add_argument("--manifest-root", help="64 hex root key that must have signed the first manifest of any delegation chain")
133
+ args = parser.parse_args(argv)
134
+ try:
135
+ if args.command == "init":
136
+ return _init(args)
137
+ if args.command == "check":
138
+ return _check(args)
139
+ if args.command == "keys":
140
+ if args.action == "create":
141
+ if not args.name:
142
+ parser.error("keys create needs a NAME")
143
+ args.handler = exchange_cli.cmd_keys_create
144
+ return exchange_cli.dispatch(args)
145
+ if args.action or args.name:
146
+ parser.error("usage: verdock keys [create NAME]")
147
+ from .local import LocalState
148
+ print(LocalState().public_key)
149
+ return 0
150
+ if args.command == "demo":
151
+ if hasattr(sys.stdout, "reconfigure"):
152
+ sys.stdout.reconfigure(encoding="utf-8")
153
+ if args.out and not (args.scene or args.offline):
154
+ parser.error("--out needs --scene or --offline")
155
+ if args.scene is None and not args.offline:
156
+ from .demo import run
157
+ run(args.currency)
158
+ return 0
159
+ from .demo import run_scenes
160
+ run_scenes(args.scene or "all", out=args.out, offline=args.offline, currency=args.currency)
161
+ return 0
162
+ if hasattr(args, "handler"):
163
+ return exchange_cli.dispatch(args)
164
+ if args.command == "verify":
165
+ return _verify(args)
166
+ except (OSError, ValueError) as exc:
167
+ print("error: " + str(exc), file=sys.stderr)
168
+ return 2
169
+ return 2
170
+
171
+
172
+ if __name__ == "__main__":
173
+ sys.exit(main())
verdock/_db.py ADDED
@@ -0,0 +1,40 @@
1
+ """Small SQLite helpers that the stores in this package use."""
2
+
3
+ import contextlib
4
+ import sqlite3
5
+
6
+
7
+ def connect(path):
8
+ """Open a connection in autocommit mode so transactions are explicit."""
9
+ conn = sqlite3.connect(str(path), timeout=30.0, isolation_level=None)
10
+ conn.row_factory = sqlite3.Row
11
+ conn.execute("PRAGMA busy_timeout = 30000")
12
+ return conn
13
+
14
+
15
+ @contextlib.contextmanager
16
+ def immediate(path):
17
+ """Yield a connection inside BEGIN IMMEDIATE; commit or roll back on exit.
18
+
19
+ BEGIN IMMEDIATE takes the database write lock at the start, so a read
20
+ followed by a write inside the block cannot interleave with another
21
+ writer, in this process or another one.
22
+ """
23
+ conn = connect(path)
24
+ try:
25
+ conn.execute("BEGIN IMMEDIATE")
26
+ try:
27
+ yield conn
28
+ except BaseException:
29
+ conn.execute("ROLLBACK")
30
+ raise
31
+ else:
32
+ conn.execute("COMMIT")
33
+ finally:
34
+ conn.close()
35
+
36
+
37
+ def init_schema(path, statements):
38
+ with immediate(path) as conn:
39
+ for statement in statements:
40
+ conn.execute(statement)
@@ -0,0 +1,12 @@
1
+ """Test mode provider adapters for Stripe and Razorpay.
2
+
3
+ Import the adapter you need::
4
+
5
+ from verdock.adapters.stripe import StripeAdapter
6
+ from verdock.adapters.razorpay import RazorpayAdapter
7
+ from verdock.adapters import load_env
8
+ """
9
+
10
+ from ._http import ProviderError, Result, load_env
11
+
12
+ __all__ = ["ProviderError", "Result", "load_env"]