agents/x402: a 2-of-2 contract wallet (ERC-1271) that neither the agent nor its owner can spend from alone
AereAgentWallet2of2 holds the agent's tokens and accepts only the agent's signature followed by the policy service's, over the same digest. In the new cosign mode the wallet service signs only its half, after every check it already made, and the agent adds its half only after it recomputes the payment itself (payer, recipient, amount, the nonce of its own ledger entry, validity, digest, declared policy signer). verifica-plati.mjs requires the wallet's code on chain to be exactly the compiled contract with the two signers; recompileaza-contract.mjs recompiles the published artifact byte for byte with solc 0.8.23. Tests: co-signing 16/16, payment verifier 14/14, negative control 30/30, wallet 25/25. On the public testnet 28001 on 2026-09-29: 13/13 with the 2-of-2 wallet (the agent alone and the policy signer alone refused by the facilitator and by the token asked on chain) and 9/9 with the wallet key. Evidence in dovezi-28001/. Nothing here has been run on the Aere Network mainnet.
This commit is contained in:
1 parent
2293c1da86
commit
8b608fe57f
20 files changed
+1480
-40
No files matched your search
+26
-11
@@ -18,12 +18,17 @@
|
||||
// de intrarea din registru, si aceeasi intrare nu poate plati de doua ori (nici la portofel, nici pe lant). Intoarce PaymentPayload-ul
|
||||
// x402 v2, de pus de agent in antetul PAYMENT-SIGNATURE, si un plic AIP-23 cu decizia.
|
||||
//
|
||||
// DOUA MODURI. `eoa`: portofelul E adresa cheii pe care o tine; cine tine cheia (proprietarul) poate plati si fara agent. `cosign`
|
||||
// (2026-09-29, `contractWallet`): banii stau intr-un portofel-contract 2-din-2 (contracts/contracts/x402/AereAgentWallet2of2.sol,
|
||||
// ERC-1271) care cere semnatura agentului SI a acestui serviciu; serviciul semneaza aici numai jumatatea lui, peste acelasi digest
|
||||
// EIP-712, iar agentul isi adauga jumatatea dupa ce isi recalculeaza singur digestul (client.mjs). Nici agentul, nici proprietarul
|
||||
// nu pot plati singuri.
|
||||
//
|
||||
// CE NU FACE: nu trimite tranzactii (decontarea o face facilitatorul x402 al serverului de resurse); nu tine alt activ decat unul
|
||||
// EIP-3009 configurat; nu e custodie fara incredere: cine tine cheia portofelului (proprietarul) poate plati fara agent. Un portofel-
|
||||
// contract 2-din-2 (agentul + politica, ERC-1271) ar scoate si increderea asta; nu e facut.
|
||||
// EIP-3009 configurat.
|
||||
//
|
||||
// node wallet.mjs serve --config wallet.json [--port 8793] serviciul HTTP (POST /authorize, POST /revocations, GET /status)
|
||||
// wallet.json: { policy, policyHash, network, token:{address,name,version}, evmKeyFile, stateFile, toleranceSeconds?, maxValiditySeconds? }
|
||||
// wallet.json: { policy, policyHash, network, token:{address,name,version}, evmKeyFile, stateFile, contractWallet?, toleranceSeconds?, maxValiditySeconds? }
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
@@ -76,7 +81,11 @@ export function createWallet(c) {
|
||||
const { policy, policyHash } = hashPolicy(c.policy);
|
||||
if (c.policyHash != null && String(c.policyHash).toLowerCase() !== policyHash) throw new Error('agent-wallet: the policy does not hash to the pinned policyHash');
|
||||
const cont = new ethers.Wallet(String(c.evmPrivateKey || '').trim());
|
||||
const adresa = cont.address.toLowerCase();
|
||||
// in modul cosign portofelul e contractul, iar cheia tinuta aici e numai a semnatarului de politica
|
||||
if (c.contractWallet != null && !ADRESA.test(String(c.contractWallet))) throw new Error('agent-wallet: contractWallet must be an address');
|
||||
const cosign = c.contractWallet != null;
|
||||
const platitor = cosign ? ethers.getAddress(c.contractWallet) : cont.address;
|
||||
const adresa = platitor.toLowerCase();
|
||||
if (policy.wallet !== adresa) throw new Error('agent-wallet: the policy does not name this wallet (policy.wallet must be its address)');
|
||||
if (!/^eip155:[0-9]+$/.test(String(c.network))) throw new Error('agent-wallet: network must be eip155:<chainId>');
|
||||
if (!c.token || !ADRESA.test(String(c.token.address)) || !c.token.name || !c.token.version) throw new Error('agent-wallet: token needs address, name and version (its EIP-712 domain)');
|
||||
@@ -95,6 +104,7 @@ export function createWallet(c) {
|
||||
const sesiune = sessionId(policy.agentId, policyHash);
|
||||
const S = stare.sessions[sesiune] || (stare.sessions[sesiune] = { anchors: [], last: null, lastEntry: null });
|
||||
const salveaza = () => { if (c.saveState) c.saveState(stare); };
|
||||
const semneazaDigest = async (d) => cont.signingKey.sign(d).serialized;
|
||||
const refuz = (error, extra = {}) => ({ ok: false, error, ...extra });
|
||||
|
||||
async function autorizeaza({ requirements: req, resource = null, ledger } = {}) {
|
||||
@@ -137,18 +147,22 @@ export function createWallet(c) {
|
||||
const d = checkAction(policy, { ...a, at: Number(b.at) }, stare.signed.map((s) => ({ amount: s.amount, at: s.at })), { approvers: aprobatori });
|
||||
if (!d.allowed) return refuz(`by what this wallet has signed: ${d.reason}`);
|
||||
// semnatura EIP-3009
|
||||
const authorization = { from: cont.address, to: ethers.getAddress(req.payTo), value: String(req.amount), validAfter: String(t - 5),
|
||||
const authorization = { from: platitor, to: ethers.getAddress(req.payTo), value: String(req.amount), validAfter: String(t - 5),
|
||||
validBefore: String(t + Math.min(timeout, VALID)), nonce: nonceForEntry(e.hash) };
|
||||
const signature = await cont.signTypedData(domeniu, TIPURI, { ...authorization, value: BigInt(authorization.value),
|
||||
const digest = ethers.TypedDataEncoder.hash(domeniu, TIPURI, { ...authorization, value: BigInt(authorization.value),
|
||||
validAfter: BigInt(authorization.validAfter), validBefore: BigInt(authorization.validBefore) });
|
||||
// aceeasi semnatura ECDSA peste digestul EIP-712 in ambele moduri (in eoa e chiar semnatura EIP-712 a platitorului). Semnarea e
|
||||
// asincrona dinadins (un semnatar din afara procesului, KMS sau HSM, se leaga aici): de aceea cererile trec prin coada de mai jos.
|
||||
const semnatura = await semneazaDigest(digest);
|
||||
S.anchors.push({ seq: e.seq, hash: e.hash, at: t });
|
||||
S.last = { seq: e.seq, hash: e.hash }; S.lastEntry = e;
|
||||
stare.signed.push({ seq: e.seq, entryHash: e.hash, amount: String(req.amount), at: Number(b.at), payTo: authorization.to, nonce: authorization.nonce });
|
||||
salveaza();
|
||||
const paymentPayload = { x402Version: 2, ...(resource ? { resource } : {}), accepted: req, payload: { signature, authorization },
|
||||
const paymentPayload = { x402Version: 2, ...(resource ? { resource } : {}), accepted: req, payload: { signature: cosign ? null : semnatura, authorization },
|
||||
extensions: { 'aere-agent-ledger': { agentId: ledger.agentId, policyHash, session: ledger.session, entrySeq: e.seq, entryHash: e.hash } } };
|
||||
return { ok: true, paymentPayload, header: Buffer.from(JSON.stringify(paymentPayload), 'utf8').toString('base64'),
|
||||
receipt: { entrySeq: e.seq, entryHash: e.hash, nonce: authorization.nonce, from: cont.address, to: authorization.to, value: authorization.value },
|
||||
return { ok: true, paymentPayload, header: cosign ? null : Buffer.from(JSON.stringify(paymentPayload), 'utf8').toString('base64'),
|
||||
...(cosign ? { cosign: { digest, policySignature: semnatura, order: 'agent signature, then policy signature (65 + 65 bytes)' } } : {}),
|
||||
receipt: { entrySeq: e.seq, entryHash: e.hash, nonce: authorization.nonce, from: platitor, to: authorization.to, value: authorization.value },
|
||||
decision: decisionEnvelope({ policyHash, action: a, decision: d, createdAt: new Date(t * 1000).toISOString() }) };
|
||||
}
|
||||
// cererile se judeca UNA CATE UNA: verificarea si semnatura au un `await` intre ele, iar doua cereri deodata ar trece amandoua de
|
||||
@@ -161,11 +175,12 @@ export function createWallet(c) {
|
||||
stare.revocations.push(rv); salveaza();
|
||||
return { ok: true, revokedAt: r.revokedAt };
|
||||
}
|
||||
const status = () => ({ version: VERSION, address: cont.address, network, asset: token, agentId: policy.agentId, policyHash,
|
||||
const status = () => ({ version: VERSION, mode: cosign ? 'cosign-2of2' : 'eoa', address: platitor, ...(cosign ? { policySigner: cont.address } : {}),
|
||||
network, asset: token, tokenName: String(c.token.name), tokenVersion: String(c.token.version), agentId: policy.agentId, policyHash,
|
||||
lastSeq: S.last ? S.last.seq : null, signed: stare.signed.length, revocations: stare.revocations.length });
|
||||
// starea, ca sa fie pastrata peste o schimbare de politica (acelasi agent, acelasi portofel): o copie, nu referinta
|
||||
const exportState = () => JSON.parse(JSON.stringify(stare));
|
||||
return { address: cont.address, network, token, policyHash, authorize, addRevocation, status, exportState };
|
||||
return { address: platitor, mode: cosign ? 'cosign-2of2' : 'eoa', network, token, policyHash, authorize, addRevocation, status, exportState };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- serviciul HTTP (numai pe 127.0.0.1 implicit)
|
||||
|
||||
Reference in new issue
Block a user