atcn 1.3.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.
- atcn/__init__.py +60 -0
- atcn/__main__.py +41 -0
- atcn/canonical.py +38 -0
- atcn/client.py +123 -0
- atcn/crypto.py +78 -0
- atcn/events.py +80 -0
- atcn/ids.py +29 -0
- atcn/subledger.py +376 -0
- atcn/usage.py +127 -0
- atcn/webhooks.py +45 -0
- atcn-1.3.0.dist-info/METADATA +47 -0
- atcn-1.3.0.dist-info/RECORD +15 -0
- atcn-1.3.0.dist-info/WHEEL +5 -0
- atcn-1.3.0.dist-info/licenses/LICENSE +202 -0
- atcn-1.3.0.dist-info/top_level.txt +1 -0
atcn/__init__.py
ADDED
|
@@ -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
|
+
]
|
atcn/__main__.py
ADDED
|
@@ -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())
|
atcn/canonical.py
ADDED
|
@@ -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__}")
|
atcn/client.py
ADDED
|
@@ -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")
|
atcn/crypto.py
ADDED
|
@@ -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)
|
atcn/events.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Event signing and evidence envelopes."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .crypto import Signed, digest_of, sha256_digest, sign_payload
|
|
8
|
+
from .ids import new_id
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def utc_now() -> str:
|
|
12
|
+
"""ISO-8601 UTC timestamp with milliseconds and a Z suffix, as ATCN timestamps require."""
|
|
13
|
+
now = datetime.now(timezone.utc)
|
|
14
|
+
return now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class EventSigner:
|
|
19
|
+
"""Signs events for one actor. The private key never leaves the caller."""
|
|
20
|
+
|
|
21
|
+
actor_id: str
|
|
22
|
+
platform_id: str
|
|
23
|
+
key_id: str
|
|
24
|
+
private_key: str
|
|
25
|
+
key_version: int = 1
|
|
26
|
+
|
|
27
|
+
def sign(self, event_type: str, obligation_id: str, data: dict[str, Any] | None = None, causation_ids: list[str] | None = None) -> Signed:
|
|
28
|
+
payload = {
|
|
29
|
+
"schema_version": "1.0",
|
|
30
|
+
"event_id": new_id("event"),
|
|
31
|
+
"event_type": event_type,
|
|
32
|
+
"obligation_id": obligation_id,
|
|
33
|
+
"actor_id": self.actor_id,
|
|
34
|
+
"actor_platform_id": self.platform_id,
|
|
35
|
+
"event_time": utc_now(),
|
|
36
|
+
"causation_ids": causation_ids or [],
|
|
37
|
+
"data": data or {},
|
|
38
|
+
}
|
|
39
|
+
return sign_payload(payload, self.key_id, self.key_version, self.private_key)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def acceptance_data(terms: dict[str, Any], accepting_agent_id: str) -> dict[str, Any]:
|
|
43
|
+
"""Data for obligation.accepted: binds the acceptance to the exact terms version, digest, and policy."""
|
|
44
|
+
return {
|
|
45
|
+
"terms_version": terms["terms_version"],
|
|
46
|
+
"terms_digest": digest_of(terms),
|
|
47
|
+
"policy_id": terms["acceptance_policy"]["policy_id"],
|
|
48
|
+
"policy_version": terms["acceptance_policy"]["policy_version"],
|
|
49
|
+
"counterparty_agent_id": accepting_agent_id,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class EvidenceInput:
|
|
55
|
+
evidence_type: str
|
|
56
|
+
producer_id: str
|
|
57
|
+
content: bytes
|
|
58
|
+
uri: str
|
|
59
|
+
retrieval_method: str
|
|
60
|
+
media_type: str
|
|
61
|
+
verifiers: list[str]
|
|
62
|
+
deliverable_ids: list[str]
|
|
63
|
+
visible_to: list[str] = field(default_factory=lambda: ["issuer", "counterparty", "reviewer", "verifier"])
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def evidence_envelope(item: EvidenceInput) -> dict[str, Any]:
|
|
67
|
+
"""Evidence envelope whose content_digest is computed from the bytes the producer holds."""
|
|
68
|
+
return {
|
|
69
|
+
"evidence_id": new_id("evidence"),
|
|
70
|
+
"evidence_type": item.evidence_type,
|
|
71
|
+
"producer_id": item.producer_id,
|
|
72
|
+
"created_at": utc_now(),
|
|
73
|
+
"content_digest": sha256_digest(item.content),
|
|
74
|
+
"uri": item.uri,
|
|
75
|
+
"retrieval_method": item.retrieval_method,
|
|
76
|
+
"media_type": item.media_type,
|
|
77
|
+
"access_policy": {"visible_to": item.visible_to},
|
|
78
|
+
"verifiers": item.verifiers,
|
|
79
|
+
"deliverable_ids": item.deliverable_ids,
|
|
80
|
+
}
|
atcn/ids.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Prefixed ULIDs, matching the TypeScript ids (e.g. evt_01J9Z...)."""
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
|
7
|
+
|
|
8
|
+
PREFIXES = {
|
|
9
|
+
"obligation": "obl",
|
|
10
|
+
"event": "evt",
|
|
11
|
+
"evidence": "evd",
|
|
12
|
+
"agent": "agt",
|
|
13
|
+
"principal": "prn",
|
|
14
|
+
"platform": "plt",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def ulid(now_ms: int | None = None) -> str:
|
|
19
|
+
remaining = int(time.time() * 1000) if now_ms is None else now_ms
|
|
20
|
+
time_part = ""
|
|
21
|
+
for _ in range(10):
|
|
22
|
+
time_part = CROCKFORD[remaining % 32] + time_part
|
|
23
|
+
remaining //= 32
|
|
24
|
+
random_part = "".join(CROCKFORD[b % 32] for b in secrets.token_bytes(16))
|
|
25
|
+
return time_part + random_part
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def new_id(kind: str) -> str:
|
|
29
|
+
return f"{PREFIXES[kind]}_{ulid()}"
|
atcn/subledger.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""Agent Work Subledger (PRD v1.2) client, receipt-link client, capture queue, and signing helpers.
|
|
2
|
+
|
|
3
|
+
Mirrors the TypeScript SDK (@atcn/sdk): same idempotency keys, same canonical statements, same signatures.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import uuid
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .canonical import canonicalize
|
|
14
|
+
from .client import AtcnApiError, AtcnClient
|
|
15
|
+
from .crypto import sha256_digest, sign_bytes, verify_bytes
|
|
16
|
+
|
|
17
|
+
Json = dict[str, Any]
|
|
18
|
+
|
|
19
|
+
RESPONSE_STATEMENT_TYPE = "atcn.subledger.receipt_response"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def ext(external_ref: str) -> str:
|
|
23
|
+
"""Caller-supplied references address records before their server IDs are known: ext("job-42")."""
|
|
24
|
+
return f"ext:{external_ref}"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def stable_key(kind: str, *parts: str) -> str:
|
|
28
|
+
"""Idempotency key derived from the caller's stable references; long references are hashed to fit 8-200 chars."""
|
|
29
|
+
key = f"sl:{kind}:{':'.join(parts)}"
|
|
30
|
+
return key if len(key) <= 200 else f"sl:{kind}:{sha256_digest(':'.join(parts))}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _path(ref: str) -> str:
|
|
34
|
+
return urllib.parse.quote(ref, safe="")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ---------- Statements and signatures ----------
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_response_statement(receipt: Json, response_type: str, fields: list[str] | None = None, note: str | None = None, evidence: list[Json] | None = None, corrections: list[Json] | None = None) -> Json:
|
|
41
|
+
"""The statement a provider responds with. receipt needs receipt_id, digest, revision, and issuer_operator_id."""
|
|
42
|
+
return {
|
|
43
|
+
"document_type": RESPONSE_STATEMENT_TYPE,
|
|
44
|
+
"receipt_id": receipt["receipt_id"],
|
|
45
|
+
"receipt_digest": receipt["digest"],
|
|
46
|
+
"receipt_revision": receipt["revision"],
|
|
47
|
+
"issuer_operator_id": receipt["issuer_operator_id"],
|
|
48
|
+
"response_type": response_type,
|
|
49
|
+
"fields": sorted(set(fields or [])),
|
|
50
|
+
"note": note,
|
|
51
|
+
"evidence": evidence or [],
|
|
52
|
+
"corrections": corrections or [],
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def sign_statement(statement: Json, private_key: str) -> str:
|
|
57
|
+
"""Provider-side signing. The service never sees the private key."""
|
|
58
|
+
return sign_bytes(canonicalize(statement).encode("utf-8"), private_key)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def verify_statement_signature(statement: Json, signature: str, public_key: str) -> bool:
|
|
62
|
+
return verify_bytes(canonicalize(statement).encode("utf-8"), signature, public_key)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def countersign_payload(payload: Any, private_key: str) -> str:
|
|
66
|
+
"""Operator-side countersignature over a closure or receipt payload, made with a key the operator holds."""
|
|
67
|
+
return sign_bytes(canonicalize(payload).encode("utf-8"), private_key)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def verify_countersignature(payload: Any, signature: str, public_key: str) -> bool:
|
|
71
|
+
return verify_bytes(canonicalize(payload).encode("utf-8"), signature, public_key)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ---------- Operator client ----------
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class SubledgerClient:
|
|
78
|
+
"""Small, independent subledger operations. Default idempotency keys derive from the caller's stable references."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, base_url: str, api_key: str, retries: int = 2, timeout: float = 30.0, default_headers: dict[str, str] | None = None):
|
|
81
|
+
self.http = AtcnClient(base_url, api_key, retries=retries, timeout=timeout, default_headers=default_headers)
|
|
82
|
+
|
|
83
|
+
# Tasks, delegations, delivery claims
|
|
84
|
+
def create_task(self, task: Json, idempotency_key: str | None = None) -> Json:
|
|
85
|
+
return self.http.request("POST", "/v1/tasks", task, idempotency_key or stable_key("task", task["external_ref"]))
|
|
86
|
+
|
|
87
|
+
def get_task(self, task_id: str) -> Json:
|
|
88
|
+
return self.http.request("GET", f"/v1/tasks/{_path(task_id)}")
|
|
89
|
+
|
|
90
|
+
def list_tasks(self, status: str | None = None, external_ref: str | None = None) -> Json:
|
|
91
|
+
return self.http.request("GET", "/v1/tasks", query={"status": status, "external_ref": external_ref})
|
|
92
|
+
|
|
93
|
+
def get_task_access(self, task_id: str) -> Json:
|
|
94
|
+
"""Admin only. Principals are "user:<id>" or "api_key:<id>"."""
|
|
95
|
+
return self.http.request("GET", f"/v1/tasks/{_path(task_id)}/access")
|
|
96
|
+
|
|
97
|
+
def update_task_access(self, task_id: str, restricted: bool | None = None, grant: list[str] | None = None, revoke: list[str] | None = None, idempotency_key: str | None = None) -> Json:
|
|
98
|
+
body: Json = {"grant": grant or [], "revoke": revoke or []}
|
|
99
|
+
if restricted is not None:
|
|
100
|
+
body["restricted"] = restricted
|
|
101
|
+
return self.http.request("POST", f"/v1/tasks/{_path(task_id)}/access", body, idempotency_key)
|
|
102
|
+
|
|
103
|
+
def create_delegation(self, task_id: str, delegation: Json, idempotency_key: str | None = None) -> Json:
|
|
104
|
+
key = idempotency_key or (stable_key("delegation", delegation["external_ref"]) if delegation.get("external_ref") else None)
|
|
105
|
+
return self.http.request("POST", f"/v1/tasks/{_path(task_id)}/delegations", delegation, key)
|
|
106
|
+
|
|
107
|
+
def assign_provider(self, delegation_id: str, provider_id: str, idempotency_key: str | None = None) -> Json:
|
|
108
|
+
return self.http.request("POST", f"/v1/delegations/{_path(delegation_id)}/provider", {"provider_id": provider_id}, idempotency_key)
|
|
109
|
+
|
|
110
|
+
def append_delegation_event(self, delegation_id: str, event: Json, idempotency_key: str | None = None) -> Json:
|
|
111
|
+
return self.http.request("POST", f"/v1/delegations/{_path(delegation_id)}/events", event, idempotency_key)
|
|
112
|
+
|
|
113
|
+
def report_capture_gap(self, task_id: str, kind: str, detail: str, delegation_id: str | None = None, idempotency_key: str | None = None) -> Json:
|
|
114
|
+
return self.http.request("POST", f"/v1/tasks/{_path(task_id)}/capture-gaps", {"kind": kind, "detail": detail, "delegation_id": delegation_id}, idempotency_key)
|
|
115
|
+
|
|
116
|
+
# Financial events, matching, allocation
|
|
117
|
+
def record_financial_event(self, event: Json, idempotency_key: str | None = None) -> Json:
|
|
118
|
+
return self.http.request("POST", "/v1/financial-events", event, idempotency_key or stable_key("financial", event["source"], event["source_event_id"]))
|
|
119
|
+
|
|
120
|
+
def import_csv(self, csv_text: str, idempotency_key: str | None = None) -> Json:
|
|
121
|
+
return self.http.request("POST", "/v1/financial-events/import", idempotency_key=idempotency_key, raw=csv_text.encode("utf-8"), content_type="text/csv")
|
|
122
|
+
|
|
123
|
+
def list_financial_events(self, unattributed: bool | None = None, source: str | None = None) -> Json:
|
|
124
|
+
return self.http.request("GET", "/v1/financial-events", query={"unattributed": None if unattributed is None else str(unattributed).lower(), "source": source})
|
|
125
|
+
|
|
126
|
+
def allocate(self, financial_event_id: str, allocation: Json, idempotency_key: str | None = None) -> Json:
|
|
127
|
+
return self.http.request("POST", f"/v1/financial-events/{financial_event_id}/allocations", allocation, idempotency_key)
|
|
128
|
+
|
|
129
|
+
def create_allocation_rule(self, rule: Json, idempotency_key: str | None = None) -> Json:
|
|
130
|
+
return self.http.request("POST", "/v1/allocation-rules", rule, idempotency_key)
|
|
131
|
+
|
|
132
|
+
def list_matches(self, status: str | None = None) -> Json:
|
|
133
|
+
return self.http.request("GET", "/v1/matches", query={"status": status})
|
|
134
|
+
|
|
135
|
+
def confirm_match(self, match_id: str, task_id: str, delegation_id: str | None = None, idempotency_key: str | None = None) -> Json:
|
|
136
|
+
return self.http.request("POST", f"/v1/matches/{match_id}/confirm", {"task_id": task_id, "delegation_id": delegation_id}, idempotency_key)
|
|
137
|
+
|
|
138
|
+
def financial_summary(self, task_id: str, report_currency: str | None = None, as_of: str | None = None) -> Json:
|
|
139
|
+
return self.http.request("GET", f"/v1/tasks/{_path(task_id)}/financial-summary", query={"report_currency": report_currency, "as_of": as_of})
|
|
140
|
+
|
|
141
|
+
def list_exceptions(self, task_id: str | None = None, status: str | None = None) -> Json:
|
|
142
|
+
return self.http.request("GET", "/v1/subledger-exceptions", query={"task_id": task_id, "status": status})
|
|
143
|
+
|
|
144
|
+
def resolve_exception(self, exception_id: str, status: str, resolution: str, idempotency_key: str | None = None) -> Json:
|
|
145
|
+
return self.http.request("POST", f"/v1/subledger-exceptions/{exception_id}/resolve", {"status": status, "resolution": resolution}, idempotency_key)
|
|
146
|
+
|
|
147
|
+
# Closures and receipts
|
|
148
|
+
def close_task(self, task_id: str, idempotency_key: str | None = None) -> Json:
|
|
149
|
+
return self.http.request("POST", f"/v1/tasks/{_path(task_id)}/close", {}, idempotency_key)
|
|
150
|
+
|
|
151
|
+
def get_closure(self, task_id: str, version: int | None = None) -> Json:
|
|
152
|
+
return self.http.request("GET", f"/v1/tasks/{_path(task_id)}/closure", query={"version": version})
|
|
153
|
+
|
|
154
|
+
def create_receipt(self, task_id: str, delegation_id: str, idempotency_key: str | None = None) -> Json:
|
|
155
|
+
return self.http.request("POST", f"/v1/tasks/{_path(task_id)}/receipts", {"delegation_id": delegation_id}, idempotency_key)
|
|
156
|
+
|
|
157
|
+
def get_receipt(self, receipt_id: str) -> Json:
|
|
158
|
+
return self.http.request("GET", f"/v1/receipts/{receipt_id}")
|
|
159
|
+
|
|
160
|
+
def mark_receipt_delivered(self, receipt_id: str, channel: str, reference: str | None = None, idempotency_key: str | None = None) -> Json:
|
|
161
|
+
return self.http.request("POST", f"/v1/receipts/{receipt_id}/delivered", {"channel": channel, "reference": reference}, idempotency_key)
|
|
162
|
+
|
|
163
|
+
def create_receipt_share(self, receipt_id: str, allowed_actions: list[str] | None = None, ttl_hours: int | None = None, idempotency_key: str | None = None) -> Json:
|
|
164
|
+
body: Json = {"receipt_id": receipt_id, "allowed_actions": allowed_actions or ["view"]}
|
|
165
|
+
if ttl_hours is not None:
|
|
166
|
+
body["ttl_hours"] = ttl_hours
|
|
167
|
+
return self.http.request("POST", "/v1/receipt-shares", body, idempotency_key)
|
|
168
|
+
|
|
169
|
+
def revoke_receipt_share(self, share_id: str, idempotency_key: str | None = None) -> Json:
|
|
170
|
+
return self.http.request("DELETE", f"/v1/receipt-shares/{share_id}", None, idempotency_key)
|
|
171
|
+
|
|
172
|
+
def list_responses(self, receipt_id: str) -> Json:
|
|
173
|
+
return self.http.request("GET", f"/v1/receipts/{receipt_id}/responses")
|
|
174
|
+
|
|
175
|
+
def decide_correction(self, response_id: str, status: str, reason: str, financial_events: list[Json] | None = None, idempotency_key: str | None = None) -> Json:
|
|
176
|
+
"""Accepting appends the corrected records. A correction of financial fields needs the corrected events."""
|
|
177
|
+
body = {"status": status, "reason": reason, "financial_events": financial_events or []}
|
|
178
|
+
return self.http.request("POST", f"/v1/receipt-responses/{response_id}/decision", body, idempotency_key)
|
|
179
|
+
|
|
180
|
+
# Provider identity
|
|
181
|
+
def create_provider(self, provider: Json, idempotency_key: str | None = None) -> Json:
|
|
182
|
+
return self.http.request("POST", "/v1/provider-identities", provider, idempotency_key or stable_key("provider", provider["name"]))
|
|
183
|
+
|
|
184
|
+
def bind_provider_key(self, provider_id: str, key_id: str, public_key: str, idempotency_key: str | None = None) -> Json:
|
|
185
|
+
return self.http.request("POST", f"/v1/provider-identities/{provider_id}/key-bindings", {"key_id": key_id, "public_key": public_key}, idempotency_key)
|
|
186
|
+
|
|
187
|
+
def start_domain_challenge(self, provider_id: str, key_id: str, public_key: str, domain: str | None = None, idempotency_key: str | None = None) -> Json:
|
|
188
|
+
"""Admin only. The provider publishes the returned txt_value at txt_name; then call verify_domain_challenge."""
|
|
189
|
+
body: Json = {"key_id": key_id, "public_key": public_key}
|
|
190
|
+
if domain is not None:
|
|
191
|
+
body["domain"] = domain
|
|
192
|
+
return self.http.request("POST", f"/v1/provider-identities/{provider_id}/domain-challenges", body, idempotency_key)
|
|
193
|
+
|
|
194
|
+
def verify_domain_challenge(self, challenge_id: str, idempotency_key: str | None = None) -> Json:
|
|
195
|
+
return self.http.request("POST", f"/v1/domain-challenges/{challenge_id}/verify", {}, idempotency_key)
|
|
196
|
+
|
|
197
|
+
# Operator-held signing keys
|
|
198
|
+
def register_operator_key(self, key_id: str, public_key: str, idempotency_key: str | None = None) -> Json:
|
|
199
|
+
"""Admin only. Registers the public half of a key the operator holds; the private key stays with the operator."""
|
|
200
|
+
return self.http.request("POST", "/v1/operator-keys", {"key_id": key_id, "public_key": public_key}, idempotency_key)
|
|
201
|
+
|
|
202
|
+
def revoke_operator_key(self, key_id: str, reason: str, idempotency_key: str | None = None) -> Json:
|
|
203
|
+
return self.http.request("POST", f"/v1/operator-keys/{_path(key_id)}/revoke", {"reason": reason}, idempotency_key)
|
|
204
|
+
|
|
205
|
+
def operator_keys(self, operator_id: str) -> Json:
|
|
206
|
+
return self.http.request("GET", f"/v1/operators/{operator_id}/keys")
|
|
207
|
+
|
|
208
|
+
def countersign(self, signed: Json, key_id: str, private_key: str, idempotency_key: str | None = None) -> Json:
|
|
209
|
+
"""Signs a closure or receipt payload locally with the operator's private key and records the countersignature."""
|
|
210
|
+
payload = signed["payload"]
|
|
211
|
+
path = f"closures/{payload['closure_id']}" if "closure_id" in payload else f"receipts/{payload['receipt_id']}"
|
|
212
|
+
return self.http.request("POST", f"/v1/{path}/countersign", {"key_id": key_id, "signature": countersign_payload(payload, private_key)}, idempotency_key)
|
|
213
|
+
|
|
214
|
+
# Metrics and keys
|
|
215
|
+
def product_metrics(self) -> Json:
|
|
216
|
+
return self.http.request("GET", "/v1/metrics/product")
|
|
217
|
+
|
|
218
|
+
def service_keys(self) -> Json:
|
|
219
|
+
return self.http.request("GET", "/v1/service/keys")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
# ---------- Provider-side client ----------
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class ReceiptLinkClient:
|
|
226
|
+
"""Provider-side access through a receipt link: no account, no API key, only the link's scope."""
|
|
227
|
+
|
|
228
|
+
def __init__(self, base_url: str, share_token: str, retries: int = 2, timeout: float = 30.0):
|
|
229
|
+
self.http = AtcnClient(base_url, "", retries=retries, timeout=timeout, share_token=share_token)
|
|
230
|
+
|
|
231
|
+
def current(self) -> Json:
|
|
232
|
+
return self.http.request("GET", "/v1/receipt-shares/current")
|
|
233
|
+
|
|
234
|
+
def verification(self, receipt_id: str) -> Json:
|
|
235
|
+
return self.http.request("GET", f"/v1/receipts/{receipt_id}/verification")
|
|
236
|
+
|
|
237
|
+
def respond(
|
|
238
|
+
self,
|
|
239
|
+
receipt: Json,
|
|
240
|
+
response_type: str,
|
|
241
|
+
fields: list[str] | None = None,
|
|
242
|
+
note: str | None = None,
|
|
243
|
+
evidence: list[Json] | None = None,
|
|
244
|
+
corrections: list[Json] | None = None,
|
|
245
|
+
signing: Json | None = None,
|
|
246
|
+
idempotency_key: str | None = None,
|
|
247
|
+
) -> Json:
|
|
248
|
+
"""receipt needs receipt_id, digest, and revision. signing needs binding_id, key_id, private_key, issuer_operator_id."""
|
|
249
|
+
provider_signature = None
|
|
250
|
+
if signing:
|
|
251
|
+
statement = build_response_statement({**receipt, "issuer_operator_id": signing["issuer_operator_id"]}, response_type, fields, note, evidence, corrections)
|
|
252
|
+
provider_signature = {"binding_id": signing["binding_id"], "key_id": signing["key_id"], "value": sign_statement(statement, signing["private_key"])}
|
|
253
|
+
body = {
|
|
254
|
+
"receipt_digest": receipt["digest"],
|
|
255
|
+
"receipt_revision": receipt["revision"],
|
|
256
|
+
"response_type": response_type,
|
|
257
|
+
"fields": fields or [],
|
|
258
|
+
"note": note,
|
|
259
|
+
"evidence": evidence or [],
|
|
260
|
+
"corrections": corrections or [],
|
|
261
|
+
"provider_signature": provider_signature,
|
|
262
|
+
}
|
|
263
|
+
return self.http.request("POST", f"/v1/receipts/{receipt['receipt_id']}/responses", body, idempotency_key)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ---------- Capture queue ----------
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class CaptureQueue:
|
|
270
|
+
"""Bounded local capture queue. enqueue() and flush() never raise, so a capture outage never stops the work.
|
|
271
|
+
|
|
272
|
+
Each operation keeps one idempotency key for its lifetime, so replays and retries create exactly one record.
|
|
273
|
+
Overflow policy: reject the newest operation and count it in `dropped`; older operations keep their order,
|
|
274
|
+
because later events (completions, charges) depend on earlier ones (tasks, delegations).
|
|
275
|
+
"""
|
|
276
|
+
|
|
277
|
+
def __init__(self, client: SubledgerClient, max_size: int = 1000, max_attempts: int = 5):
|
|
278
|
+
self.client = client
|
|
279
|
+
self.max_size = max_size
|
|
280
|
+
self.max_attempts = max_attempts
|
|
281
|
+
self._pending: list[Json] = []
|
|
282
|
+
self._failed: list[Json] = []
|
|
283
|
+
self._dropped = 0
|
|
284
|
+
self._sequence = 0
|
|
285
|
+
|
|
286
|
+
@property
|
|
287
|
+
def dropped(self) -> int:
|
|
288
|
+
return self._dropped
|
|
289
|
+
|
|
290
|
+
@property
|
|
291
|
+
def size(self) -> int:
|
|
292
|
+
return len(self._pending)
|
|
293
|
+
|
|
294
|
+
def enqueue(self, path: str, body: Any, idempotency_key: str | None = None) -> bool:
|
|
295
|
+
"""Queues one mutation. Returns False (and counts a drop) when the queue is full; never raises."""
|
|
296
|
+
if len(self._pending) >= self.max_size:
|
|
297
|
+
self._dropped += 1
|
|
298
|
+
return False
|
|
299
|
+
self._sequence += 1
|
|
300
|
+
self._pending.append(
|
|
301
|
+
{
|
|
302
|
+
"id": f"op_{int(time.time() * 1000)}_{self._sequence}",
|
|
303
|
+
"method": "POST",
|
|
304
|
+
"path": path,
|
|
305
|
+
"body": body,
|
|
306
|
+
"idempotencyKey": idempotency_key or stable_key("capture", str(uuid.uuid4())),
|
|
307
|
+
"enqueued_at": datetime.now(timezone.utc).isoformat(),
|
|
308
|
+
"attempts": 0,
|
|
309
|
+
"last_error": None,
|
|
310
|
+
}
|
|
311
|
+
)
|
|
312
|
+
return True
|
|
313
|
+
|
|
314
|
+
def task(self, task: Json) -> bool:
|
|
315
|
+
return self.enqueue("/v1/tasks", task, stable_key("task", task["external_ref"]))
|
|
316
|
+
|
|
317
|
+
def delegation(self, task_ref: str, delegation: Json) -> bool:
|
|
318
|
+
key = stable_key("delegation", delegation["external_ref"]) if delegation.get("external_ref") else None
|
|
319
|
+
return self.enqueue(f"/v1/tasks/{_path(task_ref)}/delegations", delegation, key)
|
|
320
|
+
|
|
321
|
+
def delegation_event(self, delegation_ref: str, event: Json, idempotency_key: str | None = None) -> bool:
|
|
322
|
+
return self.enqueue(f"/v1/delegations/{_path(delegation_ref)}/events", event, idempotency_key)
|
|
323
|
+
|
|
324
|
+
def financial_event(self, event: Json) -> bool:
|
|
325
|
+
return self.enqueue("/v1/financial-events", event, stable_key("financial", event["source"], event["source_event_id"]))
|
|
326
|
+
|
|
327
|
+
def flush(self) -> Json:
|
|
328
|
+
"""Sends queued operations in order. A retryable failure (network, 5xx, 429) stops the flush and keeps the
|
|
329
|
+
operation; a non-retryable rejection moves it to the failed list. Never raises."""
|
|
330
|
+
sent = 0
|
|
331
|
+
failed = 0
|
|
332
|
+
while self._pending:
|
|
333
|
+
op = self._pending[0]
|
|
334
|
+
op["attempts"] += 1
|
|
335
|
+
try:
|
|
336
|
+
self.client.http.request(op["method"], op["path"], op["body"], op["idempotencyKey"])
|
|
337
|
+
self._pending.pop(0)
|
|
338
|
+
sent += 1
|
|
339
|
+
except Exception as error: # noqa: BLE001 - a capture failure must never stop the caller's work
|
|
340
|
+
op["last_error"] = str(error)
|
|
341
|
+
retryable = not isinstance(error, AtcnApiError) or error.retryable
|
|
342
|
+
if retryable and op["attempts"] < self.max_attempts:
|
|
343
|
+
break
|
|
344
|
+
self._failed.append(self._pending.pop(0))
|
|
345
|
+
failed += 1
|
|
346
|
+
return {"sent": sent, "failed": failed, "remaining": len(self._pending)}
|
|
347
|
+
|
|
348
|
+
def failed_operations(self) -> list[Json]:
|
|
349
|
+
return list(self._failed)
|
|
350
|
+
|
|
351
|
+
def export_failed(self) -> str:
|
|
352
|
+
"""Failed operations as JSON lines (same format as the TypeScript SDK), for replay after the cause is fixed."""
|
|
353
|
+
return "\n".join(json.dumps(op) for op in self._failed)
|
|
354
|
+
|
|
355
|
+
def replay(self, json_lines: str) -> int:
|
|
356
|
+
"""Puts exported operations back in the queue with their original idempotency keys."""
|
|
357
|
+
replayed: set[str] = set()
|
|
358
|
+
for line in json_lines.splitlines():
|
|
359
|
+
if not line.strip():
|
|
360
|
+
continue
|
|
361
|
+
op = json.loads(line)
|
|
362
|
+
if self.enqueue(op["path"], op["body"], op["idempotencyKey"]):
|
|
363
|
+
replayed.add(op["idempotencyKey"])
|
|
364
|
+
self._failed = [op for op in self._failed if op["idempotencyKey"] not in replayed]
|
|
365
|
+
return len(replayed)
|
|
366
|
+
|
|
367
|
+
def report_gaps(self, task_ref: str) -> bool:
|
|
368
|
+
"""Reports drops and permanent failures for a task as capture gaps (marks its lineage incomplete). Never raises."""
|
|
369
|
+
if self._dropped == 0 and not self._failed:
|
|
370
|
+
return True
|
|
371
|
+
detail = f"{self._dropped} capture operation(s) dropped by queue overflow; {len(self._failed)} failed permanently"
|
|
372
|
+
try:
|
|
373
|
+
self.client.report_capture_gap(task_ref, "queue_overflow" if self._dropped > 0 else "capture_failed", detail)
|
|
374
|
+
return True
|
|
375
|
+
except Exception: # noqa: BLE001
|
|
376
|
+
return False
|
atcn/usage.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Opt-in anonymous usage reporting: the saved choice (the same file the TypeScript SDK uses) and the sender.
|
|
2
|
+
|
|
3
|
+
The SDK client never reports anything; only `python -m atcn init` does, after an explicit yes.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import urllib.request
|
|
9
|
+
import uuid
|
|
10
|
+
from collections.abc import Callable, Mapping
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
# The ATCN-operated collector. There is none yet, so reports are only sent when ATCN_USAGE_URL is set.
|
|
16
|
+
DEFAULT_USAGE_URL: str | None = None
|
|
17
|
+
|
|
18
|
+
CONSENT_QUESTION = "Share anonymous usage metrics to help improve ATCN?"
|
|
19
|
+
CONSENT_EXPLANATION = "\n".join(
|
|
20
|
+
[
|
|
21
|
+
"If you answer yes, this machine sends: a random installation ID, the event (integration initialized, task closed,",
|
|
22
|
+
"closure verified, exception resolved), a timestamp, the SDK version, whether it was a demo, and counts of",
|
|
23
|
+
"delegations and charges. Never task data, references, amounts, names, or keys.",
|
|
24
|
+
"Change your answer with `python -m atcn init`, or turn reporting off with ATCN_USAGE_DISABLED=1. Details: docs/USAGE_DATA.md",
|
|
25
|
+
]
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
Env = Mapping[str, str]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _now() -> str:
|
|
32
|
+
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _is_set(value: str | None) -> bool:
|
|
36
|
+
return value is not None and value != "" and value != "0" and value.lower() != "false"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def settings_path(env: Env | None = None) -> Path:
|
|
40
|
+
env = os.environ if env is None else env
|
|
41
|
+
config_dir = env.get("ATCN_CONFIG_DIR") or str(Path.home() / ".config" / "atcn")
|
|
42
|
+
return Path(config_dir) / "usage.json"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def read_usage_settings(env: Env | None = None) -> dict[str, Any] | None:
|
|
46
|
+
path = settings_path(env)
|
|
47
|
+
if not path.exists():
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
return json.loads(path.read_text())
|
|
51
|
+
except (OSError, ValueError):
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def save_usage_choice(share_usage: bool, env: Env | None = None) -> dict[str, Any]:
|
|
56
|
+
"""Saves an explicit choice. Opting in keeps an existing installation ID or creates a random one; opting out deletes it."""
|
|
57
|
+
previous = read_usage_settings(env) or {}
|
|
58
|
+
settings = {
|
|
59
|
+
"share_usage": share_usage,
|
|
60
|
+
"installation_id": (previous.get("installation_id") or str(uuid.uuid4())) if share_usage else None,
|
|
61
|
+
"decided_at": _now(),
|
|
62
|
+
}
|
|
63
|
+
path = settings_path(env)
|
|
64
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
path.write_text(json.dumps(settings, indent=2) + "\n")
|
|
66
|
+
return settings
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def disabled_by(env: Env | None = None) -> str | None:
|
|
70
|
+
"""The environment variable that turns reporting off, if one is set. It wins over any saved choice."""
|
|
71
|
+
env = os.environ if env is None else env
|
|
72
|
+
for name in ("ATCN_USAGE_DISABLED", "DO_NOT_TRACK"):
|
|
73
|
+
if _is_set(env.get(name)):
|
|
74
|
+
return name
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def usage_status(env: Env | None = None) -> dict[str, Any]:
|
|
79
|
+
"""Reporting is on only after an explicit yes, and ATCN_USAGE_DISABLED or DO_NOT_TRACK always turn it off."""
|
|
80
|
+
env = os.environ if env is None else env
|
|
81
|
+
url = env.get("ATCN_USAGE_URL") or DEFAULT_USAGE_URL
|
|
82
|
+
|
|
83
|
+
def off(reason: str) -> dict[str, Any]:
|
|
84
|
+
return {"enabled": False, "reason": reason, "installation_id": None, "url": url}
|
|
85
|
+
|
|
86
|
+
variable = disabled_by(env)
|
|
87
|
+
if variable:
|
|
88
|
+
return off(f"off: {variable} is set")
|
|
89
|
+
settings = read_usage_settings(env)
|
|
90
|
+
if settings is None:
|
|
91
|
+
return off("off: not chosen yet (run python -m atcn init)")
|
|
92
|
+
if not settings.get("share_usage") or not settings.get("installation_id"):
|
|
93
|
+
return off("off: you chose not to share usage metrics")
|
|
94
|
+
if not url:
|
|
95
|
+
return off("off until a collector is configured (set ATCN_USAGE_URL)")
|
|
96
|
+
return {"enabled": True, "reason": f"on: sharing anonymous usage metrics with {url}", "installation_id": settings["installation_id"], "url": url}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def send_usage_report(event: dict[str, Any], env: Env | None = None, timeout: float = 2.0) -> bool:
|
|
100
|
+
"""Sends one report if the user opted in, adding the installation ID and timestamp. Never raises."""
|
|
101
|
+
status = usage_status(env)
|
|
102
|
+
if not status["enabled"]:
|
|
103
|
+
return False
|
|
104
|
+
report = {"installation_id": status["installation_id"], "occurred_at": _now(), **event}
|
|
105
|
+
request = urllib.request.Request(status["url"], data=json.dumps(report).encode("utf-8"), method="POST", headers={"content-type": "application/json"})
|
|
106
|
+
try:
|
|
107
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
108
|
+
return 200 <= response.status < 300
|
|
109
|
+
except Exception:
|
|
110
|
+
return False
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def ask_to_share_usage(read_line: Callable[[str], str] = input, write: Callable[[str], Any] = print, env: Env | None = None) -> bool | None:
|
|
114
|
+
"""Asks the question and saves the answer. Only y/yes or n/no count; anything else asks again.
|
|
115
|
+
|
|
116
|
+
Returns None, saving nothing, if the input ends before an answer.
|
|
117
|
+
"""
|
|
118
|
+
write(CONSENT_EXPLANATION)
|
|
119
|
+
while True:
|
|
120
|
+
try:
|
|
121
|
+
answer = read_line(f"{CONSENT_QUESTION} [y/n] ").strip().lower()
|
|
122
|
+
except EOFError:
|
|
123
|
+
return None
|
|
124
|
+
if answer in ("y", "yes"):
|
|
125
|
+
return save_usage_choice(True, env)["share_usage"]
|
|
126
|
+
if answer in ("n", "no"):
|
|
127
|
+
return save_usage_choice(False, env)["share_usage"]
|
atcn/webhooks.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Webhook signature verification (header: ATCN-Signature: t=..,key_id=..,key_version=..,sig=..)."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
from .crypto import sign_bytes, verify_bytes
|
|
7
|
+
|
|
8
|
+
WEBHOOK_SIGNATURE_HEADER = "atcn-signature"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class WebhookVerification:
|
|
13
|
+
valid: bool
|
|
14
|
+
reason: str | None = None
|
|
15
|
+
key_id: str | None = None
|
|
16
|
+
key_version: int | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def parse_webhook_header(header: str) -> dict[str, str]:
|
|
20
|
+
parts: dict[str, str] = {}
|
|
21
|
+
for item in header.split(","):
|
|
22
|
+
name, sep, value = item.partition("=")
|
|
23
|
+
if sep:
|
|
24
|
+
parts[name.strip()] = value.strip()
|
|
25
|
+
return parts
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def sign_webhook(body: str, key_id: str, key_version: int, private_key: str, timestamp: int | None = None) -> str:
|
|
29
|
+
t = int(time.time()) if timestamp is None else timestamp
|
|
30
|
+
sig = sign_bytes(f"{t}.{body}".encode("utf-8"), private_key)
|
|
31
|
+
return f"t={t},key_id={key_id},key_version={key_version},sig={sig}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def verify_webhook(body: str, header: str, public_key: str, tolerance_seconds: int = 300, now: int | None = None) -> WebhookVerification:
|
|
35
|
+
"""Verifies the raw request body against the header using the published ATCN service key."""
|
|
36
|
+
parts = parse_webhook_header(header)
|
|
37
|
+
if "t" not in parts or "sig" not in parts or not parts["t"].lstrip("-").isdigit():
|
|
38
|
+
return WebhookVerification(False, "malformed_header")
|
|
39
|
+
timestamp = int(parts["t"])
|
|
40
|
+
current = int(time.time()) if now is None else now
|
|
41
|
+
if abs(current - timestamp) > tolerance_seconds:
|
|
42
|
+
return WebhookVerification(False, "timestamp_outside_tolerance")
|
|
43
|
+
if not verify_bytes(f"{timestamp}.{body}".encode("utf-8"), parts["sig"], public_key):
|
|
44
|
+
return WebhookVerification(False, "bad_signature")
|
|
45
|
+
return WebhookVerification(True, None, parts.get("key_id"), int(parts.get("key_version", "0")))
|
|
@@ -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.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
atcn/__init__.py,sha256=DrC9q_powW-Dj6ufCycx7vFMzNFRDy3Uy6TiA_WYx4E,1401
|
|
2
|
+
atcn/__main__.py,sha256=GBFOEIx7_L1fJ1_gP4iaMbrZALvPxrnNufXybDX7rWQ,1771
|
|
3
|
+
atcn/canonical.py,sha256=SxEQIm0eqsjJOYRHIr9W9rUCudvPLfD8c57Dtlq39_A,1538
|
|
4
|
+
atcn/client.py,sha256=k7uymK0qvi8ea8qzm_gaLMq8gr8GKqSRTMUeXDfayxU,6320
|
|
5
|
+
atcn/crypto.py,sha256=w6Um9EKDph26yWSuZqjYoi2UhYBh9v3K0ydOZhf8i3c,2725
|
|
6
|
+
atcn/events.py,sha256=wz5pRzkXtlQ6vs2YmPSJSTQ93V0sPS3G_9oTRWdXCOA,2793
|
|
7
|
+
atcn/ids.py,sha256=0H5BgjjrBdPRI1efOFlOP_OhDHV9budh0YM8r44fivc,725
|
|
8
|
+
atcn/subledger.py,sha256=7Hz3JU9RoU4lHLrbkba5P7pl8EsC3ficg93gRKbWdF4,20165
|
|
9
|
+
atcn/usage.py,sha256=A4OpWjVHjTrvjTH9kAELygQJPDEm5CqLF_XTnaWA0gc,5291
|
|
10
|
+
atcn/webhooks.py,sha256=JcKF3xdoPKplqgSSYQ14yj87_I07-tVPZZz3VTSGGoY,1847
|
|
11
|
+
atcn-1.3.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
12
|
+
atcn-1.3.0.dist-info/METADATA,sha256=mOzWhiEnWKS5R3-3FGrqOtmrwj49sWY3wNMX-z5p_XQ,2016
|
|
13
|
+
atcn-1.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
14
|
+
atcn-1.3.0.dist-info/top_level.txt,sha256=9hXjjNYfYciBocVulEJW1qUxz-JrGh2xsdNdnA9nzfo,5
|
|
15
|
+
atcn-1.3.0.dist-info/RECORD,,
|
|
@@ -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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
atcn
|