atcn 1.3.0__tar.gz

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.
atcn-1.3.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
atcn-1.3.0/PKG-INFO ADDED
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.4
2
+ Name: atcn
3
+ Version: 1.3.0
4
+ Summary: Python SDK for the Agent Transaction Closure Network: canonical JSON, Ed25519 event signing, webhook verification, API client, Agent Work Subledger
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/fadnisnikhil/atcn
7
+ Project-URL: Source, https://github.com/fadnisnikhil/atcn/tree/main/packages/sdk-python
8
+ Project-URL: Issues, https://github.com/fadnisnikhil/atcn/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: cryptography>=42
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest>=8; extra == "test"
15
+ Dynamic: license-file
16
+
17
+ # atcn (Python SDK)
18
+
19
+ The ATCN Python SDK. It covers:
20
+
21
+ - **Signing.** RFC 8785 canonical JSON, Ed25519 signing, and obligation event signing with `EventSigner`.
22
+ - **Webhooks.** `verify_webhook` and `sign_webhook`.
23
+ - **API clients.** `AtcnClient` is for the clearing network. `SubledgerClient` and `CaptureQueue` record tasks, delegations and charges. `ReceiptLinkClient` is for providers.
24
+ - **Provider response statements.** `build_response_statement`, `sign_statement` and `verify_statement_signature`.
25
+
26
+ It passes the same signing test vectors as the TypeScript SDK.
27
+
28
+ ```bash
29
+ pip install atcn
30
+ ```
31
+
32
+ ```python
33
+ from atcn import canonicalize, generate_key_pair, sign_payload, verify_payload
34
+
35
+ canonicalize({"b": 1, "a": 2}) # '{"a":2,"b":1}'
36
+ private_key, public_key = generate_key_pair()
37
+ signed = sign_payload({"hello": "world"}, "key_1", 1, private_key)
38
+ assert verify_payload(signed, public_key)
39
+ ```
40
+
41
+ The API clients need an ATCN API at `base_url`. The hosted API is not open for signup yet.
42
+
43
+ The Python SDK does not verify task closures or receipts. Use `npx @atcn/verify-cli` or the TypeScript SDK for that.
44
+
45
+ `python -m atcn init` records whether this machine shares anonymous usage metrics. Reporting is off by default and needs `ATCN_USAGE_URL`; see the [usage data documentation](https://github.com/fadnisnikhil/atcn/blob/main/docs/USAGE_DATA.md).
46
+
47
+ Apache-2.0.
atcn-1.3.0/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # atcn (Python SDK)
2
+
3
+ The ATCN Python SDK. It covers:
4
+
5
+ - **Signing.** RFC 8785 canonical JSON, Ed25519 signing, and obligation event signing with `EventSigner`.
6
+ - **Webhooks.** `verify_webhook` and `sign_webhook`.
7
+ - **API clients.** `AtcnClient` is for the clearing network. `SubledgerClient` and `CaptureQueue` record tasks, delegations and charges. `ReceiptLinkClient` is for providers.
8
+ - **Provider response statements.** `build_response_statement`, `sign_statement` and `verify_statement_signature`.
9
+
10
+ It passes the same signing test vectors as the TypeScript SDK.
11
+
12
+ ```bash
13
+ pip install atcn
14
+ ```
15
+
16
+ ```python
17
+ from atcn import canonicalize, generate_key_pair, sign_payload, verify_payload
18
+
19
+ canonicalize({"b": 1, "a": 2}) # '{"a":2,"b":1}'
20
+ private_key, public_key = generate_key_pair()
21
+ signed = sign_payload({"hello": "world"}, "key_1", 1, private_key)
22
+ assert verify_payload(signed, public_key)
23
+ ```
24
+
25
+ The API clients need an ATCN API at `base_url`. The hosted API is not open for signup yet.
26
+
27
+ The Python SDK does not verify task closures or receipts. Use `npx @atcn/verify-cli` or the TypeScript SDK for that.
28
+
29
+ `python -m atcn init` records whether this machine shares anonymous usage metrics. Reporting is off by default and needs `ATCN_USAGE_URL`; see the [usage data documentation](https://github.com/fadnisnikhil/atcn/blob/main/docs/USAGE_DATA.md).
30
+
31
+ Apache-2.0.
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "atcn"
7
+ version = "1.3.0"
8
+ description = "Python SDK for the Agent Transaction Closure Network: canonical JSON, Ed25519 event signing, webhook verification, API client, Agent Work Subledger"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ dependencies = ["cryptography>=42"]
14
+
15
+ [project.urls]
16
+ Homepage = "https://github.com/fadnisnikhil/atcn"
17
+ Source = "https://github.com/fadnisnikhil/atcn/tree/main/packages/sdk-python"
18
+ Issues = "https://github.com/fadnisnikhil/atcn/issues"
19
+
20
+ [project.optional-dependencies]
21
+ test = ["pytest>=8"]
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]
28
+ pythonpath = ["src"]
atcn-1.3.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,60 @@
1
+ """ATCN Python SDK."""
2
+
3
+ from .canonical import canonicalize
4
+ from .client import SDK_HEADER, SDK_VERSION, AtcnApiError, AtcnClient
5
+ from .crypto import (
6
+ digest_of,
7
+ generate_key_pair,
8
+ public_key_from_private,
9
+ sha256_digest,
10
+ sign_payload,
11
+ verify_payload,
12
+ )
13
+ from .events import EventSigner, EvidenceInput, acceptance_data, evidence_envelope, utc_now
14
+ from .ids import new_id
15
+ from .subledger import (
16
+ CaptureQueue,
17
+ ReceiptLinkClient,
18
+ SubledgerClient,
19
+ build_response_statement,
20
+ countersign_payload,
21
+ ext,
22
+ sign_statement,
23
+ stable_key,
24
+ verify_countersignature,
25
+ verify_statement_signature,
26
+ )
27
+ from .webhooks import WEBHOOK_SIGNATURE_HEADER, sign_webhook, verify_webhook
28
+
29
+ __all__ = [
30
+ "SDK_HEADER",
31
+ "SDK_VERSION",
32
+ "AtcnApiError",
33
+ "AtcnClient",
34
+ "CaptureQueue",
35
+ "EventSigner",
36
+ "EvidenceInput",
37
+ "ReceiptLinkClient",
38
+ "SubledgerClient",
39
+ "WEBHOOK_SIGNATURE_HEADER",
40
+ "acceptance_data",
41
+ "build_response_statement",
42
+ "canonicalize",
43
+ "countersign_payload",
44
+ "digest_of",
45
+ "evidence_envelope",
46
+ "ext",
47
+ "generate_key_pair",
48
+ "new_id",
49
+ "public_key_from_private",
50
+ "sha256_digest",
51
+ "sign_payload",
52
+ "sign_statement",
53
+ "sign_webhook",
54
+ "stable_key",
55
+ "utc_now",
56
+ "verify_countersignature",
57
+ "verify_payload",
58
+ "verify_statement_signature",
59
+ "verify_webhook",
60
+ ]
@@ -0,0 +1,41 @@
1
+ """`python -m atcn init [--share-usage yes|no]`: records whether this machine shares anonymous usage metrics."""
2
+
3
+ import argparse
4
+ import sys
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from .client import SDK_VERSION
9
+ from .usage import Env, ask_to_share_usage, save_usage_choice, send_usage_report, settings_path, usage_status
10
+
11
+
12
+ def main(argv: list[str] | None = None, read_line: Callable[[str], str] = input, write: Callable[[str], Any] = print, interactive: bool | None = None, env: Env | None = None) -> int:
13
+ """Returns the exit code: 0 saved, 2 usage error or no answer. On a yes, reports integration_initialized."""
14
+ parser = argparse.ArgumentParser(prog="python -m atcn")
15
+ parser.add_argument("command", choices=["init"])
16
+ parser.add_argument("--share-usage", choices=["yes", "no"])
17
+ try:
18
+ args = parser.parse_args(argv)
19
+ except SystemExit as exit_:
20
+ return int(exit_.code or 0)
21
+
22
+ if args.share_usage is not None:
23
+ shared: bool | None = save_usage_choice(args.share_usage == "yes", env)["share_usage"]
24
+ elif interactive if interactive is not None else sys.stdin.isatty():
25
+ shared = ask_to_share_usage(read_line, write, env)
26
+ else:
27
+ write("Not an interactive terminal: pass --share-usage yes or --share-usage no.")
28
+ return 2
29
+ if shared is None:
30
+ write("No answer given; nothing saved.")
31
+ return 2
32
+
33
+ if shared:
34
+ send_usage_report({"event": "integration_initialized", "sdk_version": f"python/{SDK_VERSION}", "workflow": "custom", "delegations": None, "charges": None}, env)
35
+ write(f"Saved your choice to {settings_path(env)}.")
36
+ write(f"Usage metrics: {usage_status(env)['reason']}.")
37
+ return 0
38
+
39
+
40
+ if __name__ == "__main__":
41
+ sys.exit(main())
@@ -0,0 +1,38 @@
1
+ """Canonical JSON (RFC 8785 JCS, restricted to safe integers) - byte-identical to the TypeScript SDK."""
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ MAX_SAFE_INTEGER = 2**53 - 1
7
+
8
+
9
+ def _utf16_sort_key(key: str) -> bytes:
10
+ # JCS orders object members by UTF-16 code units, like JavaScript's default sort.
11
+ return key.encode("utf-16-be")
12
+
13
+
14
+ def canonicalize(value: Any) -> str:
15
+ """Serializes a value canonically. Floats are rejected: amounts are integer minor units."""
16
+ if value is None:
17
+ return "null"
18
+ if value is True:
19
+ return "true"
20
+ if value is False:
21
+ return "false"
22
+ if isinstance(value, int):
23
+ if abs(value) > MAX_SAFE_INTEGER:
24
+ raise ValueError(f"integer {value} exceeds the safe integer range")
25
+ return str(value)
26
+ if isinstance(value, float):
27
+ raise ValueError("floats are not allowed in canonical payloads; use integer minor units")
28
+ if isinstance(value, str):
29
+ return json.dumps(value, ensure_ascii=False)
30
+ if isinstance(value, (list, tuple)):
31
+ return "[" + ",".join(canonicalize(item) for item in value) + "]"
32
+ if isinstance(value, dict):
33
+ for key in value:
34
+ if not isinstance(key, str):
35
+ raise ValueError("object keys must be strings")
36
+ members = sorted(value.items(), key=lambda item: _utf16_sort_key(item[0]))
37
+ return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + canonicalize(v) for k, v in members) + "}"
38
+ raise ValueError(f"unsupported type {type(value).__name__}")
@@ -0,0 +1,123 @@
1
+ """Minimal ATCN API client using only the standard library for HTTP."""
2
+
3
+ import json
4
+ import time
5
+ import uuid
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from typing import Any
10
+
11
+ from .crypto import Signed
12
+
13
+ # Must equal the version in pyproject.toml (checked by a test).
14
+ SDK_VERSION = "1.3.0"
15
+ # Names the SDK and its version on every request, so the API operator can count SDK versions in use. Nothing else is sent.
16
+ SDK_HEADER = "atcn-sdk"
17
+
18
+
19
+ class AtcnApiError(Exception):
20
+ def __init__(self, status: int, code: str, message: str, reason: str | None, retryable: bool, correlation_id: str | None):
21
+ super().__init__(f"{code}{f' ({reason})' if reason else ''}: {message}")
22
+ self.status = status
23
+ self.code = code
24
+ self.reason = reason
25
+ self.retryable = retryable
26
+ self.correlation_id = correlation_id
27
+
28
+
29
+ class AtcnClient:
30
+ """Every mutating call carries an Idempotency-Key; signed events use event:<event_id>.
31
+
32
+ With share_token, requests authenticate as a receipt-link holder (x-atcn-share-token) instead of with an API key.
33
+ default_headers are sent on every request.
34
+ """
35
+
36
+ def __init__(self, base_url: str, api_key: str, retries: int = 2, timeout: float = 30.0, share_token: str | None = None, default_headers: dict[str, str] | None = None):
37
+ self.base_url = base_url.rstrip("/")
38
+ self.api_key = api_key
39
+ self.retries = retries
40
+ self.timeout = timeout
41
+ self.share_token = share_token
42
+ self.default_headers = default_headers or {}
43
+
44
+ def request(self, method: str, path: str, body: Any = None, idempotency_key: str | None = None, query: dict[str, Any] | None = None, raw: bytes | None = None, headers: dict[str, str] | None = None, content_type: str = "application/octet-stream") -> Any:
45
+ url = self.base_url + path
46
+ if query:
47
+ url += "?" + urllib.parse.urlencode({k: v for k, v in query.items() if v is not None})
48
+ auth_header = {"x-atcn-share-token": self.share_token} if self.share_token else {"authorization": f"Bearer {self.api_key}"}
49
+ all_headers = {SDK_HEADER: f"python/{SDK_VERSION}", **auth_header, **self.default_headers, **(headers or {})}
50
+ data: bytes | None = None
51
+ if method != "GET":
52
+ all_headers["idempotency-key"] = idempotency_key or str(uuid.uuid4())
53
+ if raw is not None:
54
+ all_headers["content-type"] = content_type
55
+ data = raw
56
+ elif body is not None:
57
+ all_headers["content-type"] = "application/json"
58
+ data = json.dumps(body).encode("utf-8")
59
+
60
+ attempt = 0
61
+ while True:
62
+ attempt += 1
63
+ request = urllib.request.Request(url, data=data, method=method, headers=all_headers)
64
+ try:
65
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
66
+ text = response.read().decode("utf-8")
67
+ return json.loads(text) if text and "json" in response.headers.get("content-type", "") else text
68
+ except urllib.error.HTTPError as http_error:
69
+ text = http_error.read().decode("utf-8")
70
+ parsed = json.loads(text) if text.startswith("{") else {}
71
+ err = parsed.get("error", {})
72
+ api_error = AtcnApiError(http_error.code, err.get("code", "http_error"), err.get("message", text), err.get("reason"), bool(err.get("retryable")), parsed.get("correlation_id"))
73
+ if api_error.retryable and attempt <= self.retries:
74
+ time.sleep(0.1 * 2**attempt)
75
+ continue
76
+ raise api_error from None
77
+
78
+ # Obligations
79
+ def create_obligation(self, signed: Signed, subledger: dict[str, Any] | None = None) -> Any:
80
+ """With subledger={"task_id": ..., "parent_delegation_id": ...}, the obligation also becomes a delegation of that task.
81
+
82
+ The link is not part of the signed event and is never shared with the counterparty.
83
+ """
84
+ body = {**signed, "subledger": subledger} if subledger else signed
85
+ return self.request("POST", "/v1/obligations", body, f"event:{signed['payload']['event_id']}")
86
+
87
+ def accept_obligation(self, obligation_id: str, signed: Signed) -> Any:
88
+ return self.request("POST", f"/v1/obligations/{obligation_id}/accept", signed, f"event:{signed['payload']['event_id']}")
89
+
90
+ def append_event(self, obligation_id: str, signed: Signed) -> Any:
91
+ return self.request("POST", f"/v1/obligations/{obligation_id}/events", signed, f"event:{signed['payload']['event_id']}")
92
+
93
+ def get_obligation(self, obligation_id: str) -> Any:
94
+ return self.request("GET", f"/v1/obligations/{obligation_id}")
95
+
96
+ def list_events(self, obligation_id: str) -> Any:
97
+ return self.request("GET", f"/v1/obligations/{obligation_id}/events")
98
+
99
+ # Evidence and clearing
100
+ def upload_blob(self, content: bytes, media_type: str = "application/octet-stream") -> Any:
101
+ return self.request("POST", "/v1/blobs", raw=content, headers={"x-media-type": media_type})
102
+
103
+ def submit_evidence(self, obligation_id: str, signed: Signed) -> Any:
104
+ return self.request("POST", f"/v1/obligations/{obligation_id}/evidence", signed, f"event:{signed['payload']['event_id']}")
105
+
106
+ def evaluate(self, obligation_id: str, policy_id: str, policy_version: str, idempotency_key: str | None = None) -> Any:
107
+ return self.request("POST", f"/v1/obligations/{obligation_id}/evaluate", {"policy_id": policy_id, "policy_version": policy_version}, idempotency_key)
108
+
109
+ def finalize(self, decision_id: str, idempotency_key: str | None = None) -> Any:
110
+ return self.request("POST", f"/v1/decisions/{decision_id}/finalize", None, idempotency_key)
111
+
112
+ # Journal, settlement, export
113
+ def journal(self, **filters: Any) -> Any:
114
+ return self.request("GET", "/v1/journal", query=filters)
115
+
116
+ def report_settlement_event(self, event: dict[str, Any], idempotency_key: str | None = None) -> Any:
117
+ return self.request("POST", "/v1/settlements/events", event, idempotency_key)
118
+
119
+ def export_closure_package(self, obligation_id: str) -> Any:
120
+ return self.request("GET", f"/v1/exports/{obligation_id}")
121
+
122
+ def service_keys(self) -> Any:
123
+ return self.request("GET", "/v1/service/keys")
@@ -0,0 +1,78 @@
1
+ """Ed25519 signing over canonical JSON, SHA-256 digests, and base64url encoding."""
2
+
3
+ import base64
4
+ import hashlib
5
+ from typing import Any, TypedDict
6
+
7
+ from cryptography.exceptions import InvalidSignature
8
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
9
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
10
+
11
+ from .canonical import canonicalize
12
+
13
+ SIGNATURE_ALGORITHM = "Ed25519"
14
+
15
+
16
+ class Signature(TypedDict):
17
+ key_id: str
18
+ key_version: int
19
+ algorithm: str
20
+ value: str
21
+
22
+
23
+ class Signed(TypedDict):
24
+ payload: Any
25
+ signature: Signature
26
+
27
+
28
+ def b64url_encode(data: bytes) -> str:
29
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
30
+
31
+
32
+ def b64url_decode(text: str) -> bytes:
33
+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
34
+
35
+
36
+ def sha256_digest(data: bytes | str) -> str:
37
+ raw = data.encode("utf-8") if isinstance(data, str) else data
38
+ return "sha256:" + hashlib.sha256(raw).hexdigest()
39
+
40
+
41
+ def digest_of(value: Any) -> str:
42
+ """Digest of the canonical JSON form of a value (terms digests, payload hashes)."""
43
+ return sha256_digest(canonicalize(value))
44
+
45
+
46
+ def generate_key_pair() -> tuple[str, str]:
47
+ """Returns (private_key, public_key) as base64url strings; the private key is the 32-byte seed."""
48
+ private = Ed25519PrivateKey.generate()
49
+ seed = private.private_bytes_raw()
50
+ return b64url_encode(seed), public_key_from_private(b64url_encode(seed))
51
+
52
+
53
+ def public_key_from_private(private_key: str) -> str:
54
+ private = Ed25519PrivateKey.from_private_bytes(b64url_decode(private_key))
55
+ return b64url_encode(private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))
56
+
57
+
58
+ def sign_bytes(data: bytes, private_key: str) -> str:
59
+ return b64url_encode(Ed25519PrivateKey.from_private_bytes(b64url_decode(private_key)).sign(data))
60
+
61
+
62
+ def verify_bytes(data: bytes, signature: str, public_key: str) -> bool:
63
+ try:
64
+ Ed25519PublicKey.from_public_bytes(b64url_decode(public_key)).verify(b64url_decode(signature), data)
65
+ return True
66
+ except (InvalidSignature, ValueError):
67
+ return False
68
+
69
+
70
+ def sign_payload(payload: Any, key_id: str, key_version: int, private_key: str) -> Signed:
71
+ value = sign_bytes(canonicalize(payload).encode("utf-8"), private_key)
72
+ return {"payload": payload, "signature": {"key_id": key_id, "key_version": key_version, "algorithm": SIGNATURE_ALGORITHM, "value": value}}
73
+
74
+
75
+ def verify_payload(signed: Signed, public_key: str) -> bool:
76
+ if signed["signature"].get("algorithm") != SIGNATURE_ALGORITHM:
77
+ return False
78
+ return verify_bytes(canonicalize(signed["payload"]).encode("utf-8"), signed["signature"]["value"], public_key)