Merged
sync(A4P/java): 同步 A4P java sdk 实现与编译脚本到 develop 分支 #364
sync(A4P/java): 同步 A4P java sdk 实现与编译脚本到 develop 分支 #364
Merged
machuanAdd on 20 days ago
Total: 63 files changed+7158-2
@@ -0,0 +1,14 @@
1+.git
2+.idea
3+.hvigor
4+**/.hvigor
5+**/oh_modules
6+**/build
7+**/.test
8+**/local.properties
9+**/*.p12
10+**/*.p7b
11+**/*.cer
12+dist
13+test-reports
14+*.log
@@ -0,0 +1,31 @@
1+# Build from the SDK root with -f docker/Dockerfile.
2+# Download Linux HarmonyOS 26.0.0 Command Line Tools from a ZIP archive.
3+# Replace the placeholder URL below or override COMMAND_LINE_TOOLS_URL.
4+ARG BASE_IMAGE=ubuntu:24.04
5+FROM ${BASE_IMAGE} AS toolchain
6+ 
7+# libgl1 is needed by the SDK resource compiler; lsof by the local UT runner.
8+RUN apt-get update \
9+ && apt-get install -y --no-install-recommends \
10+ ca-certificates curl unzip git openjdk-17-jdk-headless libatomic1 libglib2.0-0 \
11+ libx11-6 libxext6 libxi6 libxrender1 libxtst6 libgl1 lsof \
12+ && rm -rf /var/lib/apt/lists/*
13+RUN ln -s "$(dirname "$(dirname "$(readlink -f /usr/bin/javac)")")" /opt/java
14+ 
15+# Placeholder: replace with the actual Linux Command Line Tools ZIP URL.
16+ARG COMMAND_LINE_TOOLS_URL=https://openjiuwen-ci.obs.cn-north-4.myhuaweicloud.com/agent-protocol/tools/commandline-tools-linux-x64-26.0.0.851.zip
17+RUN curl --fail --location --retry 3 "${COMMAND_LINE_TOOLS_URL}" -o /tmp/command-line-tools.zip \
18+ && unzip -q /tmp/command-line-tools.zip -d /opt \
19+ && rm /tmp/command-line-tools.zip \
20+ && test -d /opt/command-line-tools/bin \
21+ && test -d /opt/command-line-tools/tool/node \
22+ && test -d /opt/command-line-tools/sdk
23+ENV DEVECO_SDK_HOME=/opt/command-line-tools/sdk \
24+ OHOS_BASE_SDK_HOME=/opt/command-line-tools/sdk/default/openharmony \
25+ NODE_HOME=/opt/command-line-tools/tool/node \
26+ JAVA_HOME=/opt/java
27+ENV PATH="/opt/command-line-tools/bin:/opt/command-line-tools/tool/node/bin:/opt/java/bin:${PATH}"
28+ 
29+# Mount the SDK source here when running build or test commands.
30+WORKDIR /workspace
31+CMD ["bash"]
@@ -0,0 +1,71 @@
1+# ArkTS Build and Test Environment
2+ 
3+English | [简体中文](README_zh.md)
4+ 
5+This Dockerfile creates a reusable HarmonyOS 26.0.0 build environment image. Building the image installs system dependencies and downloads and extracts the toolchain. It does not copy project sources, install project dependencies, compile the project, or run unit tests. Mount the source directory when running a container to build or test the project.
6+ 
7+## Build the environment image
8+ 
9+Install Docker Buildx. The build automatically downloads and extracts **Linux x86_64 HarmonyOS 26.0.0 Command Line Tools** from the URL configured in the Dockerfile. No external toolchain package or download URL is required.
10+ 
11+Official toolchain documentation: <https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-commandline-get>
12+ 
13+Run all commands below from the `A4P-arkts-sdk` root directory in a Linux / Bash environment:
14+ 
15+```sh
16+docker buildx build \
17+ -f docker/Dockerfile \
18+ --load -t a4p-arkts-builder .
19+```
20+ 
21+The default target is the build and test environment; `--target` is optional. You can also select it explicitly with `--target toolchain`. The `--load` option loads the image into local Docker for subsequent `docker run` commands.
22+ 
23+The image includes JDK 17, OpenGL runtime libraries, and `lsof`. Node, OHPM, and Hvigor use the versions bundled with the toolchain. To use an alternative base image registry, pass `--build-arg BASE_IMAGE=<registry>/library/ubuntu:24.04`. Building the image requires access to the Ubuntu package repositories and the toolchain download URL. Project dependencies are installed from the OHPM / Hvigor repositories when the container runs.
24+ 
25+## Build with the existing script
26+ 
27+```sh
28+docker run --rm \
29+ -v "$PWD:/workspace" \
30+ a4p-arkts-builder \
31+ bash scripts/build.sh
32+```
33+ 
34+The script installs dependencies, cleans previous outputs, and builds a release HAR and an on-device test HAP. It packages the device tests without executing test cases.
35+ 
36+Outputs are written back to the host:
37+ 
38+- HAR: `a4p/build/default/outputs/default/a4p.har`
39+- On-device test HAP: the `.hap` file under `a4p/build/default/outputs/ohosTest/`
40+ 
41+## Build only the HAR
42+ 
43+```sh
44+docker run --rm \
45+ -v "$PWD:/workspace" \
46+ a4p-arkts-builder \
47+ bash -c 'ohpm install --all &&
48+ hvigorw --mode module -p product=default -p module=a4p@default \
49+ -p buildMode=release assembleHar --no-daemon'
50+```
51+ 
52+## Run local unit tests
53+ 
54+```sh
55+docker run --rm \
56+ -v "$PWD:/workspace" \
57+ a4p-arkts-builder \
58+ bash -c 'ohpm install --all &&
59+ hvigorw --mode module -p product=default -p module=a4p@default \
60+ test --no-daemon --stacktrace'
61+```
62+ 
63+This command runs local tests in `a4p/src/test` and requires the SDK Previewer component. Reports are typically written to `a4p/.test/` and retained on the host through the mounted source directory. Tests in `a4p/src/ohosTest` additionally require a HarmonyOS device or a compatible emulator to execute.
64+ 
65+## Open an interactive container
66+ 
67+```sh
68+docker run --rm -it -v "$PWD:/workspace" a4p-arkts-builder
69+```
70+ 
71+The container starts Bash in `/workspace`. You can run `ohpm`, `hvigorw`, or project scripts manually. The container runs as root by default, so newly generated files in the mounted directory are typically owned by root.
@@ -0,0 +1,71 @@
1+# ArkTS 构建与测试环境
2+ 
3+[English](README.md) | 简体中文
4+ 
5+此 Dockerfile 生成可重复使用的 HarmonyOS 26.0.0 构建环境镜像。镜像构建时仅安装系统依赖并下载解压工具链,不复制工程源码、不安装工程依赖、不执行工程编译或 UT。启动容器后,通过挂载源码运行构建或测试命令。
6+ 
7+## 构建环境镜像
8+ 
9+准备 Docker Buildx。构建时会自动从 Dockerfile 中已配置的下载地址获取并解压 **Linux x86_64 HarmonyOS 26.0.0 Command Line Tools**,无需额外提供工具包或下载地址。
10+ 
11+官方工具链说明:<https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-commandline-get>
12+ 
13+以下命令均在 `A4P-arkts-sdk` 根目录、Linux / Bash 环境执行:
14+ 
15+```sh
16+docker buildx build \
17+ -f docker/Dockerfile \
18+ --load -t a4p-arkts-builder .
19+```
20+ 
21+不需要指定 `--target`;默认镜像即为构建与测试环境,也可显式指定 `--target toolchain`。`--load` 将镜像加载到本地 Docker,供后续 `docker run` 使用。
22+ 
23+镜像包含 JDK 17、OpenGL 运行库、`lsof`,Node、OHPM、Hvigor 使用工具包内的版本。可用 `--build-arg BASE_IMAGE=<镜像源>/library/ubuntu:24.04` 指定基础镜像源。构建镜像需要访问 Ubuntu 软件源和工具包下载地址;工程依赖在容器运行时从 OHPM / Hvigor 仓库安装。
24+ 
25+## 使用现有脚本构建
26+ 
27+```sh
28+docker run --rm \
29+ -v "$PWD:/workspace" \
30+ a4p-arkts-builder \
31+ bash scripts/build.sh
32+```
33+ 
34+该脚本会安装依赖、清理旧输出,然后构建 release HAR 和设备测试 HAP。它只打包设备测试,不执行测试用例。
35+ 
36+产物写回宿主机:
37+ 
38+- HAR:`a4p/build/default/outputs/default/a4p.har`
39+- 设备测试 HAP:`a4p/build/default/outputs/ohosTest/` 下的 `.hap` 文件
40+ 
41+## 仅构建 HAR
42+ 
43+```sh
44+docker run --rm \
45+ -v "$PWD:/workspace" \
46+ a4p-arkts-builder \
47+ bash -c 'ohpm install --all &&
48+ hvigorw --mode module -p product=default -p module=a4p@default \
49+ -p buildMode=release assembleHar --no-daemon'
50+```
51+ 
52+## 运行本地 UT
53+ 
54+```sh
55+docker run --rm \
56+ -v "$PWD:/workspace" \
57+ a4p-arkts-builder \
58+ bash -c 'ohpm install --all &&
59+ hvigorw --mode module -p product=default -p module=a4p@default \
60+ test --no-daemon --stacktrace'
61+```
62+ 
63+该命令运行 `a4p/src/test` 本地测试,依赖 SDK 中的 Previewer 组件。报告通常位于 `a4p/.test/`,通过挂载目录保留在宿主机。业务测试位于 `a4p/src/ohosTest`,执行这些测试还需要 HarmonyOS 设备或兼容模拟器。
64+ 
65+## 进入交互式容器
66+ 
67+```sh
68+docker run --rm -it -v "$PWD:/workspace" a4p-arkts-builder
69+```
70+ 
71+容器默认在 `/workspace` 中启动 Bash,可手动运行 `ohpm`、`hvigorw` 或工程脚本。默认使用 root,挂载目录中新生成的文件通常归 root 所有。
@@ -0,0 +1 @@
1+build.sh text eol=lf
@@ -0,0 +1 @@
1+/target/
@@ -0,0 +1,325 @@
1+# A4P Java SDK
2+ 
3+English | [简体中文](./README_zh.md)
4+ 
5+Java 17 implementation of the A4P payment-intent protocol, ported from the ArkTS SDK in
6+[PR #130](https://github.com/openJiuwen-ai/agent-protocol/pull/130).
7+ 
8+## Build and test
9+ 
10+Requirements: JDK 17 or later, Maven 3.9 or later.
11+ 
12+```sh
13+cd A4P-java-sdk
14+mvn test
15+mvn package
16+```
17+ 
18+### Build script
19+ 
20+The scripts require Bash (for example, Linux, WSL or Git Bash on Windows). From the
21+repository root, run:
22+ 
23+```sh
24+bash A4P-java-sdk/scripts/build.sh # Default: build
25+bash A4P-java-sdk/scripts/build.sh build # Explicit build mode
26+bash A4P-java-sdk/scripts/build.sh ut # Run unit tests only
27+bash A4P-java-sdk/scripts/build.sh --help
28+```
29+ 
30+`build` runs `clean package` with `-Dmaven.test.skip=true`, skipping both test
31+compilation and execution. The JAR is written to
32+`A4P-java-sdk/target/a4p-java-sdk-0.1.0.jar`. `ut` runs `clean test`, requires tests to
33+be present and fails on test failures; it does not package the JAR. Surefire reports
34+are written to `A4P-java-sdk/target/surefire-reports/`. Both modes clean `target/`
35+before running and return Maven's exit code.
36+ 
37+Additional Maven options go after the mode, for example:
38+ 
39+```sh
40+bash A4P-java-sdk/scripts/build.sh build -o
41+bash A4P-java-sdk/scripts/build.sh ut -Dtest=Rsa3072Test
42+```
43+ 
44+`-o` uses Maven's offline mode, so the required dependencies and plugins must already
45+be cached. The script locates `pom.xml` relative to itself, independently of the
46+caller's working directory.
47+ 
48+### UT script with CI reports
49+ 
50+To run unit tests and generate CI reports, execute the following from the repository
51+root. The script locates the repository root relative to itself, independently of
52+the caller's working directory. Optionally set `WORKSPACE` to an absolute repository
53+root to override this default.
54+ 
55+```sh
56+bash A4P-java-sdk/scripts/ut.sh
57+```
58+ 
59+This script requires Git, Maven and standard shell utilities, including `grep` with
60+`-P` support (for example, GNU grep). It runs `mvn clean test` and returns Maven's
61+exit code (`0` for `PASS`, nonzero for `FAILED`). Reports are written under
62+`outputs/` under the resolved repository root (`$WORKSPACE/outputs/` when overridden):
63+ 
64+| File | Contents |
65+| --- | --- |
66+| `ut.log` | Maven test log |
67+| `unit_test_report.html` | Test counts and the last 200 log lines |
68+| `junit.xml` | Combined JUnit XML, generated when Surefire XML reports exist |
69+| `ut.json` | Status, Maven exit code and report link |
70+ 
71+Optional environment variables `PR_ID` (default `0`) and `OBS_BUCKET` (default
72+`openjiuwen-ci`) control the report link in `ut.json`. The script generates local
73+reports; uploading them to the linked OBS location is a separate CI step.
74+ 
75+The artifact coordinates are `io.openjiuwen:a4p-java-sdk:0.1.0`.
76+Jackson handles JSON; JUnit 5 is test-only. No web framework is required.
77+ 
78+`jackson-databind` (2.20.1 here) is the only runtime dependency; JUnit 5 is `test` scope.
79+ 
80+```xml
81+<dependency>
82+ <groupId>io.openjiuwen</groupId>
83+ <artifactId>a4p-java-sdk</artifactId>
84+ <version>0.1.0</version>
85+</dependency>
86+```
87+ 
88+Run `io.openjiuwen.a4p.examples.PaymentExample` from an IDE, or:
89+ 
90+```sh
91+mvn compile org.codehaus.mojo:exec-maven-plugin:3.6.3:java "-Dexec.mainClass=io.openjiuwen.a4p.examples.PaymentExample"
92+```
93+ 
94+The exec plugin is not declared in `pom.xml`, so that command resolves it from Maven
95+Central on first use and therefore needs network access.
96+ 
97+The example uses separate agent, intent-center and user RSA-3072 key pairs. It creates,
98+issues, authorizes, activates, verifies, reserves and completes a payment.
99+ 
100+## API
101+ 
102+| Specification | Java |
103+| --- | --- |
104+| `createIntent` | `A4p.createIntent(CreateIntentRequest, Signer[, long now])` returns `A4pResult<IntentL1>` |
105+| `issueIntent` | `A4p.issueIntent(IntentL1, SignatureVerifier, IntentIssueContext, Signer[, long now])` returns `A4pResult<IntentL2>` |
106+| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, long now])` returns `A4pResult<IntentL3>` |
107+| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, long now])` returns `A4pResult<IntentExecutionContext>` |
108+| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` returns `A4pResult<VerificationResult>` |
109+| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext)` returns `A4pResult<IntentExecutionContext>` |
110+| `createExecution / completeExecution / cancelExecution` | Static methods on `A4p`, returning `A4pResult<IntentExecutionContext>` |
111+| `A4pResult<T>` | `A4pResult`: `success()`, `data()`, `code()` (`long`), `message()` |
112+| `A4pException` | `A4pException`, thrown only by value-returning helpers and for SDK defects |
113+| `A4pErrorCode` | `code()`, `message()`, and `fromCode(int)` for turning a result code back into a constant |
114+| `A4pIntentCodec` | `A4pIntentCodec.standard()`; `serializeIntentL1/L2/L3` and `serializeIntentExecutionContext` return `String`, and each `deserialize…` counterpart returns `A4pResult` |
115+| `Signer / SignatureVerifier` | Functional interfaces; `Signer.sign(byte[])` returns a `SignatureInfo` |
116+| `Rsa3072` | Optional adapter: `Rsa3072.signer(String, PrivateKey)` and `Rsa3072.verifier(Map<String, PublicKey>)` |
117+| `CanonicalJson` | Canonical helpers used when signing: `stringify`, `toSignableBytes`, `encodeUtf8`/`decodeUtf8`, `base64UrlEncode`/`base64UrlDecode`, `MAX_SAFE_INTEGER` |
118+| Typed union (`StructuredIntent`, `Execution`, `executionInfo`) | `JsonNode` payloads; `PaymentProfile` converts AI_PAY payloads to and from records |
119+| Data model | Immutable records and enums in `Models` |
120+ 
121+`[long now]` marks the explicit-clock overload described below.
122+ 
123+The records and enums are nested in `Models`; `A4p`, `A4pResult`, `A4pException`,
124+`A4pErrorCode`, `A4pIntentCodec`, `IntentExecutionContext`, `PaymentProfile` and `Rsa3072`
125+are top-level classes, so both imports are needed:
126+ 
127+```java
128+import io.openjiuwen.a4p.*;
129+import io.openjiuwen.a4p.Models.*;
130+```
131+ 
132+Build AI_PAY payloads through `PaymentProfile`. The sketch below shows the shape of the
133+calls; `io.openjiuwen.a4p.examples.PaymentExample` is the complete, compiling version,
134+which also sets up the key pairs, the L1/L2/L3 chain and canonical serialization.
135+ 
136+```java
137+// Activate an intent that the agent created and the intent center issued and signed.
138+SignatureVerifier userVerifier = Rsa3072.verifier(Map.of("user", userPublicKey));
139+A4pResult<IntentExecutionContext> activated = A4p.activateIntent(authorizedIntent, userVerifier, now);
140+if (!activated.success()) { /* branch on activated.code() */ }
141+IntentExecutionContext context = activated.data();
142+ 
143+// Reserve, then complete, one order against the activated intent.
144+Order order = new Order("order-1", 3000L, "CNY", List.of(new CartItem(product, 1L)), now);
145+Execution execution = PaymentProfile.execution("execution-1", "1.0", order);
146+A4pResult<IntentExecutionContext> reserved = A4p.createExecution(context, execution, now);
147+if (!reserved.success()) { /* branch on reserved.code(), then persist the context */ }
148+A4pResult<IntentExecutionContext> completed = A4p.completeExecution(context, execution.id(), now);
149+ 
150+PaymentExecutionInfo info = PaymentProfile.executionInfo(context);
151+```
152+ 
153+A failed `createExecution` can still have moved the context to `EXPIRED`, so persist the
154+context after every call. `serializeIntentExecutionContext` /
155+`deserializeIntentExecutionContext`
156+on `A4pIntentCodec` provide the persisted form; deserialization re-validates the stored L3
157+(without re-verifying the user signature), checks that the ledger respects the authorized
158+constraints, and requires `executionInfo` to match the ledger. It also requires a reachable
159+state: each `reservedAt` lies within `[validFrom, validUntil]`, `completedAt`/`canceledAt`
160+are not earlier than `reservedAt`, and the status is `CONSUMED` exactly when nothing is
161+pending and the global quota is used up (`REVOKED` and `EXPIRED` accept any ledger).
162+ 
163+Optional fields use `null`; absent optional fields are omitted from signed JSON. Explicit
164+`null` values inside AI_PAY payloads are rejected. Monetary values are positive integers in
165+the application's agreed minor unit. All protocol numbers are integers limited to the
166+JavaScript safe-integer range; values that are not integers must be carried as strings.
167+ 
168+Lifecycle/execution methods have both a system-clock overload and an explicit
169+`long now` overload (epoch milliseconds). An explicit `now` must be a non-negative
170+safe integer and is validated before anything else. Production code must supply a
171+trusted clock, never a client-provided timestamp. Order timestamps do not determine
172+quota periods or authorization validity.
173+ 
174+Required strings must be non-blank (using the JavaScript `trim()` whitespace set). A
175+product needs a non-blank seller ID and at least one of `spuId`/`skuId`. A periodic rule
176+requires `anchorTime <= validFrom` and `periodSeconds <= 9007199254740`. Chain timestamps
177+are monotonic: `L1.timestamp <= L2.timestamp <= L3.timestamp`. Activation requires
178+`L3.timestamp <= now <= validUntil` (`A4P_INVALID_PARAMETER` / `A4P_TIMESTAMP_EXPIRED`); an
179+intent that is not yet valid can be activated, and reservations before `validFrom` fail with
180+`A4P_TIMESTAMP_TOO_EARLY`. Length limits and
181+sensitive-data filtering of `intentConversation` are the Agent's responsibility.
182+ 
183+### Result codes
184+ 
185+Callers branch on `code()`; `message()` is a fixed diagnostic text, and the values come
186+from `A4pErrorCode`, shared with the ArkTS SDK. `0` means success and every other value is
187+a protocol failure. `A4pErrorCode.fromCode(int)` resolves a code back to its constant and
188+maps an unknown value to `A4P_INTERNAL_ERROR` (cast the `long` returned by `code()`).
189+ 
190+| Code | Constant | Meaning |
191+| --- | --- | --- |
192+| 0 | `A4P_SUCCESS` | Operation completed successfully |
193+| 1001 | `A4P_INVALID_PARAMETER` | Invalid parameter |
194+| 1002 | `A4P_UNSUPPORTED_VERSION` | Unsupported version |
195+| 1003 | `A4P_DUPLICATE_ID` | Duplicate ID |
196+| 2001 | `A4P_SIGNING_FAIL` | Signing failed |
197+| 2002 | `A4P_VERIFY_FAIL` | Verification failed |
198+| 3001 | `A4P_INVALID_STATUS` | Invalid status |
199+| 3002 | `A4P_TIMESTAMP_EXPIRED` | Timestamp expired |
200+| 3003 | `A4P_TIMESTAMP_TOO_EARLY` | Timestamp too early |
201+| 4001 | `A4P_EXECUTION_COUNT_EXCEEDED` | Execution count exceeded |
202+| 4002 | `A4P_AMOUNT_EXCEEDED` | Amount exceeded |
203+| 4003 | `A4P_PERIOD_COUNT_EXCEEDED` | Reserved for ArkTS error-code compatibility; not returned by Java (per-period execution limits use 4004) |
204+| 4004 | `A4P_PERIOD_EXECUTION_COUNT_EXCEEDED` | Period execution count exceeded |
205+| 4005 | `A4P_PRODUCT_QUANTITY_EXCEEDED` | Product quantity exceeded |
206+| 4006 | `A4P_SINGLE_ORDER_AMOUNT_EXCEEDED` | Single order amount exceeded |
207+| 4007 | `A4P_PRODUCT_NOT_AUTHORIZED` | Product not authorized |
208+| 5001 | `A4P_SERIALIZE_FAIL` | Serialization failed |
209+| 5002 | `A4P_DESERIALIZE_FAIL` | Deserialization failed |
210+| 6001 | `A4P_INTERNAL_ERROR` | Unexpected internal error |
211+ 
212+`2001` and `2002` also cover the optional adapter: `Rsa3072` returns `2002` for a rejected
213+signature, and a `Signer`/`SignatureVerifier` that throws is mapped to the same codes by
214+the SDK, as described below.
215+ 
216+## Execution semantics
217+ 
218+- Pending and completed records both consume amount, count and whitelist quantity.
219+- Explicit cancellation releases quota; unknown downstream outcomes do not.
220+- An order's cart must match the whitelist groups one to one: `cartItems` and
221+ `itemsWhiteList` have the same length, and each cart item is paired with a distinct
222+ group listing its product. The cart order does not matter; any valid pairing is enough.
223+- `orderId` is the payment idempotency key: an order ID already in the ledger,
224+ canceled records included, is rejected with `A4P_DUPLICATE_ID`.
225+- Duplicate execution IDs remain rejected after cancellation. A provided execution ID
226+ must not be blank; a generated ID is stored on the ledger record.
227+- Reservation checks run in a fixed order: request structure (including a non-blank
228+ provided execution ID); version, action and currency against the authorized intent;
229+ context status; validity window (the lazy EXPIRED flip); duplicate execution/order IDs;
230+ then the execution-count cap, the single-order amount cap, the remaining amount, the
231+ one-to-one cart match, whitelist quantity, and period quota.
232+- A cart of the wrong size fails with `A4P_INVALID_PARAMETER`; a cart without a valid
233+ pairing (including a product outside every group) fails with `A4P_PRODUCT_NOT_AUTHORIZED`.
234+ For quantity, an item still counts against every group that lists its product.
235+- Revocation blocks reservations but permits pending completion/cancellation.
236+- A reservation past `validUntil` marks the context EXPIRED, even though the call fails.
237+ Pending records can still be completed or canceled in EXPIRED status.
238+- Completion and cancellation reject a `now` earlier than the record's `reservedAt` with
239+ `A4P_INVALID_PARAMETER`; the record stays pending.
240+- An ACTIVE intent becomes CONSUMED after a completion leaves no pending record and either
241+ the count cap is reached or the remaining amount is 0. REVOKED and EXPIRED are terminal.
242+- `executionInfo()` always declares `leftExecutionCount`, `leftAmount`, `periodIndex` and
243+ `leftPeriodExecutionCount`; non-applicable figures are `null`.
244+- Context operations synchronize validation and updates. This protects threads
245+ sharing one context, **not** multiple processes or independently activated copies.
246+- `A4pIntentCodec.standard()` returns a stateless shared singleton, so one instance can
247+ serve every thread.
248+ 
249+The ledger is in-memory. The intent center must persist the context inside a database
250+transaction locked by `intentId`, prevent replay of the same `intentId`, and bind keys to
251+identities. Activation checks the outer user signature; `verifyIntentAuthenticity` checks
252+the L3 chain and the intent center's L2 signature, not the user signature, and does not
253+depend on the context status.
254+ 
255+## Wire format and security
256+ 
257+See [canonical JSON specification](docs/canonical-json-spec.md). JSON field names follow the
258+specification (`intentConversation`, `resources`, `UserIdentity.id`), every enum is
259+serialized by name (`"AI_PAY"`, `"CONSUMED"`, `"PENDING"`), and the protocol version is
260+`1.0`. HTTP bindings are not part of this SDK until the specification settles them.
261+ 
262+Each level's signature covers the level without its whole `sign` object, so that level's
263+`alg` and `keyIdentifier` are not part of its own signed bytes; the next level's signature
264+covers them. This is the specified design. `alg` must be `RSA3072`. Verifiers must resolve
265+keys exclusively from a trusted registry and bind each key to allowed algorithms; never
266+trust the incoming `alg`.
267+ 
268+`Rsa3072` is an optional working adapter using JCA `SHA256withRSA` (PKCS#1 v1.5),
269+3072-bit RSA keys and unpadded Base64URL. Its `VerificationResult.code` is `0` on success
270+and `2002` on failure, with the reason in `message`. Its factories throw
271+`A4pException(A4P_INVALID_PARAMETER)` for a missing trust map, a blank key identifier or a
272+missing or non-3072-bit key. Peers must agree on this suite or
273+supply matching `Signer`/`SignatureVerifier` implementations. Any verifier must return a
274+`VerificationResult` whose `valid` is true exactly when `code` is `0`; an inconsistent
275+result is treated as a verification failure.
276+ 
277+Intent records and nested payloads are immutable; `JsonNode` payloads are copied on the
278+way in and out. The Java port also rejects duplicate JSON keys, unknown model fields,
279+invalid UTF-8, fractional integer fields, numeric enum values, scalar coercions and invalid
280+callback results instead of silently normalizing security-sensitive input.
281+ 
282+## Version and compatibility
283+ 
284+The protocol version is `1.0` (`A4p.PROTOCOL_VERSION`). Every level this SDK creates is
285+stamped with that constant, and each step validates the levels it receives, rejecting a
286+mismatch with `A4P_UNSUPPORTED_VERSION`. The port implements the same wire
287+format as the ArkTS SDK (`A4P-arkts-sdk/`) it came from, and the canonical-vector tests
288+keep the two in step, so intents and persisted contexts are interchangeable across the
289+two SDKs as long as both use the canonical JSON rules and the same signature suite. The
290+artifact version is `0.1.0`; protocol compatibility is governed by the `version`
291+field, not by the artifact version.
292+ 
293+## Known limitations
294+ 
295+- The ledger is in-memory and per-context. Durability, locked persistence, replay
296+ prevention and key-to-identity binding belong to the intent center.
297+- Synchronization covers threads that share one `IntentExecutionContext`, not several
298+ processes or independently activated copies of the same `intentId`.
299+- HTTP bindings are out of scope until the specification settles them; only in-process
300+ calls and canonical JSON serialization are provided.
301+- `Rsa3072` is one agreed suite rather than a negotiation; peers must either use it or
302+ supply matching `Signer`/`SignatureVerifier` implementations.
303+- `verifyIntentAuthenticity` deliberately does not verify the user signature.
304+- The port is stricter than the protocol minimum in places (duplicate JSON keys, unknown
305+ fields, numeric enums, scalar coercions) so that security-sensitive input is never
306+ silently normalized. The alignment documents below record what changed, and why.
307+ 
308+## More documentation
309+ 
310+Additional reference documents live under `docs/`:
311+ 
312+| Document | Contents |
313+| --- | --- |
314+| [canonical-json-spec.md](docs/canonical-json-spec.md) | Canonical JSON and Base64URL rules behind every signature. |
315+ 
316+## Tests
317+ 
318+Tests cover lifecycle, quota rollback, order idempotency, one-to-one cart matching, check
319+ordering, expiry finalization, terminal states, consumption, whitelist checks, period
320+boundaries, blank/structural validation, the result model, the typed-union payloads, wire
321+names and enum encoding, concurrent reservations, canonical vectors, detached signature
322+metadata, malformed input, verifier result consistency, execution-context persistence and
323+restore (including reachable status and record timestamps) and real RSA signature
324+verification/tampering. The digest signer in the test fixtures is only a deterministic
325+test double and must not be used for authorization.
@@ -0,0 +1,276 @@
1+# A4P Java SDK
2+ 
3+[English](./README.md) | 简体中文
4+ 
5+A4P 支付意图协议的 Java 17 实现,移植自 [PR #130](https://github.com/openJiuwen-ai/agent-protocol/pull/130) 中的 ArkTS SDK。
6+ 
7+## 构建与测试
8+ 
9+环境要求:JDK 17 及以上、Maven 3.9 及以上。
10+ 
11+```sh
12+cd A4P-java-sdk
13+mvn test
14+mvn package
15+```
16+ 
17+### 编译脚本
18+ 
19+脚本需要 Bash 环境(例如 Linux、WSL 或 Windows 上的 Git Bash)。在仓库根目录执行:
20+ 
21+```sh
22+bash A4P-java-sdk/scripts/build.sh # 默认使用 build 模式
23+bash A4P-java-sdk/scripts/build.sh build # 显式指定编译打包
24+bash A4P-java-sdk/scripts/build.sh ut # 仅运行单元测试
25+bash A4P-java-sdk/scripts/build.sh --help
26+```
27+ 
28+`build` 使用 `-Dmaven.test.skip=true` 执行 `clean package`,跳过测试代码的编译与执行,
29+产物为 `A4P-java-sdk/target/a4p-java-sdk-0.1.0.jar`。`ut` 执行 `clean test`,
30+要求存在测试,测试失败时返回失败,不打包 JAR;Surefire 测试报告位于
31+`A4P-java-sdk/target/surefire-reports/`。两种模式都会先清理 `target/`,并返回 Maven 的退出码。
32+ 
33+额外的 Maven 参数放在模式之后,例如:
34+ 
35+```sh
36+bash A4P-java-sdk/scripts/build.sh build -o
37+bash A4P-java-sdk/scripts/build.sh ut -Dtest=Rsa3072Test
38+```
39+ 
40+`-o` 表示 Maven 离线模式,所需依赖和插件必须已缓存。脚本根据自身位置定位 `pom.xml`,
41+不依赖调用时的工作目录。
42+ 
43+### 生成 CI 报告的 UT 脚本
44+ 
45+如需运行单元测试并生成 CI 报告,在仓库根目录执行以下命令。脚本根据自身位置定位仓库
46+根目录,不依赖调用者的工作目录;也可通过 `WORKSPACE` 指定仓库根目录的绝对路径来覆盖默认值。
47+ 
48+```sh
49+bash A4P-java-sdk/scripts/ut.sh
50+```
51+ 
52+该脚本需要 Git、Maven 和常用 Shell 工具,其中 `grep` 需要支持 `-P`(例如 GNU grep)。
53+脚本执行 `mvn clean test`,并返回 Maven 的退出码(`0` 为 `PASS`,非 `0` 为 `FAILED`)。
54+报告输出到定位到的仓库根目录下的 `outputs/`(设置覆盖值时为 `$WORKSPACE/outputs/`):
55+ 
56+| 文件 | 内容 |
57+| --- | --- |
58+| `ut.log` | Maven 测试日志 |
59+| `unit_test_report.html` | 测试数量统计及最后 200 行日志 |
60+| `junit.xml` | 合并后的 JUnit XML,仅在存在 Surefire XML 报告时生成 |
61+| `ut.json` | 状态、Maven 退出码及报告链接 |
62+ 
63+可选环境变量 `PR_ID`(默认 `0`)与 `OBS_BUCKET`(默认 `openjiuwen-ci`)用于配置
64+`ut.json` 中的报告链接。脚本只生成本地报告,上传到链接对应的 OBS 位置需由 CI 另行完成。
65+ 
66+构件坐标为 `io.openjiuwen:a4p-java-sdk:0.1.0`。JSON 由 Jackson 处理;JUnit 5 仅用于测试。不需要任何 Web 框架。
67+ 
68+`jackson-databind`(此处为 2.20.1)是唯一的运行时依赖,JUnit 5 为 `test` 作用域。
69+ 
70+```xml
71+<dependency>
72+ <groupId>io.openjiuwen</groupId>
73+ <artifactId>a4p-java-sdk</artifactId>
74+ <version>0.1.0</version>
75+</dependency>
76+```
77+ 
78+可在 IDE 中运行 `io.openjiuwen.a4p.examples.PaymentExample`,或执行:
79+ 
80+```sh
81+mvn compile org.codehaus.mojo:exec-maven-plugin:3.6.3:java "-Dexec.mainClass=io.openjiuwen.a4p.examples.PaymentExample"
82+```
83+ 
84+`pom.xml` 中并未声明 exec 插件,因此该命令首次执行时会从 Maven 中央仓库解析该插件,需要有网络访问。
85+ 
86+示例使用相互独立的 Agent、意图中心(intent center)与用户 RSA-3072 密钥对,演示了创建、签发、授权、激活、验签、预留与完成一笔支付。
87+ 
88+## API
89+ 
90+| 规范 | Java |
91+| --- | --- |
92+| `createIntent` | `A4p.createIntent(CreateIntentRequest, Signer[, long now])` 返回 `A4pResult<IntentL1>` |
93+| `issueIntent` | `A4p.issueIntent(IntentL1, SignatureVerifier, IntentIssueContext, Signer[, long now])` 返回 `A4pResult<IntentL2>` |
94+| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, long now])` 返回 `A4pResult<IntentL3>` |
95+| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, long now])` 返回 `A4pResult<IntentExecutionContext>` |
96+| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` 返回 `A4pResult<VerificationResult>` |
97+| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext)` 返回 `A4pResult<IntentExecutionContext>` |
98+| `createExecution / completeExecution / cancelExecution` | `A4p` 上的静态方法,返回 `A4pResult<IntentExecutionContext>` |
99+| `A4pResult<T>` | `A4pResult`:`success()`、`data()`、`code()`(`long`)、`message()` |
100+| `A4pException` | `A4pException`,仅由返回值型辅助方法以及 SDK 缺陷抛出 |
101+| `A4pErrorCode` | `code()`、`message()`,以及把结果码还原为常量的 `fromCode(int)` |
102+| `A4pIntentCodec` | `A4pIntentCodec.standard()`;`serializeIntentL1/L2/L3` 与 `serializeIntentExecutionContext` 返回 `String`,对应的每个 `deserialize…` 返回 `A4pResult` |
103+| `Signer / SignatureVerifier` | 函数式接口;`Signer.sign(byte[])` 返回 `SignatureInfo` |
104+| `Rsa3072` | 可选适配器:`Rsa3072.signer(String, PrivateKey)` 与 `Rsa3072.verifier(Map<String, PublicKey>)` |
105+| `CanonicalJson` | 签名时使用的规范化辅助方法:`stringify`、`toSignableBytes`、`encodeUtf8`/`decodeUtf8`、`base64UrlEncode`/`base64UrlDecode`、`MAX_SAFE_INTEGER` |
106+| 类型联合(`StructuredIntent`、`Execution`、`executionInfo`) | `JsonNode` 载荷;`PaymentProfile` 在 AI_PAY 载荷与记录之间相互转换 |
107+| 数据模型 | `Models` 中的不可变 record 与枚举 |
108+ 
109+`[long now]` 表示下文中说明的显式时钟重载。
110+ 
111+这些 record 与枚举嵌套在 `Models` 中;`A4p`、`A4pResult`、`A4pException`、`A4pErrorCode`、
112+`A4pIntentCodec`、`IntentExecutionContext`、`PaymentProfile` 与 `Rsa3072` 是顶层类,因此两个 import 都需要:
113+ 
114+```java
115+import io.openjiuwen.a4p.*;
116+import io.openjiuwen.a4p.Models.*;
117+```
118+ 
119+AI_PAY 载荷请通过 `PaymentProfile` 构造。下面的片段展示调用形态;完整可编译的版本见
120+`io.openjiuwen.a4p.examples.PaymentExample`,其中还包含密钥对、L1/L2/L3 链以及规范化序列化的搭建过程。
121+ 
122+```java
123+// 激活一个由 Agent 创建、意图中心签发并签名的意图。
124+SignatureVerifier userVerifier = Rsa3072.verifier(Map.of("user", userPublicKey));
125+A4pResult<IntentExecutionContext> activated = A4p.activateIntent(authorizedIntent, userVerifier, now);
126+if (!activated.success()) { /* 依据 activated.code() 分支处理 */ }
127+IntentExecutionContext context = activated.data();
128+ 
129+// 针对已激活的意图预留一笔订单,然后完成它。
130+Order order = new Order("order-1", 3000L, "CNY", List.of(new CartItem(product, 1L)), now);
131+Execution execution = PaymentProfile.execution("execution-1", "1.0", order);
132+A4pResult<IntentExecutionContext> reserved = A4p.createExecution(context, execution, now);
133+if (!reserved.success()) { /* 依据 reserved.code() 分支处理,然后持久化 context */ }
134+A4pResult<IntentExecutionContext> completed = A4p.completeExecution(context, execution.id(), now);
135+ 
136+PaymentExecutionInfo info = PaymentProfile.executionInfo(context);
137+```
138+ 
139+失败的 `createExecution` 仍可能已把 context 置为 `EXPIRED`,因此每次调用后都要持久化 context。
140+`A4pIntentCodec` 上的 `serializeIntentExecutionContext` / `deserializeIntentExecutionContext`
141+提供持久化形式;反序列化会重新校验存储的 L3(不重新验证用户签名),检查账本是否符合已授权约束,
142+并要求 `executionInfo` 与账本一致。它还要求状态可达:每个 `reservedAt` 落在 `[validFrom, validUntil]` 内,
143+`completedAt`/`canceledAt` 不早于 `reservedAt`,并且当且仅当没有待处理记录且全局配额已用尽时状态为
144+`CONSUMED`(`REVOKED` 与 `EXPIRED` 接受任意账本)。
145+ 
146+可选字段使用 `null`;缺席的可选字段不会出现在签名 JSON 中。AI_PAY 载荷内显式的 `null` 会被拒绝。
147+金额是应用约定的最小货币单位下的正整数。所有协议数值都是限制在 JavaScript 安全整数范围内的整数;
148+不是整数的值必须以字符串承载。
149+ 
150+生命周期与执行方法都同时提供系统时钟重载与显式的 `long now` 重载(epoch 毫秒)。显式 `now`
151+必须是非负安全整数,并且在其他校验之前最先被验证。生产代码必须提供可信时钟,绝不能使用客户端
152+提供的时间戳。订单时间戳不决定配额周期,也不决定授权有效期。
153+ 
154+必填字符串不能为空白(使用 JavaScript `trim()` 的空白字符集)。一个商品需要非空白的 seller ID,
155+并且 `spuId`/`skuId` 至少提供一个。周期规则要求 `anchorTime <= validFrom` 且
156+`periodSeconds <= 9007199254740`。链上时间戳单调:`L1.timestamp <= L2.timestamp <= L3.timestamp`。
157+激活要求 `L3.timestamp <= now <= validUntil`(`A4P_INVALID_PARAMETER` / `A4P_TIMESTAMP_EXPIRED`);
158+尚未生效的意图可以被激活,而在 `validFrom` 之前的预留会以 `A4P_TIMESTAMP_TOO_EARLY` 失败。
159+`intentConversation` 的长度限制与敏感数据过滤由 Agent 负责。
160+ 
161+### 结果码
162+ 
163+调用方依据 `code()` 分支处理;`message()` 是固定的诊断文本,取值来自与 ArkTS SDK 共用的
164+`A4pErrorCode`。`0` 表示成功,其他任何值都是协议失败。`A4pErrorCode.fromCode(int)` 把码还原为常量,
165+未知值映射为 `A4P_INTERNAL_ERROR`(调用时需把 `code()` 返回的 `long` 转成 `int`)。
166+ 
167+| 码 | 常量 | 含义 |
168+| --- | --- | --- |
169+| 0 | `A4P_SUCCESS` | 操作成功 |
170+| 1001 | `A4P_INVALID_PARAMETER` | 参数无效 |
171+| 1002 | `A4P_UNSUPPORTED_VERSION` | 版本不受支持 |
172+| 1003 | `A4P_DUPLICATE_ID` | ID 重复 |
173+| 2001 | `A4P_SIGNING_FAIL` | 签名失败 |
174+| 2002 | `A4P_VERIFY_FAIL` | 验证失败 |
175+| 3001 | `A4P_INVALID_STATUS` | 状态无效 |
176+| 3002 | `A4P_TIMESTAMP_EXPIRED` | 时间戳已过期 |
177+| 3003 | `A4P_TIMESTAMP_TOO_EARLY` | 时间戳过早 |
178+| 4001 | `A4P_EXECUTION_COUNT_EXCEEDED` | 超出执行次数上限 |
179+| 4002 | `A4P_AMOUNT_EXCEEDED` | 超出金额上限 |
180+| 4003 | `A4P_PERIOD_COUNT_EXCEEDED` | 为兼容 ArkTS 错误码而保留;Java 当前不返回此码(周期执行次数超限使用 4004) |
181+| 4004 | `A4P_PERIOD_EXECUTION_COUNT_EXCEEDED` | 超出周期执行次数上限 |
182+| 4005 | `A4P_PRODUCT_QUANTITY_EXCEEDED` | 超出商品数量上限 |
183+| 4006 | `A4P_SINGLE_ORDER_AMOUNT_EXCEEDED` | 超出单笔订单金额上限 |
184+| 4007 | `A4P_PRODUCT_NOT_AUTHORIZED` | 商品未被授权 |
185+| 5001 | `A4P_SERIALIZE_FAIL` | 序列化失败 |
186+| 5002 | `A4P_DESERIALIZE_FAIL` | 反序列化失败 |
187+| 6001 | `A4P_INTERNAL_ERROR` | 意外的内部错误 |
188+ 
189+`2001` 与 `2002` 也覆盖可选适配器:`Rsa3072` 对签名被拒返回 `2002`,抛出异常的
190+`Signer`/`SignatureVerifier` 会被 SDK 映射为同样的码,详见下文。
191+ 
192+## 执行语义
193+ 
194+- 待处理记录与已完成记录都会占用金额、次数和白名单数量。
195+- 显式取消会释放配额;下游结果未知则不会释放。
196+- 订单购物车必须与白名单分组一一匹配:`cartItems` 与 `itemsWhiteList` 长度相同,并且每个购物车
197+ 条目与一个不同的、列出该商品的分组配对。购物车顺序无关紧要,只要存在一种有效配对即可。
198+- `orderId` 是支付的幂等键:账本中已存在的订单 ID(含已取消记录)会以 `A4P_DUPLICATE_ID` 被拒绝。
199+- 重复的执行 ID 在取消之后依然会被拒绝。调用方提供的执行 ID 不能为空白;自动生成的 ID 会写入账本记录。
200+- 预留检查按固定顺序执行:请求结构(包括提供的执行 ID 非空白);版本、动作与币种是否与已授权意图
201+ 一致;context 状态;有效期窗口(惰性置为 EXPIRED);执行/订单 ID 重复;随后是执行次数上限、
202+ 单笔订单金额上限、剩余金额、购物车一一匹配、白名单数量,最后是周期配额。
203+- 购物车长度不匹配会以 `A4P_INVALID_PARAMETER` 失败;购物车不存在有效配对(包括商品不在任何分组中)
204+ 会以 `A4P_PRODUCT_NOT_AUTHORIZED` 失败。在数量校验中,一个条目仍会针对每一个列出其商品的分组计数。
205+- 撤销会阻止预留,但允许对待处理记录执行完成/取消。
206+- 超过 `validUntil` 的预留会把 context 标记为 EXPIRED,尽管该次调用失败。待处理记录在 EXPIRED 状态下
207+ 仍可被完成或取消。
208+- 完成与取消操作若 `now` 早于该记录的 `reservedAt`,会以 `A4P_INVALID_PARAMETER` 被拒绝;记录保持待处理。
209+- 当一次完成操作之后不再有待处理记录,且要么达到次数上限、要么剩余金额为 0 时,ACTIVE 意图变为
210+ CONSUMED。REVOKED 与 EXPIRED 是终态。
211+- `executionInfo()` 始终给出 `leftExecutionCount`、`leftAmount`、`periodIndex` 与
212+ `leftPeriodExecutionCount`;不适用的数值为 `null`。
213+- context 操作对校验与更新加锁。这保护共享同一个 context 的线程,而**不**保护多个进程或各自独立激活
214+ 的副本。
215+- `A4pIntentCodec.standard()` 返回无状态的共享单例,因此一个实例可以服务所有线程。
216+ 
217+账本位于内存中。意图中心必须在以 `intentId` 加锁的数据库事务中持久化 context,防止同一个 `intentId`
218+被重放,并把密钥与身份绑定。激活会校验最外层的用户签名;`verifyIntentAuthenticity` 校验 L3 链与意图
219+中心的 L2 签名,不校验用户签名,也不依赖 context 状态。
220+ 
221+## 线格式与安全
222+ 
223+参见 [canonical JSON 规范](docs/canonical-json-spec.md)。JSON 字段名遵循规范
224+(`intentConversation`、`resources`、`UserIdentity.id`),每个枚举都按名称序列化
225+(`"AI_PAY"`、`"CONSUMED"`、`"PENDING"`),协议版本为 `1.0`。在规范确定它们之前,HTTP 绑定不属于本 SDK。
226+ 
227+每一层的签名覆盖该层除去整个 `sign` 对象之后的内容,因此该层自己的 `alg` 与 `keyIdentifier`
228+不在其自身签名字节内;它们由下一层的签名覆盖。这是规范规定的设计。`alg` 必须是 `RSA3072`。
229+验证方必须只从可信注册表中解析密钥,并把每个密钥绑定到允许的算法;绝不要信任传入的 `alg`。
230+ 
231+`Rsa3072` 是一个可选但可用的适配器,使用 JCA `SHA256withRSA`(PKCS#1 v1.5)、3072 位 RSA 密钥
232+和无填充的 Base64URL。其 `VerificationResult.code` 成功为 `0`、失败为 `2002`,失败原因放在
233+`message` 中。缺失信任映射表、空白密钥标识符或缺失/非 3072 位密钥时,其工厂方法抛出
234+`A4pException(A4P_INVALID_PARAMETER)`。对端必须就该套件达成一致,或提供相匹配的
235+`Signer`/`SignatureVerifier` 实现。任何验证器返回的 `VerificationResult` 都必须在 `code` 为 `0`
236+时恰好令 `valid` 为 true;结果不一致时按验证失败处理。
237+ 
238+意图记录与嵌套载荷不可变;`JsonNode` 载荷在进出时都会被复制。该 Java 移植还拒绝重复的 JSON 键、
239+未知的模型字段、非法 UTF-8、带小数的整数字段、数值型枚举值、标量强制转换以及非法的回调结果,
240+而不是静默地规范化安全敏感输入。
241+ 
242+## 版本与兼容性
243+ 
244+协议版本是 `1.0`(`A4p.PROTOCOL_VERSION`)。本 SDK 创建的每一层都写入该常量,每一步都会校验所收到的
245+各层,不一致时以 `A4P_UNSUPPORTED_VERSION` 拒绝。该移植与它所来自的 ArkTS SDK(`A4P-arkts-sdk/`)
246+实现相同的线格式,canonical-vector 测试让两者保持一致,因此在双方都使用 canonical JSON 规则与同一
247+签名套件的前提下,意图与持久化的 context 可以在两个 SDK 之间互换。构件版本为 `0.1.0`;
248+协议兼容性由 `version` 字段决定,而不是由构件版本决定。
249+ 
250+## 已知限制
251+ 
252+- 账本是内存内的、以单个 context 为粒度。持久化、加锁写入、防重放以及密钥与身份的绑定都由意图中心负责。
253+- 同步只覆盖共享同一个 `IntentExecutionContext` 的线程,不覆盖多个进程,也不覆盖同一个 `intentId`
254+ 各自独立激活的副本。
255+- 在规范确定之前,HTTP 绑定不在范围内;仅提供进程内调用与 canonical JSON 序列化。
256+- `Rsa3072` 是约定好的一个套件,而非协商结果;对端要么使用它,要么提供相匹配的
257+ `Signer`/`SignatureVerifier` 实现。
258+- `verifyIntentAuthenticity` 有意不校验用户签名。
259+- 该移植在若干处比协议最低要求更严格(重复 JSON 键、未知字段、数值枚举、标量强制转换),以确保安全
260+ 敏感输入永远不会被静默规范化。下文的对齐文档记录了改了什么以及为什么。
261+ 
262+## 更多文档
263+ 
264+参考文档位于 `docs/` 目录:
265+ 
266+| 文档 | 内容 |
267+| --- | --- |
268+| [canonical-json-spec.md](docs/canonical-json-spec.md) | 每次签名背后的 canonical JSON 与 Base64URL 规则。 |
269+ 
270+## 测试
271+ 
272+测试覆盖生命周期、配额回滚、订单幂等、购物车一一匹配、检查顺序、过期终结、终态、消费、白名单校验、
273+周期边界、空白与结构校验、结果模型、类型联合载荷、线格式名称与枚举编码、并发预留、canonical 向量、
274+分离的签名元数据、畸形输入、验证器结果一致性、执行 context 的持久化与恢复(包括状态可达性与记录
275+时间戳),以及真实的 RSA 签名验证与篡改检测。测试夹具中的 digest 签名器只是一个确定性的测试替身,
276+不得用于授权。
@@ -0,0 +1,13 @@
1+# Build environment for A4P Java SDK (linux/amd64 and linux/arm64).
2+# Build context: A4P-java-sdk/docker; mount the SDK source at /workspace.
3+ARG JAVA_VERSION=17
4+ARG MAVEN_VERSION=3.9
5+FROM maven:${MAVEN_VERSION}-eclipse-temurin-${JAVA_VERSION}
6+ 
7+WORKDIR /workspace
8+ 
9+# Fail early if the selected image does not provide the required toolchain.
10+RUN java -version && javac -version && mvn --version && bash --version
11+ 
12+# Builds and tests must be invoked explicitly when starting the container.
13+CMD ["bash"]
@@ -0,0 +1,39 @@
1+# Java SDK Docker build environment
2+ 
3+English | [简体中文](README_zh.md)
4+ 
5+Run from the repository root. Docker must be able to pull the official Maven image;
6+Maven needs access to its dependency repositories on the first build.
7+ 
8+```sh
9+docker build -t a4p-java-build:17 A4P-java-sdk/docker
10+docker run --rm -v "$PWD/A4P-java-sdk:/workspace" -v a4p-maven-cache:/root/.m2 a4p-java-build:17 bash build.sh build
11+docker run --rm -v "$PWD/A4P-java-sdk:/workspace" -v a4p-maven-cache:/root/.m2 a4p-java-build:17 bash build.sh ut
12+```
13+ 
14+The container defaults to Bash and does not build the SDK automatically. Invoke
15+`bash build.sh build` explicitly to package `target/a4p-java-sdk-0.1.0.jar` without compiling or
16+running tests. The UT command writes reports to `target/surefire-reports/` and cleans
17+the previous JAR. Archive the JAR before running UT. Both commands return Maven's
18+exit status. Output files belong to the container user (root by default).
19+ 
20+Use a newer JDK by selecting a Java version supported by the official Maven image:
21+ 
22+```sh
23+docker build --build-arg JAVA_VERSION=21 -t a4p-java-build:21 A4P-java-sdk/docker
24+```
25+ 
26+`MAVEN_VERSION` defaults to the `3.9` image tag and can be pinned to a published
27+3.9.x tag. The POM keeps `maven.compiler.release=17`, so builds with newer JDKs
28+still produce Java 17-compatible bytecode. The base image supplies native JDK and
29+Maven tools on both AMD64 and ARM64; CPU emulation is unnecessary.
30+ 
31+For a custom repository mirror, mount a Maven settings file and pass it to the script:
32+ 
33+```sh
34+docker run --rm -v "$PWD/A4P-java-sdk:/workspace" -v a4p-maven-cache:/root/.m2 \
35+ -v "$PWD/settings.xml:/tmp/settings.xml:ro" \
36+ a4p-java-build:17 bash build.sh build --settings /tmp/settings.xml
37+```
38+ 
39+PowerShell: use `${PWD}/A4P-java-sdk` in place of `$PWD/A4P-java-sdk`.
@@ -0,0 +1,35 @@
1+# Java SDK Docker 构建环境
2+ 
3+[English](README.md) | 简体中文
4+ 
5+在仓库根目录执行以下命令。Docker 需要能够拉取官方 Maven 镜像;首次构建时 Maven 需要访问其依赖仓库。
6+ 
7+```sh
8+docker build -t a4p-java-build:17 A4P-java-sdk/docker
9+docker run --rm -v "$PWD/A4P-java-sdk:/workspace" -v a4p-maven-cache:/root/.m2 a4p-java-build:17 bash build.sh build
10+docker run --rm -v "$PWD/A4P-java-sdk:/workspace" -v a4p-maven-cache:/root/.m2 a4p-java-build:17 bash build.sh ut
11+```
12+ 
13+容器默认进入 Bash,不会自动构建 SDK。需要显式执行 `bash build.sh build`,在不编译、不运行测试的情况下打包出 `target/a4p-java-sdk-0.1.0.jar`。单元测试命令将报告写入 `target/surefire-reports/`,并清理上一次构建的 JAR,因此请在运行 UT 前归档 JAR。两条命令均返回 Maven 的退出状态。产物文件归属容器用户(默认为 root)。
14+ 
15+## 更换 JDK 版本
16+ 
17+选择官方 Maven 镜像支持的 Java 版本,即可使用更新的 JDK:
18+ 
19+```sh
20+docker build --build-arg JAVA_VERSION=21 -t a4p-java-build:21 A4P-java-sdk/docker
21+```
22+ 
23+`MAVEN_VERSION` 默认为 `3.9` 镜像标签,也可以固定为已发布的 3.9.x 标签。POM 中保持 `maven.compiler.release=17`,因此使用更新的 JDK 构建时仍生成兼容 Java 17 的字节码。基础镜像在 AMD64 和 ARM64 上均提供原生 JDK 与 Maven 工具,无需 CPU 模拟。
24+ 
25+## 使用自定义仓库镜像
26+ 
27+挂载 Maven settings 文件并将其传给脚本:
28+ 
29+```sh
30+docker run --rm -v "$PWD/A4P-java-sdk:/workspace" -v a4p-maven-cache:/root/.m2 \
31+ -v "$PWD/settings.xml:/tmp/settings.xml:ro" \
32+ a4p-java-build:17 bash build.sh build --settings /tmp/settings.xml
33+```
34+ 
35+PowerShell:将 `$PWD/A4P-java-sdk` 替换为 `${PWD}/A4P-java-sdk`。
@@ -0,0 +1,42 @@
1+# Canonical JSON and signed bytes
2+ 
3+Reference: PR #334
4+ 
5+1. Object keys are sorted lexicographically by UTF-16 code units (Java
6+ `String.compareTo`, equivalent to JavaScript's default string sort and to RFC 8785).
7+2. Array order is preserved. There is no whitespace between tokens.
8+3. Numbers must be finite integers in `[-9007199254740991, 9007199254740991]`.
9+ They use decimal notation without a fractional part or exponent. Negative zero
10+ becomes `0`. Amounts and timestamps are subject to additional model validation.
11+ Every protocol number is an integer by design; a value that is not an integer must
12+ be carried as a string.
13+4. Quotes, backslashes and control characters use JSON escapes. Characters below
14+ U+0020 without a short escape use lowercase `\u00xx`; other Unicode characters
15+ are emitted directly, with no normalization. Unpaired surrogates are rejected.
16+5. Java record fields with `null` represent absent optional properties and are
17+ omitted. Null values inside explicit JSON maps and lists remain `null`. Enums are
18+ rendered by name, for example `"AI_PAY"`.
19+6. Signing removes only the complete top-level property named `sign`, canonicalizes
20+ the remaining object, and encodes it as UTF-8 without a byte-order mark. It does
21+ not recursively remove nested signatures. The level's own `alg` and `keyIdentifier`
22+ are therefore not part of that level's signed bytes; the next level's signature
23+ covers them. This is the specified design (API specification §4.6.2).
24+7. Signature bytes use RFC 4648 Base64URL without padding. Decoders reject padding,
25+ non-URL-safe characters and nonzero unused trailing bits.
26+ 
27+Examples:
28+ 
29+```text
30+{"b":1,"a":2} -> {"a":2,"b":1}
31+[3,1,2] -> [3,1,2]
32+{"10":1,"2":2} -> {"10":1,"2":2}
33+9007199254740991 -> 9007199254740991
34+{"sign":"outer","nested":{"sign":"inner"}}
35+signed bytes -> {"nested":{"sign":"inner"}}
36+```
37+ 
38+`CanonicalJson.stringify` accepts JSON maps/lists/primitives, Jackson `JsonNode` trees
39+and SDK model records and enums. Arbitrary Java objects, non-string map keys, cycles and
40+excessive nesting fail with `A4P_SERIALIZE_FAIL`. Deserialization requires an object of
41+the expected model, rejects unknown properties, numeric enum values and explicit nulls
42+inside AI_PAY payloads, and validates every nested signature and constraint.
@@ -0,0 +1,39 @@
1+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
3+ <modelVersion>4.0.0</modelVersion>
4+ <groupId>io.openjiuwen</groupId>
5+ <artifactId>a4p-java-sdk</artifactId>
6+ <version>0.1.0</version>
7+ <name>A4P Java SDK</name>
8+ <properties>
9+ <maven.compiler.release>17</maven.compiler.release>
10+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
11+ </properties>
12+ <dependencies>
13+ <dependency>
14+ <groupId>com.fasterxml.jackson.core</groupId>
15+ <artifactId>jackson-databind</artifactId>
16+ <version>2.20.1</version>
17+ </dependency>
18+ <dependency>
19+ <groupId>org.junit.jupiter</groupId>
20+ <artifactId>junit-jupiter</artifactId>
21+ <version>5.14.1</version>
22+ <scope>test</scope>
23+ </dependency>
24+ </dependencies>
25+ <build>
26+ <plugins>
27+ <plugin>
28+ <groupId>org.apache.maven.plugins</groupId>
29+ <artifactId>maven-compiler-plugin</artifactId>
30+ <version>3.14.1</version>
31+ </plugin>
32+ <plugin>
33+ <groupId>org.apache.maven.plugins</groupId>
34+ <artifactId>maven-surefire-plugin</artifactId>
35+ <version>3.5.4</version>
36+ </plugin>
37+ </plugins>
38+ </build>
39+</project>
@@ -0,0 +1,195 @@
1+import java.nio.charset.StandardCharsets;
2+import java.nio.file.*;
3+import java.time.ZonedDateTime;
4+import java.util.*;
5+import javax.xml.XMLConstants;
6+import javax.xml.parsers.DocumentBuilderFactory;
7+import javax.xml.transform.*;
8+import javax.xml.transform.dom.DOMSource;
9+import javax.xml.transform.stream.StreamResult;
10+import org.w3c.dom.*;
11+ 
12+/** Dependency-free Surefire report renderer, compiled with JDK 17 or later. */
13+class UtReport {
14+ record Result(String status, String name, String duration, String detail) {}
15+ 
16+ static String escape(String text) {
17+ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
18+ .replace("\"", "&quot;").replace("'", "&#39;");
19+ }
20+ 
21+ public static void main(String[] args) throws Exception {
22+ Path project = Path.of(args[0]);
23+ var factory = DocumentBuilderFactory.newInstance();
24+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
25+ factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
26+ factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
27+ var builder = factory.newDocumentBuilder();
28+ var document = builder.newDocument();
29+ var suites = document.createElement("testsuites");
30+ document.appendChild(suites);
31+ List<Result> results = new ArrayList<>();
32+ List<String> warnings = new ArrayList<>();
33+ Map<String, Set<String>> testEnvironment = new LinkedHashMap<>();
34+ for (String key : List.of("os.name", "os.version", "java.version")) {
35+ testEnvironment.put(key, new LinkedHashSet<>());
36+ }
37+ Path reports = project.resolve("target/surefire-reports");
38+ if (Files.isDirectory(reports)) {
39+ List<Path> files;
40+ try (var stream = Files.list(reports)) {
41+ files = stream.filter(p -> p.getFileName().toString().matches("TEST-.*\\.xml"))
42+ .sorted().toList();
43+ }
44+ for (Path file : files) {
45+ Element suite;
46+ try {
47+ suite = builder.parse(file.toFile()).getDocumentElement();
48+ } catch (Exception ex) {
49+ warnings.add(file.getFileName() + ": " + ex.getMessage());
50+ continue;
51+ }
52+ suites.appendChild(document.importNode(suite, true));
53+ var properties = suite.getElementsByTagName("property");
54+ for (int i = 0; i < properties.getLength(); i++) {
55+ Element property = (Element) properties.item(i);
56+ var values = testEnvironment.get(property.getAttribute("name"));
57+ if (values != null && !property.getAttribute("value").isBlank()) {
58+ values.add(property.getAttribute("value"));
59+ }
60+ }
61+ var cases = suite.getElementsByTagName("testcase");
62+ for (int i = 0; i < cases.getLength(); i++) {
63+ Element test = (Element) cases.item(i);
64+ String status = "Passed";
65+ StringJoiner detail = new StringJoiner("\n\n");
66+ for (String tag : List.of("failure", "error", "skipped")) {
67+ var nodes = test.getElementsByTagName(tag);
68+ if (nodes.getLength() == 0) continue;
69+ status = switch (tag) {
70+ case "failure" -> "Failed";
71+ case "error" -> "Error";
72+ default -> "Skipped";
73+ };
74+ for (int n = 0; n < nodes.getLength(); n++) {
75+ Element node = (Element) nodes.item(n);
76+ detail.add(node.getAttribute("message") + "\n" + node.getTextContent());
77+ }
78+ break;
79+ }
80+ for (String tag : List.of("system-out", "system-err")) {
81+ var nodes = test.getElementsByTagName(tag);
82+ for (int n = 0; n < nodes.getLength(); n++) {
83+ detail.add("Captured " + tag + ":\n" + nodes.item(n).getTextContent());
84+ }
85+ }
86+ String name = test.getAttribute("classname");
87+ if (!name.isEmpty()) name += "::";
88+ name += test.getAttribute("name");
89+ String duration = test.getAttribute("time");
90+ results.add(new Result(status, name, duration.isEmpty() ? "0" : duration, detail.toString()));
91+ }
92+ }
93+ }
94+ Map<String, Long> counts = new LinkedHashMap<>();
95+ for (String status : List.of("Passed", "Failed", "Skipped", "Error")) {
96+ counts.put(status, results.stream().filter(r -> r.status().equals(status)).count());
97+ }
98+ suites.setAttribute("tests", Integer.toString(results.size()));
99+ suites.setAttribute("failures", counts.get("Failed").toString());
100+ suites.setAttribute("errors", counts.get("Error").toString());
101+ suites.setAttribute("skipped", counts.get("Skipped").toString());
102+ var transformer = TransformerFactory.newInstance().newTransformer();
103+ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
104+ transformer.transform(new DOMSource(document), new StreamResult(Path.of(args[2]).toFile()));
105+ if (results.isEmpty()) warnings.add("No test cases were found in Maven Surefire reports.");
106+ if (!args[5].equals("0")) warnings.add("Maven exited with code " + args[5] + ".");
107+ double elapsed = Math.max(0, System.currentTimeMillis() / 1000.0 - Long.parseLong(args[4]));
108+ StringBuilder out = new StringBuilder(HEADER);
109+ out.append("<p>Report generated on ").append(escape(ZonedDateTime.now().toString()))
110+ .append(" by Maven Surefire (pytest-html style).</p><h2>Environment</h2><table id=\"environment\">");
111+ String[][] environment = {{"Project", project.getFileName().toString()},
112+ {"Platform", environmentValue(testEnvironment, "os.name") + " / "
113+ + environmentValue(testEnvironment, "os.version")},
114+ {"Java", environmentValue(testEnvironment, "java.version")},
115+ {"Environment source", "Surefire XML (test JVM)"},
116+ {"CI", System.getenv().getOrDefault("CI", "")}};
117+ System.out.println(">>> Test environment (Surefire XML): Platform=" + environment[1][1]
118+ + ", Java=" + environment[2][1]);
119+ for (String[] entry : environment) {
120+ out.append("<tr><td>").append(escape(entry[0])).append("</td><td>")
121+ .append(escape(entry[1])).append("</td></tr>");
122+ }
123+ out.append("</table><h2>Summary</h2><p>").append(results.size()).append(" tests ran in ")
124+ .append(String.format(Locale.ROOT, "%.2f", elapsed)).append(" seconds.</p>")
125+ .append("<p>(Un)check the boxes to filter the results.</p><div class=\"controls\">");
126+ counts.forEach((status, count) -> out.append("<label class=\"").append(status.toLowerCase(Locale.ROOT))
127+ .append("\"><input type=\"checkbox\" data-status=\"").append(status).append("\" checked>")
128+ .append(count).append(' ').append(status.toLowerCase(Locale.ROOT)).append("</label> "));
129+ out.append("</div>");
130+ warnings.forEach(w -> out.append("<p class=\"warning\">").append(escape(w)).append("</p>"));
131+ out.append("<h2>Results</h2><p><button id=\"show-all\">Show all details</button> / <button id=\"hide-all\">Hide all details</button></p>")
132+ .append("<table id=\"results-table\"><thead><tr><th>Result</th><th>Test</th><th>Duration</th><th>Links</th></tr></thead>");
133+ for (Result r : results) {
134+ out.append("<tbody data-status=\"").append(r.status()).append("\"><tr class=\"result-row\"><td class=\"col-result ")
135+ .append(r.status().toLowerCase(Locale.ROOT)).append("\">").append(r.status()).append("</td><td>")
136+ .append(escape(r.name())).append("</td><td class=\"col-duration\">").append(escape(r.duration()))
137+ .append(" s</td><td></td></tr>");
138+ if (!r.detail().isEmpty()) {
139+ out.append("<tr class=\"detail-row\"><td colspan=\"4\"><details")
140+ .append(r.status().equals("Failed") || r.status().equals("Error") ? " open" : "")
141+ .append("><summary>Details</summary><pre>").append(escape(r.detail()))
142+ .append("</pre></details></td></tr>");
143+ }
144+ out.append("</tbody>");
145+ }
146+ out.append("</table><h2>Test Log</h2><details><summary>Maven output (last 200 lines)</summary><pre>");
147+ var lines = Files.readAllLines(Path.of(args[3]), StandardCharsets.UTF_8);
148+ out.append(escape(String.join("\n", lines.subList(Math.max(0, lines.size() - 200), lines.size()))));
149+ out.append(FOOTER);
150+ Files.writeString(Path.of(args[1]), out, StandardCharsets.UTF_8);
151+ }
152+ 
153+ static String environmentValue(Map<String, Set<String>> environment, String key) {
154+ var values = environment.get(key);
155+ return values.isEmpty() ? "Not recorded in Surefire XML" : String.join(", ", values);
156+ }
157+ 
158+ static final String HEADER = """
159+<!DOCTYPE html>
160+<html lang="en"><head><meta charset="UTF-8">
161+<meta name="viewport" content="width=device-width, initial-scale=1">
162+<title>unit_test_report.html</title><style>
163+body{font-family:Helvetica,Arial,sans-serif;font-size:12px;min-width:800px;color:#999}
164+h1{font-size:24px;color:#000}h2{font-size:16px;color:#000}p{color:#000}a{color:#999}
165+table{border-collapse:collapse}#environment td{padding:5px;border:1px solid #e6e6e6}
166+#environment tr:nth-child(odd){background:#f6f6f6}.passed{color:green}.failed,.error{color:red}
167+.skipped{color:orange}#results-table{border:1px solid #e6e6e6;color:#999;font-size:12px;width:100%}
168+#results-table th,#results-table td{padding:5px;border:1px solid #e6e6e6;text-align:left}
169+#results-table th{cursor:pointer}#results-table th:hover{color:#000}
170+.result-row:hover{background:#f6f6f6}.col-result{width:110px}.col-duration{width:100px}
171+pre{background:#e6e6e6;color:#000;font-family:monospace;white-space:pre-wrap;overflow-wrap:anywhere;padding:10px;max-height:400px;overflow:auto}
172+.controls{margin:12px 0}button{background:none;border:0;color:#999;text-decoration:underline;cursor:pointer}
173+.warning{color:red}details summary{cursor:pointer}.detail-row[hidden],.result-row[hidden]{display:none}
174+</style></head><body><h1>unit_test_report.html</h1>
175+ """;
176+ static final String FOOTER = """
177+</pre></details><script>
178+const table=document.getElementById('results-table');
179+document.querySelectorAll('input[data-status]').forEach(box=>box.addEventListener('change',()=>{
180+ table.querySelectorAll('tbody').forEach(body=>{if(body.dataset.status===box.dataset.status)body.hidden=!box.checked;});
181+}));
182+for(const [id,open] of [['show-all',true],['hide-all',false]]){
183+ document.getElementById(id).addEventListener('click',()=>table.querySelectorAll('details').forEach(d=>d.open=open));
184+}
185+table.querySelectorAll('th').forEach((th,index)=>th.addEventListener('click',()=>{
186+ const direction=th.dataset.direction==='asc'?-1:1;
187+ th.dataset.direction=direction===1?'asc':'desc';
188+ [...table.tBodies].sort((a,b)=>{
189+ const x=a.rows[0].cells[index].textContent,y=b.rows[0].cells[index].textContent;
190+ return direction*(index===2?parseFloat(x)-parseFloat(y):x.localeCompare(y));
191+ }).forEach(body=>table.appendChild(body));
192+}));
193+</script></body></html>
194+ """;
195+}
@@ -0,0 +1,43 @@
1+#!/usr/bin/env bash
2+# CI entry point with separate build and unit-test modes.
3+set -euo pipefail
4+ 
5+usage() {
6+ echo "Usage: bash build.sh [build|ut] [additional Maven options]"
7+ echo " build Compile and package the JAR without compiling/running tests (default)."
8+ echo " ut Compile and run unit tests without packaging the JAR."
9+}
10+ 
11+MODE="${1:-build}"
12+if [[ $# -gt 0 ]]; then
13+ shift
14+fi
15+case "${MODE}" in
16+ build)
17+ MAVEN_ARGS=(-Dmaven.test.skip=true clean package)
18+ ;;
19+ ut)
20+ MAVEN_ARGS=(-DskipTests=false -Dmaven.test.skip=false -Dmaven.test.failure.ignore=false -DfailIfNoTests=true clean test)
21+ ;;
22+ -h|--help)
23+ usage
24+ exit 0
25+ ;;
26+ *)
27+ echo "Error: unknown mode '${MODE}'." >&2
28+ usage >&2
29+ exit 2
30+ ;;
31+esac
32+ 
33+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
34+PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
35+if ! command -v mvn >/dev/null 2>&1; then
36+ echo "Error: Maven 3.9+ is required; install Maven and add mvn to PATH." >&2
37+ exit 1
38+fi
39+ 
40+# Resolve the project independently of the caller's working directory.
41+# Preserve Maven's exit code so compilation/test failures fail the CI job.
42+exec mvn --batch-mode --no-transfer-progress --show-version \
43+ --file "${PROJECT_DIR}/pom.xml" "$@" "${MAVEN_ARGS[@]}"
@@ -0,0 +1,104 @@
1+#!/usr/bin/env bash
2+# A4P-Java-SDK 单元测试 CI 步骤。
3+#
4+# 使用 Maven Surefire 运行 JUnit 5 测试,生成标准格式报告。
5+#
6+# 产出:
7+# - outputs/ut.log (Maven 测试日志)
8+# - outputs/unit_test_report.html (HTML 报告)
9+# - outputs/junit.xml (JUnit XML, 供 CI 解析)
10+# - outputs/ut.json (状态汇总)
11+#
12+# 判定: mvn 退出码 0=PASS, 非0=FAILED。
13+set -eu
14+(set -o pipefail) 2>/dev/null && set -o pipefail || true
15+ 
16+# ---------------------------------------------------------------------------
17+# 0. 参数解析
18+# ---------------------------------------------------------------------------
19+# 优先使用 WORKSPACE 环境变量,否则从脚本位置定位仓库根目录
20+if [ -n "${WORKSPACE:-}" ]; then
21+ BASE_DIR="$WORKSPACE"
22+else
23+ BASE_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
24+fi
25+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
26+echo "BASE_DIR: ${BASE_DIR}"
27+ 
28+# ---------------------------------------------------------------------------
29+# 1. 必备工具
30+# ---------------------------------------------------------------------------
31+cd "$BASE_DIR"
32+ 
33+# ---------------------------------------------------------------------------
34+# 2. 查找 Java 项目
35+# ---------------------------------------------------------------------------
36+JAVA_PROJECT_DIR=""
37+for dir in A4P-java-sdk a4p-java-sdk java-sdk; do
38+ if [ -d "$BASE_DIR/$dir" ] && [ -f "$BASE_DIR/$dir/pom.xml" ]; then
39+ JAVA_PROJECT_DIR="$BASE_DIR/$dir"
40+ break
41+ fi
42+done
43+ 
44+if [ -z "$JAVA_PROJECT_DIR" ]; then
45+ echo "Error: No Java project with pom.xml found" >&2
46+ exit 1
47+fi
48+ 
49+echo ">>> Found Java project: $JAVA_PROJECT_DIR"
50+ 
51+# ---------------------------------------------------------------------------
52+# 3. 结果目录 (使用 BASE_DIR 而非 JAVA_PROJECT_DIR)
53+# ---------------------------------------------------------------------------
54+mkdir -p "$BASE_DIR/outputs"
55+HTML="$BASE_DIR/outputs/unit_test_report.html"
56+JUNIT="$BASE_DIR/outputs/junit.xml"
57+LOG="$BASE_DIR/outputs/ut.log"
58+JSON="$BASE_DIR/outputs/ut.json"
59+# 清除上次运行或随仓库检出的报告,避免失败时上传旧产物。
60+rm -f -- "$HTML" "$JUNIT" "$LOG" "$JSON"
61+m=""
62+for t in git mvn java; do
63+ command -v "$t" >/dev/null || m="$m $t"
64+done
65+[ -z "$m" ] || { echo "missing tools:$m" >&2; exit 1; }
66+echo ">>> Report output: $HTML"
67+ 
68+# ---------------------------------------------------------------------------
69+# 4. 运行 Maven 测试
70+# ---------------------------------------------------------------------------
71+cd "$JAVA_PROJECT_DIR"
72+ 
73+started_at=$(date +%s)
74+rc=0
75+mvn --batch-mode --no-transfer-progress clean test 2>&1 | tee "$LOG" || rc=${PIPESTATUS[0]}
76+ 
77+# ---------------------------------------------------------------------------
78+# 5. 转换 Surefire 报告为标准 JUnit XML
79+# ---------------------------------------------------------------------------
80+# 使用 JDK 17 源文件启动模式生成自包含报告,无需额外依赖。
81+java -Dfile.encoding=UTF-8 "$SCRIPT_DIR/UtReport.java" \
82+ "$JAVA_PROJECT_DIR" "$HTML" "$JUNIT" "$LOG" "$started_at" "$rc"
83+echo ">>> Generated report: $HTML"
84+ 
85+# ---------------------------------------------------------------------------
86+# 7. 判定通过/失败
87+# ---------------------------------------------------------------------------
88+if [ "$rc" -eq 0 ]; then
89+ st="PASS"
90+else
91+ st="FAILED"; echo ">>> ERROR: Maven exit code=$rc" >&2
92+fi
93+ 
94+# ---------------------------------------------------------------------------
95+# 8. 汇总状态 JSON
96+# ---------------------------------------------------------------------------
97+PR_ID="${PR_ID:-0}"
98+OBS_BUCKET="${OBS_BUCKET:-openjiuwen-ci}"
99+OBS_PATH="agentcore/ut/${PR_ID}"
100+REPORT_LINK="https://${OBS_BUCKET}.obs.cn-north-4.myhuaweicloud.com/${OBS_PATH}/unit_test_report.html"
101+echo ">>> ut=$st (Maven exit=$rc)"
102+printf '{"status":"%s","exit_code":%d,"link":"%s"}\n' "$st" "$rc" "$REPORT_LINK" > "$JSON"
103+ 
104+exit $rc
@@ -0,0 +1,266 @@
1+package io.openjiuwen.a4p;
2+ 
3+import io.openjiuwen.a4p.Models.*;
4+import java.math.BigInteger;
5+import java.util.List;
6+import java.util.UUID;
7+import static io.openjiuwen.a4p.A4pErrorCode.*;
8+import static io.openjiuwen.a4p.Validation.require;
9+ 
10+public final class A4p {
11+ public static final String PROTOCOL_VERSION = "1.0";
12+ 
13+ private A4p() {}
14+ 
15+ public static A4pResult<IntentL1> createIntent(CreateIntentRequest request, Signer agentSigner) {
16+ return createIntent(request, agentSigner, System.currentTimeMillis());
17+ }
18+ 
19+ public static A4pResult<IntentL1> createIntent(CreateIntentRequest request, Signer agentSigner, long now) {
20+ return A4pResult.capture(() -> {
21+ Validation.integer(now, false);
22+ Validation.request(request);
23+ String intentId = request.intentId() == null ? UUID.randomUUID().toString() : request.intentId();
24+ IntentL1 unsigned = new IntentL1(PROTOCOL_VERSION, intentId, request.intentConversation(),
25+ request.intentSummary(), request.structuredIntent(), now, null);
26+ return new IntentL1(unsigned.version(), intentId, unsigned.intentConversation(), unsigned.intentSummary(),
27+ unsigned.structuredIntent(), now, sign(agentSigner, unsigned));
28+ });
29+ }
30+ 
31+ public static A4pResult<IntentL2> issueIntent(IntentL1 intent, SignatureVerifier agentVerifier,
32+ IntentIssueContext context, Signer serverSigner) {
33+ return issueIntent(intent, agentVerifier, context, serverSigner, System.currentTimeMillis());
34+ }
35+ 
36+ public static A4pResult<IntentL2> issueIntent(IntentL1 intent, SignatureVerifier agentVerifier,
37+ IntentIssueContext context, Signer serverSigner, long now) {
38+ return A4pResult.capture(() -> {
39+ Validation.integer(now, false);
40+ Validation.issueContext(context);
41+ Validation.intentL1(intent);
42+ Validation.version(intent.version());
43+ verifyOrThrow(agentVerifier, intent, intent.sign());
44+ // Chain timestamps are monotonic; refuse to emit an L2 that every peer would reject.
45+ require(now >= intent.timestamp(), A4P_INVALID_PARAMETER);
46+ IntentL2 unsigned = new IntentL2(PROTOCOL_VERSION, intent, context.userIdentity(),
47+ context.agentIdentity(), context.serviceProviderIdentity(), now, null);
48+ return new IntentL2(unsigned.version(), intent, unsigned.userIdentity(), unsigned.agentIdentity(),
49+ unsigned.serviceProviderIdentity(), now, sign(serverSigner, unsigned));
50+ });
51+ }
52+ 
53+ public static A4pResult<IntentL3> signIntent(IntentL2 intent, SignatureVerifier serverVerifier,
54+ SigningEnv environment, Signer userSigner) {
55+ return signIntent(intent, serverVerifier, environment, userSigner, System.currentTimeMillis());
56+ }
57+ 
58+ public static A4pResult<IntentL3> signIntent(IntentL2 intent, SignatureVerifier serverVerifier,
59+ SigningEnv environment, Signer userSigner, long now) {
60+ return A4pResult.capture(() -> {
61+ Validation.integer(now, false);
62+ Validation.signingEnv(environment);
63+ Validation.intentL2(intent);
64+ Validation.version(intent.version());
65+ verifyOrThrow(serverVerifier, intent, intent.sign());
66+ require(now >= intent.timestamp(), A4P_INVALID_PARAMETER);
67+ IntentL3 unsigned = new IntentL3(PROTOCOL_VERSION, intent, environment, now, null);
68+ return new IntentL3(PROTOCOL_VERSION, intent, environment, now, sign(userSigner, unsigned));
69+ });
70+ }
71+ 
72+ public static A4pResult<IntentExecutionContext> activateIntent(IntentL3 intent, SignatureVerifier userVerifier) {
73+ return activateIntent(intent, userVerifier, System.currentTimeMillis());
74+ }
75+ 
76+ public static A4pResult<IntentExecutionContext> activateIntent(IntentL3 intent, SignatureVerifier userVerifier,
77+ long now) {
78+ return A4pResult.capture(() -> {
79+ Validation.integer(now, false);
80+ Validation.intentL3(intent);
81+ Validation.versions(intent);
82+ verifyOrThrow(userVerifier, intent, intent.sign());
83+ require(now >= intent.timestamp(), A4P_INVALID_PARAMETER);
84+ // An intent past validUntil could never execute; one not yet valid is activated and waits for validFrom.
85+ PaymentConstraints constraints = PaymentProfile.constraints(intent.intentL2().intentL1().structuredIntent());
86+ require(now <= constraints.validUntil(), A4P_TIMESTAMP_EXPIRED);
87+ return new IntentExecutionContext(intent, now);
88+ });
89+ }
90+ 
91+ // Checks the whole L3 chain and the intent center's L2 signature; the user signature is not verified here.
92+ // It is a pure check on the intent, so it does not depend on any context status.
93+ public static A4pResult<VerificationResult> verifyIntentAuthenticity(IntentL3 intent,
94+ SignatureVerifier issuerVerifier) {
95+ return A4pResult.capture(() -> {
96+ Validation.intentL3(intent);
97+ Validation.versions(intent);
98+ return verify(issuerVerifier, intent.intentL2(), intent.intentL2().sign());
99+ });
100+ }
101+ 
102+ public static A4pResult<IntentExecutionContext> revokeIntent(IntentExecutionContext context) {
103+ return A4pResult.capture(() -> {
104+ Validation.present(context);
105+ synchronized (context) {
106+ require(context.status() == IntentExecutionStatus.ACTIVE, A4P_INVALID_STATUS);
107+ context.status(IntentExecutionStatus.REVOKED);
108+ return context;
109+ }
110+ });
111+ }
112+ 
113+ public static A4pResult<IntentExecutionContext> createExecution(IntentExecutionContext context,
114+ Execution execution) {
115+ return createExecution(context, execution, System.currentTimeMillis());
116+ }
117+ 
118+ // A failed call can still have flipped the context to EXPIRED, so callers persist the context either way.
119+ public static A4pResult<IntentExecutionContext> createExecution(IntentExecutionContext context,
120+ Execution execution, long now) {
121+ return A4pResult.capture(() -> reserve(context, execution, now));
122+ }
123+ 
124+ public static A4pResult<IntentExecutionContext> completeExecution(IntentExecutionContext context,
125+ String executionId) {
126+ return completeExecution(context, executionId, System.currentTimeMillis());
127+ }
128+ 
129+ public static A4pResult<IntentExecutionContext> completeExecution(IntentExecutionContext context,
130+ String executionId, long now) {
131+ return A4pResult.capture(() -> finalizeExecution(context, executionId, now, false));
132+ }
133+ 
134+ public static A4pResult<IntentExecutionContext> cancelExecution(IntentExecutionContext context,
135+ String executionId) {
136+ return cancelExecution(context, executionId, System.currentTimeMillis());
137+ }
138+ 
139+ public static A4pResult<IntentExecutionContext> cancelExecution(IntentExecutionContext context,
140+ String executionId, long now) {
141+ return A4pResult.capture(() -> finalizeExecution(context, executionId, now, true));
142+ }
143+ 
144+ private static IntentExecutionContext reserve(IntentExecutionContext context, Execution execution, long now) {
145+ Validation.integer(now, false);
146+ Validation.present(context);
147+ Order order = Validation.execution(execution);
148+ String executionId = execution.id() == null ? UUID.randomUUID().toString() : execution.id();
149+ synchronized (context) {
150+ // Parameter consistency comes before state and ledger checks, and the expiry flip before duplicates.
151+ IntentL1 intent = context.authorizedIntent().intentL2().intentL1();
152+ PaymentConstraints constraints = context.constraints();
153+ require(execution.version().equals(intent.version()), A4P_UNSUPPORTED_VERSION);
154+ require(execution.action() == intent.structuredIntent().action(), A4P_INVALID_PARAMETER);
155+ require(order.currency().equals(constraints.currency()), A4P_INVALID_PARAMETER);
156+ require(context.status() == IntentExecutionStatus.ACTIVE, A4P_INVALID_STATUS);
157+ require(now >= constraints.validFrom(), A4P_TIMESTAMP_TOO_EARLY);
158+ if (now > constraints.validUntil()) {
159+ context.status(IntentExecutionStatus.EXPIRED);
160+ throw new A4pException(A4P_TIMESTAMP_EXPIRED);
161+ }
162+ require(context.ledger().stream().noneMatch(entry -> entry.record().executionId().equals(executionId)),
163+ A4P_DUPLICATE_ID);
164+ // orderId is the payment idempotency key, so canceled records still block reuse.
165+ require(context.ledger().stream().noneMatch(entry -> entry.order().orderId().equals(order.orderId())),
166+ A4P_DUPLICATE_ID);
167+ if (constraints.maxExecuteCount() != null) {
168+ require(Accounting.count(context) < constraints.maxExecuteCount(), A4P_EXECUTION_COUNT_EXCEEDED);
169+ }
170+ if (constraints.singleOrderMaxAmount() != null) {
171+ require(order.amount() <= constraints.singleOrderMaxAmount(), A4P_SINGLE_ORDER_AMOUNT_EXCEEDED);
172+ }
173+ require(order.amount() <= Accounting.leftAmount(context), A4P_AMOUNT_EXCEEDED);
174+ enforceWhitelist(context, order.cartItems());
175+ Long period = Accounting.period(constraints, now);
176+ if (period != null) {
177+ require(Accounting.periodCount(context, period) < constraints.maxExecutionCountPerPeriod(),
178+ A4P_PERIOD_EXECUTION_COUNT_EXCEEDED);
179+ }
180+ Execution snapshot = new Execution(execution.action(), executionId, execution.version(),
181+ execution.executionContent());
182+ context.ledger().add(new IntentExecutionContext.Entry(new ExecutionRecord(executionId,
183+ ExecutionStatus.PENDING, period, now, null, null, snapshot), order));
184+ Accounting.recompute(context, now);
185+ return context;
186+ }
187+ }
188+ 
189+ private static IntentExecutionContext finalizeExecution(IntentExecutionContext context, String executionId,
190+ long now, boolean cancel) {
191+ Validation.integer(now, false);
192+ Validation.present(context);
193+ synchronized (context) {
194+ // Pending reservations made before revocation or expiry can still be finalized.
195+ require(context.status() == IntentExecutionStatus.ACTIVE || context.status() == IntentExecutionStatus.REVOKED
196+ || context.status() == IntentExecutionStatus.EXPIRED, A4P_INVALID_STATUS);
197+ List<IntentExecutionContext.Entry> ledger = context.ledger();
198+ int index = -1;
199+ for (int position = 0; position < ledger.size(); position++) {
200+ if (ledger.get(position).record().executionId().equals(executionId)) {
201+ index = position;
202+ break;
203+ }
204+ }
205+ require(index >= 0, A4P_INVALID_PARAMETER);
206+ IntentExecutionContext.Entry entry = ledger.get(index);
207+ ExecutionRecord record = entry.record();
208+ require(record.status() == ExecutionStatus.PENDING, A4P_INVALID_STATUS);
209+ // Record timestamps are monotonic like the chain's, so a persisted ledger can be checked for them.
210+ require(now >= record.reservedAt(), A4P_INVALID_PARAMETER);
211+ ExecutionRecord updated = new ExecutionRecord(record.executionId(),
212+ cancel ? ExecutionStatus.CANCELED : ExecutionStatus.COMPLETED, record.periodIndex(),
213+ record.reservedAt(), cancel ? null : now, cancel ? now : null, record.execution());
214+ ledger.set(index, new IntentExecutionContext.Entry(updated, entry.order()));
215+ if (cancel) {
216+ Accounting.recompute(context, now);
217+ } else if (context.status() == IntentExecutionStatus.ACTIVE && Accounting.exhausted(context)) {
218+ // REVOKED and EXPIRED are terminal; draining their ledger does not rewrite them.
219+ context.status(IntentExecutionStatus.CONSUMED);
220+ }
221+ return context;
222+ }
223+ }
224+ 
225+ private static void enforceWhitelist(IntentExecutionContext context, List<CartItem> items) {
226+ List<ItemWhiteList> groups = context.resources().itemsWhiteList();
227+ CartMatching.requireOneToOne(items, groups);
228+ // Quantity stays fail-closed: an item counts against every group that lists its product.
229+ for (ItemWhiteList group : groups) {
230+ BigInteger accumulated = context.ledger().stream().filter(Accounting::counted)
231+ .map(entry -> CartMatching.quantity(entry.order().cartItems(), group))
232+ .reduce(BigInteger.ZERO, BigInteger::add);
233+ require(accumulated.add(CartMatching.quantity(items, group))
234+ .compareTo(BigInteger.valueOf(group.quantity())) <= 0, A4P_PRODUCT_QUANTITY_EXCEEDED);
235+ }
236+ }
237+ 
238+ private static SignatureInfo sign(Signer signer, Object intent) {
239+ byte[] bytes = CanonicalJson.toSignableBytes(intent);
240+ try {
241+ SignatureInfo signature = signer.sign(bytes);
242+ Validation.signature(signature);
243+ return signature;
244+ } catch (Exception error) {
245+ throw new A4pException(A4P_SIGNING_FAIL);
246+ }
247+ }
248+ 
249+ private static VerificationResult verify(SignatureVerifier verifier, Object intent, SignatureInfo signature) {
250+ byte[] bytes = CanonicalJson.toSignableBytes(intent);
251+ try {
252+ VerificationResult result = verifier.verify(bytes, signature);
253+ // valid and code must agree; an inconsistent result is not trusted either way.
254+ if (result == null || result.valid() != (result.code() == A4P_SUCCESS.code())) {
255+ throw new A4pException(A4P_VERIFY_FAIL);
256+ }
257+ return result;
258+ } catch (Exception error) {
259+ throw new A4pException(A4P_VERIFY_FAIL);
260+ }
261+ }
262+ 
263+ private static void verifyOrThrow(SignatureVerifier verifier, Object intent, SignatureInfo signature) {
264+ require(verify(verifier, intent, signature).valid(), A4P_VERIFY_FAIL);
265+ }
266+}
@@ -0,0 +1,44 @@
1+package io.openjiuwen.a4p;
2+ 
3+public enum A4pErrorCode {
4+ A4P_SUCCESS(0, "Operation completed successfully"),
5+ A4P_INVALID_PARAMETER(1001, "Invalid parameter"),
6+ A4P_UNSUPPORTED_VERSION(1002, "Unsupported version"),
7+ A4P_DUPLICATE_ID(1003, "Duplicate ID"),
8+ A4P_SIGNING_FAIL(2001, "Signing failed"),
9+ A4P_VERIFY_FAIL(2002, "Verification failed"),
10+ A4P_INVALID_STATUS(3001, "Invalid status"),
11+ A4P_TIMESTAMP_EXPIRED(3002, "Timestamp expired"),
12+ A4P_TIMESTAMP_TOO_EARLY(3003, "Timestamp too early"),
13+ A4P_EXECUTION_COUNT_EXCEEDED(4001, "Execution count exceeded"),
14+ A4P_AMOUNT_EXCEEDED(4002, "Amount exceeded"),
15+ // Retained for ArkTS error-code compatibility; Java uses 4004 for per-period execution limits.
16+ A4P_PERIOD_COUNT_EXCEEDED(4003, "Period count exceeded"),
17+ A4P_PERIOD_EXECUTION_COUNT_EXCEEDED(4004, "Period execution count exceeded"),
18+ A4P_PRODUCT_QUANTITY_EXCEEDED(4005, "Product quantity exceeded"),
19+ A4P_SINGLE_ORDER_AMOUNT_EXCEEDED(4006, "Single order amount exceeded"),
20+ A4P_PRODUCT_NOT_AUTHORIZED(4007, "Product not authorized"),
21+ A4P_SERIALIZE_FAIL(5001, "Serialization failed"),
22+ A4P_DESERIALIZE_FAIL(5002, "Deserialization failed"),
23+ A4P_INTERNAL_ERROR(6001, "Unexpected internal error");
24+ 
25+ private final int code;
26+ private final String message;
27+ 
28+ A4pErrorCode(int code, String message) {
29+ this.code = code;
30+ this.message = message;
31+ }
32+ 
33+ public int code() { return code; }
34+ public String message() { return message; }
35+ 
36+ public static A4pErrorCode fromCode(int code) {
37+ for (A4pErrorCode value : values()) {
38+ if (value.code == code) {
39+ return value;
40+ }
41+ }
42+ return A4P_INTERNAL_ERROR;
43+ }
44+}
@@ -0,0 +1,16 @@
1+package io.openjiuwen.a4p;
2+ 
3+public final class A4pException extends RuntimeException {
4+ private final A4pErrorCode code;
5+ 
6+ public A4pException(A4pErrorCode code) {
7+ this(code, code.message(), null);
8+ }
9+ 
10+ public A4pException(A4pErrorCode code, String message, Throwable cause) {
11+ super(message, cause);
12+ this.code = code;
13+ }
14+ 
15+ public A4pErrorCode code() { return code; }
16+}
@@ -0,0 +1,23 @@
1+package io.openjiuwen.a4p;
2+ 
3+import io.openjiuwen.a4p.Models.*;
4+ 
5+public interface A4pIntentCodec {
6+ String serializeIntentL1(IntentL1 intentL1);
7+ 
8+ A4pResult<IntentL1> deserializeIntentL1(String serialized);
9+ 
10+ String serializeIntentL2(IntentL2 intentL2);
11+ 
12+ A4pResult<IntentL2> deserializeIntentL2(String serialized);
13+ 
14+ String serializeIntentL3(IntentL3 intentL3);
15+ 
16+ A4pResult<IntentL3> deserializeIntentL3(String serialized);
17+ 
18+ String serializeIntentExecutionContext(IntentExecutionContext intentExecutionContext);
19+ 
20+ A4pResult<IntentExecutionContext> deserializeIntentExecutionContext(String serialized);
21+ 
22+ static A4pIntentCodec standard() { return CanonicalIntentCodec.INSTANCE; }
23+}
@@ -0,0 +1,48 @@
1+package io.openjiuwen.a4p;
2+ 
3+import java.util.function.Supplier;
4+import static io.openjiuwen.a4p.A4pErrorCode.*;
5+ 
6+public final class A4pResult<T> {
7+ private final boolean success;
8+ private final T data;
9+ private final long code;
10+ private final String message;
11+ 
12+ private A4pResult(boolean success, T data, A4pErrorCode code) {
13+ this.success = success;
14+ this.data = data;
15+ this.code = code.code();
16+ this.message = code.message();
17+ }
18+ 
19+ public static <T> A4pResult<T> ok(T data) {
20+ if (data == null) { return failure(A4P_INTERNAL_ERROR); }
21+ return new A4pResult<>(true, data, A4P_SUCCESS);
22+ }
23+ 
24+ public static <T> A4pResult<T> failure(A4pErrorCode code) {
25+ return new A4pResult<>(false, null, code == null || code == A4P_SUCCESS ? A4P_INTERNAL_ERROR : code);
26+ }
27+ 
28+ public boolean success() { return success; }
29+ public T data() { return data; }
30+ public long code() { return code; }
31+ public String message() { return message; }
32+ 
33+ @Override
34+ public String toString() {
35+ return "A4pResult[success=" + success + ", code=" + code + ", message=" + message + "]";
36+ }
37+ 
38+ // Protocol failures become results; anything else is an SDK defect and surfaces as A4pException.
39+ static <T> A4pResult<T> capture(Supplier<T> action) {
40+ try {
41+ return ok(action.get());
42+ } catch (A4pException error) {
43+ return failure(error.code());
44+ } catch (RuntimeException error) {
45+ throw new A4pException(A4P_INTERNAL_ERROR, A4P_INTERNAL_ERROR.message(), error);
46+ }
47+ }
48+}
@@ -0,0 +1,61 @@
1+package io.openjiuwen.a4p;
2+ 
3+import io.openjiuwen.a4p.Models.*;
4+import java.math.BigInteger;
5+import java.util.Objects;
6+ 
7+final class Accounting {
8+ private Accounting() {}
9+ 
10+ static Long period(PaymentConstraints constraints, long now) {
11+ if (constraints.anchorTime() == null) { return null; }
12+ BigInteger elapsed = BigInteger.valueOf(now).subtract(BigInteger.valueOf(constraints.anchorTime()));
13+ BigInteger duration = BigInteger.valueOf(constraints.periodSeconds()).multiply(BigInteger.valueOf(1000));
14+ BigInteger[] quotient = elapsed.divideAndRemainder(duration);
15+ return (elapsed.signum() < 0 && quotient[1].signum() != 0
16+ ? quotient[0].subtract(BigInteger.ONE) : quotient[0]).longValueExact();
17+ }
18+ 
19+ static boolean counted(IntentExecutionContext.Entry entry) {
20+ return entry.record().status() != ExecutionStatus.CANCELED;
21+ }
22+ 
23+ static long count(IntentExecutionContext context) {
24+ return context.ledger().stream().filter(Accounting::counted).count();
25+ }
26+ 
27+ static long amount(IntentExecutionContext context) {
28+ return context.ledger().stream().filter(Accounting::counted).mapToLong(entry -> entry.order().amount()).sum();
29+ }
30+ 
31+ static long leftAmount(IntentExecutionContext context) {
32+ return context.constraints().totalMaxAmount() - amount(context);
33+ }
34+ 
35+ // The global quota is permanently used up and nothing is pending, so an ACTIVE intent becomes CONSUMED.
36+ static boolean exhausted(IntentExecutionContext context) {
37+ boolean pending = context.ledger().stream()
38+ .anyMatch(entry -> entry.record().status() == ExecutionStatus.PENDING);
39+ Long countCap = context.constraints().maxExecuteCount();
40+ boolean countUsedUp = countCap != null && count(context) >= countCap;
41+ return !pending && (countUsedUp || leftAmount(context) == 0);
42+ }
43+ 
44+ static long periodCount(IntentExecutionContext context, Long period) {
45+ return context.ledger().stream().filter(Accounting::counted)
46+ .filter(entry -> Objects.equals(entry.record().periodIndex(), period)).count();
47+ }
48+ 
49+ static void recompute(IntentExecutionContext context, long now) {
50+ context.executionInfo(executionInfo(context, period(context.constraints(), now)));
51+ }
52+ 
53+ static PaymentExecutionInfo executionInfo(IntentExecutionContext context, Long period) {
54+ PaymentConstraints constraints = context.constraints();
55+ return new PaymentExecutionInfo(
56+ constraints.maxExecuteCount() == null ? null : constraints.maxExecuteCount() - count(context),
57+ leftAmount(context),
58+ period,
59+ period == null ? null : constraints.maxExecutionCountPerPeriod() - periodCount(context, period));
60+ }
61+}
@@ -0,0 +1,135 @@
1+package io.openjiuwen.a4p;
2+ 
3+import com.fasterxml.jackson.databind.JsonNode;
4+import io.openjiuwen.a4p.Models.*;
5+import java.util.ArrayList;
6+import java.util.LinkedHashMap;
7+import java.util.List;
8+import java.util.Map;
9+import java.util.function.Consumer;
10+import static io.openjiuwen.a4p.A4pErrorCode.*;
11+ 
12+// Serializes to canonical JSON; deserialization parses strictly and validates the whole chain.
13+final class CanonicalIntentCodec implements A4pIntentCodec {
14+ static final CanonicalIntentCodec INSTANCE = new CanonicalIntentCodec();
15+ 
16+ // Wire form of a persisted context; reservedAt is boxed so a missing field is rejected instead of read as 0.
17+ record ContextJson(String version, String intentId, IntentL3 authorizedIntent, IntentExecutionStatus status,
18+ JsonNode executionInfo, List<RecordJson> executions) {}
19+ 
20+ record RecordJson(String executionId, ExecutionStatus status, Long periodIndex, Long reservedAt,
21+ Long completedAt, Long canceledAt, Execution execution) {}
22+ 
23+ private CanonicalIntentCodec() {}
24+ 
25+ @Override
26+ public String serializeIntentL1(IntentL1 intentL1) { return serialize(intentL1); }
27+ 
28+ @Override
29+ public String serializeIntentL2(IntentL2 intentL2) { return serialize(intentL2); }
30+ 
31+ @Override
32+ public String serializeIntentL3(IntentL3 intentL3) { return serialize(intentL3); }
33+ 
34+ @Override
35+ public A4pResult<IntentL1> deserializeIntentL1(String serialized) {
36+ return decode(serialized, IntentL1.class, Validation::intentL1);
37+ }
38+ 
39+ @Override
40+ public A4pResult<IntentL2> deserializeIntentL2(String serialized) {
41+ return decode(serialized, IntentL2.class, Validation::intentL2);
42+ }
43+ 
44+ @Override
45+ public A4pResult<IntentL3> deserializeIntentL3(String serialized) {
46+ return decode(serialized, IntentL3.class, Validation::intentL3);
47+ }
48+ 
49+ @Override
50+ public String serializeIntentExecutionContext(IntentExecutionContext intentExecutionContext) {
51+ Validation.present(intentExecutionContext);
52+ Map<String, Object> fields = new LinkedHashMap<>();
53+ // One lock for every field, so the ledger and executionInfo come from the same state.
54+ synchronized (intentExecutionContext) {
55+ fields.put("version", intentExecutionContext.version());
56+ fields.put("intentId", intentExecutionContext.intentId());
57+ fields.put("authorizedIntent", intentExecutionContext.authorizedIntent());
58+ fields.put("status", intentExecutionContext.status());
59+ fields.put("executionInfo", intentExecutionContext.executionInfo());
60+ fields.put("executions", intentExecutionContext.executions());
61+ }
62+ return CanonicalJson.stringify(fields);
63+ }
64+ 
65+ // The user signature is not re-verified; the stored L3 is checked like activateIntent's input otherwise.
66+ @Override
67+ public A4pResult<IntentExecutionContext> deserializeIntentExecutionContext(String serialized) {
68+ return A4pResult.capture(() -> restore(parse(serialized, ContextJson.class)));
69+ }
70+ 
71+ private static IntentExecutionContext restore(ContextJson wire) {
72+ Validation.present(wire);
73+ Validation.text(wire.version());
74+ Validation.version(wire.version());
75+ IntentL3 authorized = wire.authorizedIntent();
76+ Validation.intentL3(authorized);
77+ Validation.versions(authorized);
78+ IntentL1 intent = authorized.intentL2().intentL1();
79+ Validation.require(intent.intentId().equals(wire.intentId()), A4P_INVALID_PARAMETER);
80+ Validation.present(wire.status());
81+ Validation.present(wire.executions());
82+ List<IntentExecutionContext.Entry> ledger = new ArrayList<>();
83+ for (RecordJson record : wire.executions()) {
84+ Validation.present(record);
85+ Validation.integer(record.reservedAt(), false);
86+ Order order = Validation.execution(record.execution());
87+ ledger.add(new IntentExecutionContext.Entry(new ExecutionRecord(record.executionId(), record.status(),
88+ record.periodIndex(), record.reservedAt(), record.completedAt(), record.canceledAt(),
89+ record.execution()), order));
90+ }
91+ Long period = period(wire.executionInfo(), PaymentProfile.constraints(intent.structuredIntent()));
92+ IntentExecutionContext context = new IntentExecutionContext(authorized, wire.status(), ledger, period);
93+ Validation.ledger(context);
94+ // executionInfo is derived state, so it must match what the restored ledger yields.
95+ Validation.require(context.executionInfo().equals(CanonicalJson.freezeNode(wire.executionInfo())),
96+ A4P_INVALID_PARAMETER);
97+ return context;
98+ }
99+ 
100+ // The period executionInfo was last recomputed in depends on call times the ledger does not record.
101+ private static Long period(JsonNode info, PaymentConstraints constraints) {
102+ Validation.require(info != null && info.isObject(), A4P_INVALID_PARAMETER);
103+ JsonNode period = info.get("periodIndex");
104+ if (period == null || period.isNull()) {
105+ Validation.require(constraints.anchorTime() == null, A4P_INVALID_PARAMETER);
106+ return null;
107+ }
108+ Validation.require(constraints.anchorTime() != null && period.isIntegralNumber() && period.canConvertToLong(),
109+ A4P_INVALID_PARAMETER);
110+ return period.longValue();
111+ }
112+ 
113+ private static String serialize(Object intent) {
114+ Validation.present(intent);
115+ return CanonicalJson.stringify(intent);
116+ }
117+ 
118+ private static <Value> A4pResult<Value> decode(String json, Class<Value> type, Consumer<Value> validate) {
119+ return A4pResult.capture(() -> {
120+ Value value = parse(json, type);
121+ validate.accept(value);
122+ return value;
123+ });
124+ }
125+ 
126+ private static <Value> Value parse(String json, Class<Value> type) {
127+ Validation.require(json != null && !json.isEmpty(), A4P_INVALID_PARAMETER);
128+ Object parsed = CanonicalJson.parse(json);
129+ try {
130+ return CanonicalJson.MAPPER.convertValue(parsed, type);
131+ } catch (IllegalArgumentException error) {
132+ throw new A4pException(A4P_INVALID_PARAMETER);
133+ }
134+ }
135+}
@@ -0,0 +1,255 @@
1+package io.openjiuwen.a4p;
2+ 
3+import com.fasterxml.jackson.core.JsonFactory;
4+import com.fasterxml.jackson.core.StreamReadFeature;
5+import com.fasterxml.jackson.databind.DeserializationFeature;
6+import com.fasterxml.jackson.databind.JsonNode;
7+import com.fasterxml.jackson.databind.MapperFeature;
8+import com.fasterxml.jackson.databind.json.JsonMapper;
9+import com.fasterxml.jackson.databind.node.ArrayNode;
10+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
11+import com.fasterxml.jackson.databind.node.LongNode;
12+import com.fasterxml.jackson.databind.node.ObjectNode;
13+import java.lang.reflect.RecordComponent;
14+import java.math.BigDecimal;
15+import java.nio.ByteBuffer;
16+import java.nio.CharBuffer;
17+import java.nio.charset.CharacterCodingException;
18+import java.nio.charset.CodingErrorAction;
19+import java.nio.charset.StandardCharsets;
20+import java.util.ArrayList;
21+import java.util.Base64;
22+import java.util.Collections;
23+import java.util.IdentityHashMap;
24+import java.util.LinkedHashMap;
25+import java.util.List;
26+import java.util.Map;
27+import java.util.TreeMap;
28+import java.util.stream.Collectors;
29+ 
30+import static io.openjiuwen.a4p.A4pErrorCode.*;
31+ 
32+public final class CanonicalJson {
33+ public static final long MAX_SAFE_INTEGER = 9_007_199_254_740_991L;
34+ static final JsonMapper MAPPER = JsonMapper.builder(JsonFactory.builder()
35+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build())
36+ .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)
37+ .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT)
38+ .enable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS)
39+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
40+ .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
41+ .build();
42+ 
43+ private CanonicalJson() {}
44+ 
45+ public static String stringify(Object value) {
46+ try {
47+ return render(normalize(value, new IdentityHashMap<>(), 0));
48+ } catch (A4pException error) {
49+ throw error;
50+ } catch (Exception error) {
51+ throw new A4pException(A4P_SERIALIZE_FAIL);
52+ }
53+ }
54+ 
55+ public static byte[] toSignableBytes(Object intent) {
56+ Object normalized = normalize(intent, new IdentityHashMap<>(), 0);
57+ if (!(normalized instanceof Map<?, ?> fields)) {
58+ throw new A4pException(A4P_SERIALIZE_FAIL);
59+ }
60+ Map<Object, Object> unsigned = new LinkedHashMap<>(fields);
61+ unsigned.remove("sign");
62+ return encodeUtf8(stringify(unsigned));
63+ }
64+ 
65+ public static String base64UrlEncode(byte[] data) {
66+ return Base64.getUrlEncoder().withoutPadding().encodeToString(data);
67+ }
68+ 
69+ public static byte[] base64UrlDecode(String data) {
70+ try {
71+ if (data == null || !data.matches("[A-Za-z0-9_-]*")) {
72+ throw new IllegalArgumentException();
73+ }
74+ byte[] decoded = Base64.getUrlDecoder().decode(data);
75+ if (!base64UrlEncode(decoded).equals(data)) {
76+ throw new IllegalArgumentException();
77+ }
78+ return decoded;
79+ } catch (IllegalArgumentException error) {
80+ throw new A4pException(A4P_DESERIALIZE_FAIL);
81+ }
82+ }
83+ 
84+ public static byte[] encodeUtf8(String data) {
85+ try {
86+ ByteBuffer encoded = StandardCharsets.UTF_8.newEncoder()
87+ .onMalformedInput(CodingErrorAction.REPORT).encode(CharBuffer.wrap(data));
88+ byte[] bytes = new byte[encoded.remaining()];
89+ encoded.get(bytes);
90+ return bytes;
91+ } catch (CharacterCodingException | NullPointerException error) {
92+ throw new A4pException(A4P_SERIALIZE_FAIL);
93+ }
94+ }
95+ 
96+ public static String decodeUtf8(byte[] data) {
97+ try {
98+ return StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
99+ .decode(ByteBuffer.wrap(data)).toString();
100+ } catch (CharacterCodingException | NullPointerException error) {
101+ throw new A4pException(A4P_DESERIALIZE_FAIL);
102+ }
103+ }
104+ 
105+ static Object parse(String json) {
106+ try {
107+ return MAPPER.readValue(json, Object.class);
108+ } catch (Exception error) {
109+ throw new A4pException(A4P_DESERIALIZE_FAIL);
110+ }
111+ }
112+ 
113+ @SuppressWarnings("unchecked")
114+ static Map<String, Object> freezeMap(Map<String, Object> source) {
115+ return source == null ? null : (Map<String, Object>) normalize(source, new IdentityHashMap<>(), 0);
116+ }
117+ 
118+ // Deep copy that stores every integral number as a long, so equal payloads compare equal after a round trip.
119+ static JsonNode freezeNode(JsonNode node) {
120+ if (node == null) { return null; }
121+ if (node.isIntegralNumber() && node.canConvertToLong()) { return LongNode.valueOf(node.longValue()); }
122+ if (node.isObject()) {
123+ ObjectNode copy = JsonNodeFactory.instance.objectNode();
124+ node.properties().forEach(entry -> copy.set(entry.getKey(), freezeNode(entry.getValue())));
125+ return copy;
126+ }
127+ if (node.isArray()) {
128+ ArrayNode copy = JsonNodeFactory.instance.arrayNode();
129+ node.forEach(item -> copy.add(freezeNode(item)));
130+ return copy;
131+ }
132+ return node.deepCopy();
133+ }
134+ 
135+ private static Object normalizeNode(JsonNode node, IdentityHashMap<Object, Boolean> ancestors, int depth) {
136+ if (node.isNull()) { return null; }
137+ if (node.isTextual()) { return node.textValue(); }
138+ if (node.isBoolean()) { return node.booleanValue(); }
139+ if (node.isNumber()) { return normalize(node.numberValue(), ancestors, depth); }
140+ if (node.isObject()) {
141+ Map<String, Object> result = new TreeMap<>();
142+ node.properties().forEach(entry ->
143+ result.put(entry.getKey(), normalize(entry.getValue(), ancestors, depth + 1)));
144+ return Collections.unmodifiableMap(result);
145+ }
146+ if (node.isArray()) {
147+ List<Object> result = new ArrayList<>();
148+ node.forEach(item -> result.add(normalize(item, ancestors, depth + 1)));
149+ return Collections.unmodifiableList(result);
150+ }
151+ throw new A4pException(A4P_SERIALIZE_FAIL);
152+ }
153+ 
154+ private static Object normalize(Object value, IdentityHashMap<Object, Boolean> ancestors, int depth) {
155+ if (depth > 100) {
156+ throw new A4pException(A4P_SERIALIZE_FAIL);
157+ }
158+ if (value == null || value instanceof String || value instanceof Boolean) {
159+ return value;
160+ }
161+ if (value instanceof Number number) {
162+ try {
163+ long integer = new BigDecimal(number.toString()).longValueExact();
164+ if (integer < -MAX_SAFE_INTEGER || integer > MAX_SAFE_INTEGER) {
165+ throw new ArithmeticException();
166+ }
167+ return integer;
168+ } catch (ArithmeticException | NumberFormatException error) {
169+ throw new A4pException(A4P_SERIALIZE_FAIL);
170+ }
171+ }
172+ if (value instanceof Enum<?> constant && constant.getDeclaringClass().getEnclosingClass() == Models.class) {
173+ return constant.name();
174+ }
175+ if (value instanceof JsonNode node) {
176+ return normalizeNode(node, ancestors, depth);
177+ }
178+ if (ancestors.put(value, true) != null) {
179+ throw new A4pException(A4P_SERIALIZE_FAIL);
180+ }
181+ try {
182+ if (value instanceof Map<?, ?> source) {
183+ Map<String, Object> result = new TreeMap<>();
184+ for (Map.Entry<?, ?> entry : source.entrySet()) {
185+ if (!(entry.getKey() instanceof String key)) {
186+ throw new A4pException(A4P_SERIALIZE_FAIL);
187+ }
188+ result.put(key, normalize(entry.getValue(), ancestors, depth + 1));
189+ }
190+ return Collections.unmodifiableMap(result);
191+ }
192+ if (value instanceof List<?> source) {
193+ List<Object> result = new ArrayList<>();
194+ for (Object item : source) {
195+ result.add(normalize(item, ancestors, depth + 1));
196+ }
197+ return Collections.unmodifiableList(result);
198+ }
199+ if (value.getClass().isRecord() && value.getClass().getEnclosingClass() == Models.class) {
200+ Map<String, Object> fields = new TreeMap<>();
201+ for (RecordComponent component : value.getClass().getRecordComponents()) {
202+ Object field = component.getAccessor().invoke(value);
203+ if (field != null) {
204+ fields.put(component.getName(), normalize(field, ancestors, depth + 1));
205+ }
206+ }
207+ return Collections.unmodifiableMap(fields);
208+ }
209+ throw new A4pException(A4P_SERIALIZE_FAIL);
210+ } catch (ReflectiveOperationException error) {
211+ throw new A4pException(A4P_SERIALIZE_FAIL);
212+ } finally {
213+ ancestors.remove(value);
214+ }
215+ }
216+ 
217+ private static String render(Object value) {
218+ if (value == null) { return "null"; }
219+ if (value instanceof String text) { return quote(text); }
220+ if (value instanceof Map<?, ?> fields) {
221+ return fields.entrySet().stream()
222+ .map(entry -> quote((String) entry.getKey()) + ":" + render(entry.getValue()))
223+ .collect(Collectors.joining(",", "{", "}"));
224+ }
225+ if (value instanceof List<?> items) {
226+ return items.stream().map(CanonicalJson::render).collect(Collectors.joining(",", "[", "]"));
227+ }
228+ return value.toString();
229+ }
230+ 
231+ private static String quote(String text) {
232+ encodeUtf8(text);
233+ StringBuilder result = new StringBuilder("\"");
234+ for (int index = 0; index < text.length(); index++) {
235+ char character = text.charAt(index);
236+ switch (character) {
237+ case '"' -> result.append("\\\"");
238+ case '\\' -> result.append("\\\\");
239+ case '\b' -> result.append("\\b");
240+ case '\f' -> result.append("\\f");
241+ case '\n' -> result.append("\\n");
242+ case '\r' -> result.append("\\r");
243+ case '\t' -> result.append("\\t");
244+ default -> {
245+ if (character < 0x20) {
246+ result.append(String.format("\\u%04x", (int) character));
247+ } else {
248+ result.append(character);
249+ }
250+ }
251+ }
252+ }
253+ return result.append('"').toString();
254+ }
255+}
@@ -0,0 +1,46 @@
1+package io.openjiuwen.a4p;
2+ 
3+import io.openjiuwen.a4p.Models.*;
4+import java.math.BigInteger;
5+import java.util.Arrays;
6+import java.util.List;
7+import static io.openjiuwen.a4p.A4pErrorCode.*;
8+ 
9+// Whitelist groups are ANDed: every group is bought through its own cart item, in any cart order.
10+final class CartMatching {
11+ private CartMatching() {}
12+ 
13+ // Requires a one-to-one assignment of cart items to groups whose whitelist contains the item's product.
14+ static void requireOneToOne(List<CartItem> items, List<ItemWhiteList> groups) {
15+ Validation.require(items.size() == groups.size(), A4P_INVALID_PARAMETER);
16+ int[] owner = new int[groups.size()];
17+ Arrays.fill(owner, -1);
18+ for (int item = 0; item < items.size(); item++) {
19+ Validation.require(assign(item, items, groups, owner, new boolean[groups.size()]),
20+ A4P_PRODUCT_NOT_AUTHORIZED);
21+ }
22+ }
23+ 
24+ static boolean matches(ItemWhiteList group, Product product) {
25+ return group.whiteList().stream().anyMatch(product::equals);
26+ }
27+ 
28+ static BigInteger quantity(List<CartItem> items, ItemWhiteList group) {
29+ return items.stream().filter(item -> matches(group, item.product()))
30+ .map(item -> BigInteger.valueOf(item.quantity())).reduce(BigInteger.ZERO, BigInteger::add);
31+ }
32+ 
33+ // Augmenting path: a greedy pick can block a later item, so earlier assignments may be moved.
34+ private static boolean assign(int item, List<CartItem> items, List<ItemWhiteList> groups, int[] owner,
35+ boolean[] visited) {
36+ for (int group = 0; group < groups.size(); group++) {
37+ if (visited[group] || !matches(groups.get(group), items.get(item).product())) { continue; }
38+ visited[group] = true;
39+ if (owner[group] < 0 || assign(owner[group], items, groups, owner, visited)) {
40+ owner[group] = item;
41+ return true;
42+ }
43+ }
44+ return false;
45+ }
46+}
@@ -0,0 +1,57 @@
1+package io.openjiuwen.a4p;
2+ 
3+import com.fasterxml.jackson.databind.JsonNode;
4+import io.openjiuwen.a4p.Models.*;
5+import java.util.ArrayList;
6+import java.util.List;
7+ 
8+public final class IntentExecutionContext {
9+ private final IntentL3 authorizedIntent;
10+ private final ShoppingItems resources;
11+ private final PaymentConstraints constraints;
12+ private IntentExecutionStatus status = IntentExecutionStatus.ACTIVE;
13+ private final List<Entry> ledger = new ArrayList<>();
14+ private PaymentExecutionInfo executionInfo;
15+ 
16+ // A ledger record together with its parsed AI_PAY order.
17+ record Entry(ExecutionRecord record, Order order) {}
18+ 
19+ IntentExecutionContext(IntentL3 authorizedIntent, long now) {
20+ this(authorizedIntent);
21+ Accounting.recompute(this, now);
22+ }
23+ 
24+ // Restores a persisted context; executionInfo is recomputed for the period it was last computed in.
25+ IntentExecutionContext(IntentL3 authorizedIntent, IntentExecutionStatus status, List<Entry> ledger,
26+ Long period) {
27+ this(authorizedIntent);
28+ this.status = status;
29+ this.ledger.addAll(ledger);
30+ this.executionInfo = Accounting.executionInfo(this, period);
31+ }
32+ 
33+ private IntentExecutionContext(IntentL3 authorizedIntent) {
34+ this.authorizedIntent = authorizedIntent;
35+ StructuredIntent intent = authorizedIntent.intentL2().intentL1().structuredIntent();
36+ this.resources = PaymentProfile.resources(intent);
37+ this.constraints = PaymentProfile.constraints(intent);
38+ }
39+ 
40+ public String version() { return A4p.PROTOCOL_VERSION; }
41+ public String intentId() { return authorizedIntent.intentL2().intentL1().intentId(); }
42+ public IntentL3 authorizedIntent() { return authorizedIntent; }
43+ public synchronized IntentExecutionStatus status() { return status; }
44+ public synchronized List<ExecutionRecord> executions() { return ledger.stream().map(Entry::record).toList(); }
45+ 
46+ // Typed union: the action selects the schema; read it as PaymentExecutionInfo via PaymentProfile.
47+ public synchronized JsonNode executionInfo() {
48+ return CanonicalJson.freezeNode(CanonicalJson.MAPPER.valueToTree(executionInfo));
49+ }
50+ 
51+ synchronized PaymentExecutionInfo paymentExecutionInfo() { return executionInfo; }
52+ void status(IntentExecutionStatus status) { this.status = status; }
53+ void executionInfo(PaymentExecutionInfo info) { this.executionInfo = info; }
54+ List<Entry> ledger() { return ledger; }
55+ ShoppingItems resources() { return resources; }
56+ PaymentConstraints constraints() { return constraints; }
57+}
@@ -0,0 +1,104 @@
1+package io.openjiuwen.a4p;
2+ 
3+import com.fasterxml.jackson.databind.JsonNode;
4+import java.util.ArrayList;
5+import java.util.Collections;
6+import java.util.List;
7+import java.util.Map;
8+ 
9+public final class Models {
10+ private Models() {}
11+ 
12+ // Every enum is serialized by name, e.g. "AI_PAY".
13+ public enum IntentActionType { AI_PAY }
14+ 
15+ public enum AlgorithmType { RSA3072 }
16+ 
17+ public enum IntentExecutionStatus { ACTIVE, CONSUMED, REVOKED, EXPIRED }
18+ 
19+ public enum ExecutionStatus { PENDING, COMPLETED, CANCELED }
20+ 
21+ // AI_PAY payload types; PaymentProfile maps them to and from the JsonNode fields below.
22+ public record SellerInfo(String id) {}
23+ public record SpuSkuInfo(String spuId, String skuId) {}
24+ public record Product(SellerInfo seller, SpuSkuInfo spusku) {}
25+ public record CartItem(Product product, Long quantity) {}
26+ 
27+ public record ItemWhiteList(List<Product> whiteList, Long quantity) {
28+ public ItemWhiteList { whiteList = snapshot(whiteList); }
29+ }
30+ 
31+ public record ShoppingItems(List<ItemWhiteList> itemsWhiteList) {
32+ public ShoppingItems { itemsWhiteList = snapshot(itemsWhiteList); }
33+ }
34+ 
35+ public record PaymentConstraints(Long singleOrderMaxAmount, Long totalMaxAmount, String currency,
36+ Long validFrom, Long validUntil, Long maxExecuteCount,
37+ Long anchorTime, Long periodSeconds, Long maxExecutionCountPerPeriod) {}
38+ 
39+ public record Order(String orderId, Long amount, String currency, List<CartItem> cartItems, Long timestamp) {
40+ public Order { cartItems = snapshot(cartItems); }
41+ }
42+ 
43+ // Non-applicable figures are null and still serialized, so every field is always declared.
44+ public record PaymentExecutionInfo(Long leftExecutionCount, long leftAmount, Long periodIndex,
45+ Long leftPeriodExecutionCount) {}
46+ 
47+ // Typed union: the action selects the schema of resources and constraints.
48+ public record StructuredIntent(IntentActionType action, JsonNode resources, JsonNode constraints) {
49+ public StructuredIntent {
50+ resources = CanonicalJson.freezeNode(resources);
51+ constraints = CanonicalJson.freezeNode(constraints);
52+ }
53+ 
54+ @Override
55+ public JsonNode resources() { return CanonicalJson.freezeNode(resources); }
56+ 
57+ @Override
58+ public JsonNode constraints() { return CanonicalJson.freezeNode(constraints); }
59+ }
60+ 
61+ public record UserIdentity(String identityProvider, String id, String additionalInfo) {}
62+ public record AgentIdentity(String identityProvider, String id, String additionalInfo) {}
63+ public record ServiceProviderIdentity(String id, String additionalInfo) {}
64+ 
65+ public record SigningEnv(Map<String, Object> device, Map<String, Object> app) {
66+ public SigningEnv {
67+ device = CanonicalJson.freezeMap(device);
68+ app = CanonicalJson.freezeMap(app);
69+ }
70+ }
71+ 
72+ public record SignatureInfo(String alg, String keyIdentifier, String sign) {
73+ public SignatureInfo(AlgorithmType alg, String keyIdentifier, String sign) {
74+ this(alg == null ? null : alg.name(), keyIdentifier, sign);
75+ }
76+ }
77+ 
78+ public record CreateIntentRequest(String intentConversation, String intentSummary,
79+ StructuredIntent structuredIntent, String intentId) {}
80+ public record IntentIssueContext(UserIdentity userIdentity, AgentIdentity agentIdentity,
81+ ServiceProviderIdentity serviceProviderIdentity) {}
82+ public record VerificationResult(boolean valid, long code, String message) {}
83+ public record IntentL1(String version, String intentId, String intentConversation, String intentSummary,
84+ StructuredIntent structuredIntent, Long timestamp, SignatureInfo sign) {}
85+ public record IntentL2(String version, IntentL1 intentL1, UserIdentity userIdentity,
86+ AgentIdentity agentIdentity, ServiceProviderIdentity serviceProviderIdentity,
87+ Long timestamp, SignatureInfo sign) {}
88+ public record IntentL3(String version, IntentL2 intentL2, SigningEnv signingEnv,
89+ Long timestamp, SignatureInfo sign) {}
90+ 
91+ public record Execution(IntentActionType action, String id, String version, JsonNode executionContent) {
92+ public Execution { executionContent = CanonicalJson.freezeNode(executionContent); }
93+ 
94+ @Override
95+ public JsonNode executionContent() { return CanonicalJson.freezeNode(executionContent); }
96+ }
97+ 
98+ public record ExecutionRecord(String executionId, ExecutionStatus status, Long periodIndex,
99+ long reservedAt, Long completedAt, Long canceledAt, Execution execution) {}
100+ 
101+ private static <Value> List<Value> snapshot(List<Value> values) {
102+ return values == null ? null : Collections.unmodifiableList(new ArrayList<>(values));
103+ }
104+}
@@ -0,0 +1,75 @@
1+package io.openjiuwen.a4p;
2+ 
3+import com.fasterxml.jackson.annotation.JsonInclude;
4+import com.fasterxml.jackson.databind.JsonNode;
5+import com.fasterxml.jackson.databind.json.JsonMapper;
6+import io.openjiuwen.a4p.Models.*;
7+import static io.openjiuwen.a4p.A4pErrorCode.*;
8+ 
9+// Payment Profile of the typed union for action AI_PAY (API spec section 4.5).
10+public final class PaymentProfile {
11+ // Absent optional fields are omitted, matching the canonical form the ArkTS peer signs.
12+ private static final JsonMapper PAYLOAD_MAPPER = CanonicalJson.MAPPER.rebuild()
13+ .defaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.NON_NULL,
14+ JsonInclude.Include.NON_NULL))
15+ .build();
16+ 
17+ private PaymentProfile() {}
18+ 
19+ public static StructuredIntent structuredIntent(ShoppingItems resources, PaymentConstraints constraints) {
20+ return new StructuredIntent(IntentActionType.AI_PAY, toNode(resources), toNode(constraints));
21+ }
22+ 
23+ public static Execution execution(String id, String version, Order order) {
24+ return new Execution(IntentActionType.AI_PAY, id, version, toNode(order));
25+ }
26+ 
27+ public static ShoppingItems resources(StructuredIntent intent) {
28+ Validation.present(intent);
29+ requireAction(intent.action());
30+ return parse(intent.resources(), ShoppingItems.class);
31+ }
32+ 
33+ public static PaymentConstraints constraints(StructuredIntent intent) {
34+ Validation.present(intent);
35+ requireAction(intent.action());
36+ return parse(intent.constraints(), PaymentConstraints.class);
37+ }
38+ 
39+ public static Order order(Execution execution) {
40+ Validation.present(execution);
41+ requireAction(execution.action());
42+ return parse(execution.executionContent(), Order.class);
43+ }
44+ 
45+ public static PaymentExecutionInfo executionInfo(IntentExecutionContext context) {
46+ Validation.present(context);
47+ return context.paymentExecutionInfo();
48+ }
49+ 
50+ private static void requireAction(IntentActionType action) {
51+ Validation.require(action == IntentActionType.AI_PAY, A4P_INVALID_PARAMETER);
52+ }
53+ 
54+ private static JsonNode toNode(Object value) {
55+ return value == null ? null : CanonicalJson.freezeNode(PAYLOAD_MAPPER.valueToTree(value));
56+ }
57+ 
58+ // Explicit nulls are rejected like the ArkTS validators do; absent fields are the only way to omit a value.
59+ private static <Value> Value parse(JsonNode node, Class<Value> type) {
60+ Validation.require(node != null && !containsNull(node), A4P_INVALID_PARAMETER);
61+ try {
62+ return CanonicalJson.MAPPER.treeToValue(node, type);
63+ } catch (Exception error) {
64+ throw new A4pException(A4P_INVALID_PARAMETER);
65+ }
66+ }
67+ 
68+ private static boolean containsNull(JsonNode node) {
69+ if (node.isNull()) { return true; }
70+ for (JsonNode child : node) {
71+ if (containsNull(child)) { return true; }
72+ }
73+ return false;
74+ }
75+}
@@ -0,0 +1,63 @@
1+package io.openjiuwen.a4p;
2+ 
3+import io.openjiuwen.a4p.Models.*;
4+import java.security.PrivateKey;
5+import java.security.PublicKey;
6+import java.security.Signature;
7+import java.security.interfaces.RSAKey;
8+import java.util.HashMap;
9+import java.util.Map;
10+ 
11+public final class Rsa3072 {
12+ private Rsa3072() {}
13+ 
14+ public static Signer signer(String keyIdentifier, PrivateKey privateKey) {
15+ Validation.text(keyIdentifier);
16+ requireKey(privateKey);
17+ return data -> {
18+ Signature signer = Signature.getInstance("SHA256withRSA");
maoqiming
maoqimingmaoqiming20 days ago

【review】设计建议。签名使用 SHA256withRSA(PKCS#1 v1.5),属于可接受但非首选的 RSA 方案。如果协议可与 ArkTS/Python 对端同步演进,建议迁移到 RSASSA-PSS(SHA256withRSA/PSS)以提升签名方案安全性;若需保持现有互操作可暂不修改,仅记录为协议演进项。

likedislike
machuan
machuan
20 days ago Comments:
likedislike
19+ signer.initSign(privateKey);
20+ signer.update(data);
21+ return new SignatureInfo(AlgorithmType.RSA3072, keyIdentifier,
22+ CanonicalJson.base64UrlEncode(signer.sign()));
23+ };
24+ }
25+ 
26+ // Codes follow the A4pErrorCode set; message names the reason for diagnostics only.
27+ public static SignatureVerifier verifier(Map<String, PublicKey> trustedKeys) {
28+ Validation.present(trustedKeys);
29+ // Copied into a HashMap first, which admits nulls, so they are rejected as A4pException.
30+ Map<String, PublicKey> copy = new HashMap<>(trustedKeys);
31+ copy.forEach((keyIdentifier, key) -> {
32+ Validation.text(keyIdentifier);
33+ requireKey(key);
34+ });
35+ Map<String, PublicKey> keys = Map.copyOf(copy);
36+ return (data, info) -> {
37+ if (info == null || !AlgorithmType.RSA3072.name().equals(info.alg())
38+ || info.keyIdentifier() == null || !keys.containsKey(info.keyIdentifier())) {
39+ return rejected("UNTRUSTED_KEY_OR_ALGORITHM");
40+ }
41+ try {
42+ Signature verifier = Signature.getInstance("SHA256withRSA");
43+ verifier.initVerify(keys.get(info.keyIdentifier()));
44+ verifier.update(data);
45+ if (verifier.verify(CanonicalJson.base64UrlDecode(info.sign()))) {
46+ return new VerificationResult(true, A4pErrorCode.A4P_SUCCESS.code(), null);
47+ }
48+ return rejected("INVALID_SIGNATURE");
49+ } catch (Exception error) {
50+ return rejected("INVALID_SIGNATURE");
51+ }
52+ };
53+ }
54+ 
55+ private static VerificationResult rejected(String reason) {
56+ return new VerificationResult(false, A4pErrorCode.A4P_VERIFY_FAIL.code(), reason);
57+ }
58+ 
59+ private static void requireKey(Object key) {
60+ Validation.require(key instanceof RSAKey rsa && rsa.getModulus().bitLength() == 3072,
61+ A4pErrorCode.A4P_INVALID_PARAMETER);
62+ }
63+}
@@ -0,0 +1,9 @@
1+package io.openjiuwen.a4p;
2+ 
3+import io.openjiuwen.a4p.Models.SignatureInfo;
4+import io.openjiuwen.a4p.Models.VerificationResult;
5+ 
6+@FunctionalInterface
7+public interface SignatureVerifier {
8+ VerificationResult verify(byte[] data, SignatureInfo signature) throws Exception;
9+}
@@ -0,0 +1,8 @@
1+package io.openjiuwen.a4p;
2+ 
3+import io.openjiuwen.a4p.Models.SignatureInfo;
4+ 
5+@FunctionalInterface
6+public interface Signer {
7+ SignatureInfo sign(byte[] data) throws Exception;
8+}
@@ -0,0 +1,246 @@
1+package io.openjiuwen.a4p;
2+ 
3+import io.openjiuwen.a4p.Models.*;
4+import java.math.BigInteger;
5+import java.util.HashMap;
6+import java.util.HashSet;
7+import java.util.List;
8+import java.util.Map;
9+import java.util.Objects;
10+import java.util.Set;
11+import static io.openjiuwen.a4p.A4pErrorCode.*;
12+ 
13+final class Validation {
14+ static final long MAX_PERIOD_SECONDS = CanonicalJson.MAX_SAFE_INTEGER / 1000;
15+ 
16+ private Validation() {}
17+ 
18+ static void require(boolean condition, A4pErrorCode code) {
19+ if (!condition) { throw new A4pException(code); }
20+ }
21+ 
22+ static void present(Object value) { require(value != null, A4P_INVALID_PARAMETER); }
23+ static void text(String value) { require(value != null && !blank(value), A4P_INVALID_PARAMETER); }
24+ static void optionalText(String value) { if (value != null) { text(value); } }
25+ 
26+ // Matches ArkTS String.prototype.trim(), whose whitespace set differs from Character.isWhitespace.
27+ private static boolean blank(String value) {
28+ return value.chars().allMatch(character -> character == '\t' || character == 0x0B || character == '\f'
29+ || character == ' ' || character == 0xA0 || character == 0xFEFF || character == '\n'
30+ || character == '\r' || character == 0x2028 || character == 0x2029
31+ || Character.getType(character) == Character.SPACE_SEPARATOR);
32+ }
33+ 
34+ static void integer(Long value, boolean positive) {
35+ require(value != null && value >= (positive ? 1 : 0)
36+ && value <= CanonicalJson.MAX_SAFE_INTEGER, A4P_INVALID_PARAMETER);
37+ }
38+ 
39+ static void request(CreateIntentRequest request) {
40+ present(request);
41+ text(request.intentConversation());
42+ text(request.intentSummary());
43+ optionalText(request.intentId());
44+ structured(request.structuredIntent());
45+ }
46+ 
47+ private static void structured(StructuredIntent intent) {
48+ present(intent);
49+ require(intent.action() == IntentActionType.AI_PAY, A4P_INVALID_PARAMETER);
50+ ShoppingItems resources = PaymentProfile.resources(intent);
51+ nonempty(resources.itemsWhiteList());
52+ for (ItemWhiteList group : resources.itemsWhiteList()) {
53+ present(group);
54+ integer(group.quantity(), true);
55+ nonempty(group.whiteList());
56+ group.whiteList().forEach(Validation::product);
57+ }
58+ PaymentConstraints constraints = PaymentProfile.constraints(intent);
59+ integer(constraints.totalMaxAmount(), true);
60+ text(constraints.currency());
61+ integer(constraints.validFrom(), false);
62+ integer(constraints.validUntil(), false);
63+ require(constraints.validFrom() <= constraints.validUntil(), A4P_INVALID_PARAMETER);
64+ if (constraints.singleOrderMaxAmount() != null) { integer(constraints.singleOrderMaxAmount(), true); }
65+ if (constraints.maxExecuteCount() != null) { integer(constraints.maxExecuteCount(), true); }
66+ if (constraints.anchorTime() != null || constraints.periodSeconds() != null
67+ || constraints.maxExecutionCountPerPeriod() != null) {
68+ integer(constraints.anchorTime(), false);
69+ // A later anchor would give pre-anchor reservations negative periods, each with a fresh budget.
70+ require(constraints.anchorTime() <= constraints.validFrom(), A4P_INVALID_PARAMETER);
71+ integer(constraints.periodSeconds(), true);
72+ require(constraints.periodSeconds() <= MAX_PERIOD_SECONDS, A4P_INVALID_PARAMETER);
73+ integer(constraints.maxExecutionCountPerPeriod(), true);
74+ }
75+ }
76+ 
77+ // Seller id + spuId + skuId is the whitelist matching key, so blank ids must not match vacuously.
78+ private static void product(Product product) {
79+ present(product);
80+ present(product.seller());
81+ text(product.seller().id());
82+ present(product.spusku());
83+ optionalText(product.spusku().spuId());
84+ optionalText(product.spusku().skuId());
85+ require(product.spusku().spuId() != null || product.spusku().skuId() != null, A4P_INVALID_PARAMETER);
86+ }
87+ 
88+ private static void nonempty(List<?> values) {
89+ require(values != null && !values.isEmpty(), A4P_INVALID_PARAMETER);
90+ }
91+ 
92+ static void issueContext(IntentIssueContext context) {
93+ present(context);
94+ present(context.userIdentity());
95+ text(context.userIdentity().identityProvider());
96+ text(context.userIdentity().id());
97+ present(context.agentIdentity());
98+ text(context.agentIdentity().identityProvider());
99+ text(context.agentIdentity().id());
100+ present(context.serviceProviderIdentity());
101+ text(context.serviceProviderIdentity().id());
102+ }
103+ 
104+ static void signingEnv(SigningEnv environment) {
105+ present(environment);
106+ present(environment.device());
107+ present(environment.app());
108+ }
109+ 
110+ // alg and keyIdentifier are detached from the signed bytes, so unknown algorithms are rejected structurally.
111+ static void signature(SignatureInfo signature) {
112+ present(signature);
113+ require(AlgorithmType.RSA3072.name().equals(signature.alg()), A4P_INVALID_PARAMETER);
114+ text(signature.keyIdentifier());
115+ text(signature.sign());
116+ }
117+ 
118+ static void intentL1(IntentL1 intent) {
119+ present(intent);
120+ text(intent.version());
121+ text(intent.intentId());
122+ request(new CreateIntentRequest(intent.intentConversation(), intent.intentSummary(),
123+ intent.structuredIntent(), intent.intentId()));
124+ integer(intent.timestamp(), false);
125+ signature(intent.sign());
126+ }
127+ 
128+ static void intentL2(IntentL2 intent) {
129+ present(intent);
130+ text(intent.version());
131+ intentL1(intent.intentL1());
132+ issueContext(new IntentIssueContext(intent.userIdentity(), intent.agentIdentity(),
133+ intent.serviceProviderIdentity()));
134+ integer(intent.timestamp(), false);
135+ require(intent.timestamp() >= intent.intentL1().timestamp(), A4P_INVALID_PARAMETER);
136+ signature(intent.sign());
137+ }
138+ 
139+ static void intentL3(IntentL3 intent) {
140+ present(intent);
141+ text(intent.version());
142+ intentL2(intent.intentL2());
143+ signingEnv(intent.signingEnv());
144+ integer(intent.timestamp(), false);
145+ require(intent.timestamp() >= intent.intentL2().timestamp(), A4P_INVALID_PARAMETER);
146+ signature(intent.sign());
147+ }
148+ 
149+ // Returns the AI_PAY order parsed from the typed-union executionContent.
150+ static Order execution(Execution execution) {
151+ present(execution);
152+ require(execution.action() == IntentActionType.AI_PAY, A4P_INVALID_PARAMETER);
153+ text(execution.version());
154+ optionalText(execution.id());
155+ Order order = PaymentProfile.order(execution);
156+ text(order.orderId());
157+ integer(order.amount(), true);
158+ text(order.currency());
159+ integer(order.timestamp(), false);
160+ nonempty(order.cartItems());
161+ for (CartItem item : order.cartItems()) {
162+ present(item);
163+ product(item.product());
164+ integer(item.quantity(), true);
165+ }
166+ return order;
167+ }
168+ 
169+ static void versions(IntentL3 intent) {
170+ version(intent.version());
171+ version(intent.intentL2().version());
172+ version(intent.intentL2().intentL1().version());
173+ }
174+ 
175+ // A persisted ledger is untrusted: it must be one the execution operations could have produced for the
176+ // authorized intent, and a violation fails with the code the offending operation would have returned.
177+ static void ledger(IntentExecutionContext context) {
178+ IntentL1 intent = context.authorizedIntent().intentL2().intentL1();
179+ PaymentConstraints constraints = context.constraints();
180+ List<ItemWhiteList> groups = context.resources().itemsWhiteList();
181+ Set<String> executionIds = new HashSet<>();
182+ Set<String> orderIds = new HashSet<>();
183+ Map<Long, Long> periodCounts = new HashMap<>();
184+ BigInteger amount = BigInteger.ZERO;
185+ for (IntentExecutionContext.Entry entry : context.ledger()) {
186+ ExecutionRecord record = entry.record();
187+ Order order = entry.order();
188+ text(record.executionId());
189+ present(record.status());
190+ require(record.executionId().equals(record.execution().id()), A4P_INVALID_PARAMETER);
191+ require(record.execution().version().equals(intent.version()), A4P_UNSUPPORTED_VERSION);
192+ require(record.execution().action() == intent.structuredIntent().action(), A4P_INVALID_PARAMETER);
193+ require(order.currency().equals(constraints.currency()), A4P_INVALID_PARAMETER);
194+ require(record.reservedAt() >= constraints.validFrom(), A4P_TIMESTAMP_TOO_EARLY);
195+ require(record.reservedAt() <= constraints.validUntil(), A4P_TIMESTAMP_EXPIRED);
196+ require(Objects.equals(record.periodIndex(), Accounting.period(constraints, record.reservedAt())),
197+ A4P_INVALID_PARAMETER);
198+ finalizedAt(record.completedAt(), record.status() == ExecutionStatus.COMPLETED, record.reservedAt());
199+ finalizedAt(record.canceledAt(), record.status() == ExecutionStatus.CANCELED, record.reservedAt());
200+ require(executionIds.add(record.executionId()), A4P_DUPLICATE_ID);
201+ require(orderIds.add(order.orderId()), A4P_DUPLICATE_ID);
202+ if (constraints.singleOrderMaxAmount() != null) {
203+ require(order.amount() <= constraints.singleOrderMaxAmount(), A4P_SINGLE_ORDER_AMOUNT_EXCEEDED);
204+ }
205+ CartMatching.requireOneToOne(order.cartItems(), groups);
206+ if (Accounting.counted(entry)) {
207+ amount = amount.add(BigInteger.valueOf(order.amount()));
208+ if (record.periodIndex() != null) { periodCounts.merge(record.periodIndex(), 1L, Long::sum); }
209+ }
210+ }
211+ if (constraints.maxExecuteCount() != null) {
212+ require(Accounting.count(context) <= constraints.maxExecuteCount(), A4P_EXECUTION_COUNT_EXCEEDED);
213+ }
214+ require(amount.compareTo(BigInteger.valueOf(constraints.totalMaxAmount())) <= 0, A4P_AMOUNT_EXCEEDED);
215+ if (constraints.maxExecutionCountPerPeriod() != null) {
216+ require(periodCounts.values().stream().allMatch(count -> count <= constraints.maxExecutionCountPerPeriod()),
217+ A4P_PERIOD_EXECUTION_COUNT_EXCEEDED);
218+ }
219+ for (ItemWhiteList group : groups) {
220+ BigInteger accumulated = context.ledger().stream().filter(Accounting::counted)
221+ .map(entry -> CartMatching.quantity(entry.order().cartItems(), group))
222+ .reduce(BigInteger.ZERO, BigInteger::add);
223+ require(accumulated.compareTo(BigInteger.valueOf(group.quantity())) <= 0, A4P_PRODUCT_QUANTITY_EXCEEDED);
224+ }
225+ // Completing the last pending record of an exhausted ACTIVE intent always yields CONSUMED, and nothing
226+ // else does; REVOKED and EXPIRED are reachable with any ledger.
227+ IntentExecutionStatus status = context.status();
228+ if (status == IntentExecutionStatus.ACTIVE || status == IntentExecutionStatus.CONSUMED) {
229+ require((status == IntentExecutionStatus.CONSUMED) == Accounting.exhausted(context), A4P_INVALID_PARAMETER);
230+ }
231+ }
232+ 
233+ // completedAt and canceledAt are set exactly when the record reached the matching final status, never before
234+ // the reservation.
235+ private static void finalizedAt(Long timestamp, boolean expected, long reservedAt) {
236+ require((timestamp != null) == expected, A4P_INVALID_PARAMETER);
237+ if (timestamp != null) {
238+ integer(timestamp, false);
239+ require(timestamp >= reservedAt, A4P_INVALID_PARAMETER);
240+ }
241+ }
242+ 
243+ static void version(String version) {
244+ require(A4p.PROTOCOL_VERSION.equals(version), A4P_UNSUPPORTED_VERSION);
245+ }
246+}
@@ -0,0 +1,54 @@
1+package io.openjiuwen.a4p.examples;
2+ 
3+import io.openjiuwen.a4p.*;
4+import io.openjiuwen.a4p.Models.*;
5+import java.security.KeyPairGenerator;
6+import java.util.List;
7+import java.util.Map;
8+ 
9+public final class PaymentExample {
10+ private PaymentExample() {}
11+ 
12+ public static void main(String[] args) throws Exception {
13+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
14+ generator.initialize(3072);
15+ var agentKey = generator.generateKeyPair();
16+ var serverKey = generator.generateKeyPair();
17+ var userKey = generator.generateKeyPair();
18+ SignatureVerifier agentVerifier = Rsa3072.verifier(Map.of("agent", agentKey.getPublic()));
19+ SignatureVerifier serverVerifier = Rsa3072.verifier(Map.of("server", serverKey.getPublic()));
20+ SignatureVerifier userVerifier = Rsa3072.verifier(Map.of("user", userKey.getPublic()));
21+ long now = System.currentTimeMillis();
22+ Product product = new Product(new SellerInfo("shop"), new SpuSkuInfo("book", "paperback"));
23+ PaymentConstraints constraints = new PaymentConstraints(5000L, 10000L, "CNY", now,
24+ now + 86_400_000L, 2L, null, null, null);
25+ CreateIntentRequest request = new CreateIntentRequest("purchase", "Buy two books",
26+ PaymentProfile.structuredIntent(new ShoppingItems(List.of(new ItemWhiteList(List.of(product), 2L))),
27+ constraints), null);
28+ IntentL1 proposal = unwrap(A4p.createIntent(request, Rsa3072.signer("agent", agentKey.getPrivate()), now));
29+ IntentIssueContext identities = new IntentIssueContext(new UserIdentity("example", "user-1", null),
30+ new AgentIdentity("example", "agent-1", null), new ServiceProviderIdentity("shop", null));
31+ IntentL2 issued = unwrap(A4p.issueIntent(proposal, agentVerifier, identities,
32+ Rsa3072.signer("server", serverKey.getPrivate()), now));
33+ IntentL3 authorized = unwrap(A4p.signIntent(issued, serverVerifier,
34+ new SigningEnv(Map.of("type", "desktop"), Map.of("name", "payment-example")),
35+ Rsa3072.signer("user", userKey.getPrivate()), now));
36+ IntentExecutionContext context = unwrap(A4p.activateIntent(authorized, userVerifier, now));
37+ System.out.println("Issued by intent center: "
38+ + unwrap(A4p.verifyIntentAuthenticity(authorized, serverVerifier)).valid());
39+ Execution execution = PaymentProfile.execution("execution-1", "1.0",
40+ new Order("order-1", 3000L, "CNY", List.of(new CartItem(product, 1L)), now));
41+ unwrap(A4p.createExecution(context, execution, now));
42+ unwrap(A4p.completeExecution(context, execution.id(), now));
43+ System.out.println("Intent: " + context.intentId() + " (" + context.status() + ")");
44+ System.out.println("Remaining amount: " + PaymentProfile.executionInfo(context).leftAmount());
45+ System.out.println(A4pIntentCodec.standard().serializeIntentL3(authorized));
46+ }
47+ 
48+ private static <Value> Value unwrap(A4pResult<Value> result) {
49+ if (!result.success()) {
50+ throw new IllegalStateException(result.code() + " " + result.message());
51+ }
52+ return result.data();
53+ }
54+}
MREADME.md+11-1