|
| 1 | +/** |
| 2 | + * Blockchain Adapter for Audityzer Security Agent |
| 3 | + * Records audit results on-chain for immutable provenance |
| 4 | + */ |
| 5 | + |
| 6 | +export class BlockchainAdapter { |
| 7 | + constructor(config = {}) { |
| 8 | + this.config = { |
| 9 | + network: config.network || 'ethereum', |
| 10 | + rpcUrl: config.rpcUrl || process.env.BLOCKCHAIN_RPC_URL || null, |
| 11 | + contractAddress: config.contractAddress || process.env.AUDIT_CONTRACT_ADDRESS || null, |
| 12 | + enabled: config.enabled !== undefined ? config.enabled : !!config.rpcUrl, |
| 13 | + ...config, |
| 14 | + }; |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Record an audit result on the blockchain |
| 19 | + * @param {string} scanId - Unique scan identifier |
| 20 | + * @param {string} ipfsHash - IPFS CID of the stored report |
| 21 | + * @returns {string|null} Transaction hash or null if disabled |
| 22 | + */ |
| 23 | + async recordAudit(scanId, ipfsHash) { |
| 24 | + if (!this.config.enabled || !this.config.contractAddress) { |
| 25 | + console.warn('[BlockchainAdapter] Blockchain recording disabled or not configured'); |
| 26 | + return null; |
| 27 | + } |
| 28 | + |
| 29 | + try { |
| 30 | + // Dynamic import to avoid hard dependency on ethers |
| 31 | + const { ethers } = await import('ethers'); |
| 32 | + const provider = new ethers.JsonRpcProvider(this.config.rpcUrl); |
| 33 | + const wallet = new ethers.Wallet(process.env.BLOCKCHAIN_PRIVATE_KEY, provider); |
| 34 | + |
| 35 | + const abi = [ |
| 36 | + 'function recordAudit(string scanId, string ipfsHash) external returns (bytes32)', |
| 37 | + ]; |
| 38 | + const contract = new ethers.Contract(this.config.contractAddress, abi, wallet); |
| 39 | + const tx = await contract.recordAudit(scanId, ipfsHash); |
| 40 | + const receipt = await tx.wait(); |
| 41 | + return receipt.hash; |
| 42 | + } catch (error) { |
| 43 | + console.error('[BlockchainAdapter] Failed to record audit:', error.message); |
| 44 | + return null; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + isEnabled() { |
| 49 | + return this.config.enabled; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +export default BlockchainAdapter; |
0 commit comments