// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.24; /// @title DagSeal — document authenticity registry on BlockDAG /// @notice Verifying is always free for anyone. /// Any issuer can register documents by paying in BDAG. /// Issuers verified by the owner get a free trial period. /// All revenue stays in the contract and only the owner can withdraw it, /// always to the owner's wallet. contract DocumentRegistry { // ------------------------------------------------------------------ // Types // ------------------------------------------------------------------ struct Issuer { string name; uint64 trialStart; // 0 = no trial period (not verified yet) uint32 trialUsed; uint64 planUntil; uint32 planDocsLeft; // documents still included in the current plan bool verified; bool blocked; bool exists; } struct Doc { bytes32 hash; address issuer; uint64 registeredAt; uint64 validUntil; // 0 = no expiry uint8 docType; bool revoked; bytes8 shortCode; } /// @notice Result of a verification (returned as a struct). struct Record { bool found; bytes32 hash; address issuer; string issuerName; bool issuerVerified; bool issuerBlocked; uint64 registeredAt; uint64 validUntil; uint8 docType; bool revoked; bytes8 shortCode; } struct IssuerView { bool exists; string name; bool verified; bool blocked; bool trialActive; uint64 trialEnds; uint32 trialDocsLeft; uint64 planUntil; uint256 feePerDocument; uint256 planPrice; uint64 planDuration; uint32 planDocsLeft; uint32 planQuota; } // ------------------------------------------------------------------ // State // ------------------------------------------------------------------ address public owner; address public pendingOwner; bool public paused; uint256 public feePerDocument; // BDAG wei uint256 public planPrice; // BDAG wei per period uint64 public planDuration; // seconds uint32 public planQuota; // documents included per plan period (protects revenue) uint64 public trialDuration; // seconds uint32 public trialQuota; // free documents in the trial period uint256 public totalDocuments; uint256 public totalRevenue; // cumulative, never decreases uint256 public totalWithdrawn; uint8 public constant MAX_DOC_TYPE = 15; uint256 public constant MAX_BATCH = 100; uint256 public constant MAX_PLAN_PERIODS = 12; uint64 public constant MAX_TRIAL_DURATION = 365 days; uint64 public constant MAX_PLAN_DURATION = 366 days; mapping(address => Issuer) private _issuers; /// recordId = keccak256(issuer, hash). Each issuer has its own record: /// nobody can "take over" another issuer's hash. mapping(bytes32 => Doc) private _docs; /// All issuers that registered the same file. mapping(bytes32 => address[]) private _claimants; /// Short code (8 bytes) -> recordId. mapping(bytes8 => bytes32) private _shortCodes; uint256 private _lock = 1; // ------------------------------------------------------------------ // Events // ------------------------------------------------------------------ event IssuerRegistered(address indexed issuer, string name); event IssuerRenamed(address indexed issuer, string name); event IssuerVerified(address indexed issuer, bool verified); event IssuerBlocked(address indexed issuer, bool blocked); event DocumentRegistered( bytes32 indexed hash, address indexed issuer, bytes8 shortCode, uint8 docType, uint64 validUntil, bool paid ); event DocumentRevoked(bytes32 indexed hash, address indexed issuer); event PlanPurchased(address indexed issuer, uint256 periods, uint64 planUntil, uint256 amount); event PricingChanged(uint256 feePerDocument, uint256 planPrice, uint64 planDuration, uint32 planQuota); event TrialChanged(uint64 trialDuration, uint32 trialQuota); event Paused(bool paused); event Withdrawn(address indexed to, uint256 amount); event OwnershipTransferStarted(address indexed from, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); // ------------------------------------------------------------------ // Errors // ------------------------------------------------------------------ error NotOwner(); error NotPendingOwner(); error ContractPaused(); error NotAnIssuer(); error IssuerIsBlocked(); error InvalidName(); error InvalidHash(); error InvalidDocType(); error InvalidValidity(); error AlreadyRegistered(); error NotFound(); error AlreadyRevoked(); error WrongPayment(uint256 expected, uint256 sent); error PlanTermsChanged(uint64 currentDuration); error InvalidPeriods(); error InvalidPricing(); error InvalidTrial(); error BatchTooLarge(); error ShortCodeTaken(); error InsufficientBalance(); error TransferFailed(); error Reentrancy(); error DirectPaymentsNotAccepted(); // ------------------------------------------------------------------ // Modifiers // ------------------------------------------------------------------ modifier onlyOwner() { if (msg.sender != owner) revert NotOwner(); _; } modifier whenNotPaused() { if (paused) revert ContractPaused(); _; } modifier nonReentrant() { if (_lock != 1) revert Reentrancy(); _lock = 2; _; _lock = 1; } // ------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------ constructor( uint256 _feePerDocument, uint256 _planPrice, uint64 _planDuration, uint32 _planQuota, uint64 _trialDuration, uint32 _trialQuota ) { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); _setPricing(_feePerDocument, _planPrice, _planDuration, _planQuota); _setTrial(_trialDuration, _trialQuota); } receive() external payable { revert DirectPaymentsNotAccepted(); } // ------------------------------------------------------------------ // Issuers // ------------------------------------------------------------------ /// @notice Creates or renames the issuer profile. /// Changing the name removes the verified badge. function registerIssuer(string calldata name) external whenNotPaused { uint256 len = bytes(name).length; if (len == 0 || len > 100) revert InvalidName(); Issuer storage i = _issuers[msg.sender]; if (i.blocked) revert IssuerIsBlocked(); i.name = name; if (!i.exists) { i.exists = true; emit IssuerRegistered(msg.sender, name); } else { if (i.verified) { i.verified = false; emit IssuerVerified(msg.sender, false); } emit IssuerRenamed(msg.sender, name); } } // ------------------------------------------------------------------ // Document registration // ------------------------------------------------------------------ /// @notice Registers the fingerprint (SHA-256) of a document. /// Free during the trial period or with an active plan; /// otherwise, send exactly `feePerDocument`. function register(bytes32 hash, uint8 docType, uint64 validUntil) external payable whenNotPaused nonReentrant { Issuer storage i = _activeIssuer(msg.sender); bool paid = !_consumeFree(i); uint256 expected = paid ? feePerDocument : 0; if (msg.value != expected) revert WrongPayment(expected, msg.value); _store(hash, docType, validUntil, paid); totalRevenue += msg.value; } /// @notice Registers up to 100 documents at once. function registerBatch(bytes32[] calldata hashes, uint8 docType, uint64 validUntil) external payable whenNotPaused nonReentrant { uint256 n = hashes.length; if (n == 0 || n > MAX_BATCH) revert BatchTooLarge(); Issuer storage i = _activeIssuer(msg.sender); uint256 paidCount; for (uint256 k; k < n; ++k) { bool paid = !_consumeFree(i); if (paid) ++paidCount; _store(hashes[k], docType, validUntil, paid); } uint256 expected = paidCount * feePerDocument; if (msg.value != expected) revert WrongPayment(expected, msg.value); totalRevenue += msg.value; } /// @notice Buys `periods` plan periods. Each period includes `planQuota` /// documents; above that, each document pays `feePerDocument`. /// `expectedDuration` protects against changed terms. function buyPlan(uint256 periods, uint64 expectedDuration, uint32 expectedQuota) external payable whenNotPaused nonReentrant { if (periods == 0 || periods > MAX_PLAN_PERIODS) revert InvalidPeriods(); if (expectedDuration != planDuration || expectedQuota != planQuota) revert PlanTermsChanged(planDuration); Issuer storage i = _activeIssuer(msg.sender); uint256 expected = planPrice * periods; if (msg.value != expected) revert WrongPayment(expected, msg.value); bool active = i.planUntil > block.timestamp; uint256 start = active ? uint256(i.planUntil) : block.timestamp; uint256 until = start + periods * uint256(planDuration); uint256 docs = (active ? uint256(i.planDocsLeft) : 0) + periods * uint256(planQuota); if (until > type(uint64).max || docs > type(uint32).max) revert InvalidPeriods(); i.planUntil = uint64(until); i.planDocsLeft = uint32(docs); totalRevenue += msg.value; emit PlanPurchased(msg.sender, periods, i.planUntil, msg.value); } /// @notice An issuer can revoke a document it registered. function revoke(bytes32 hash) external { Doc storage d = _docs[_recordId(msg.sender, hash)]; if (d.issuer == address(0)) revert NotFound(); if (d.revoked) revert AlreadyRevoked(); d.revoked = true; emit DocumentRevoked(hash, msg.sender); } // ------------------------------------------------------------------ // Reading — free for anyone // ------------------------------------------------------------------ /// @notice Verifies a document from a specific issuer (via QR). function verify(bytes32 hash, address issuer) public view returns (Record memory r) { return _record(_recordId(issuer, hash)); } /// @notice Verifies using the short code printed on the document. function verifyShortCode(bytes8 code) external view returns (Record memory r) { bytes32 id = _shortCodes[code]; if (id == bytes32(0)) return r; return _record(id); } /// @notice How many issuers registered this file. function claimantCount(bytes32 hash) external view returns (uint256) { return _claimants[hash].length; } /// @notice Records of this file, paginated (for verifying with the file only). function claimants(bytes32 hash, uint256 offset, uint256 limit) external view returns (Record[] memory out) { address[] storage list = _claimants[hash]; uint256 n = list.length; if (offset >= n) return new Record[](0); uint256 end = offset + limit; if (end > n) end = n; out = new Record[](end - offset); for (uint256 k = offset; k < end; ++k) { out[k - offset] = _record(_recordId(list[k], hash)); } } function issuerStatus(address who) external view returns (IssuerView memory v) { Issuer storage i = _issuers[who]; v.feePerDocument = feePerDocument; v.planPrice = planPrice; v.planDuration = planDuration; v.planQuota = planQuota; if (!i.exists) return v; v.exists = true; v.name = i.name; v.verified = i.verified; v.blocked = i.blocked; v.planUntil = i.planUntil; if (i.planUntil > block.timestamp) v.planDocsLeft = i.planDocsLeft; if (i.trialStart != 0) { uint256 ends = uint256(i.trialStart) + trialDuration; v.trialEnds = uint64(ends); if (block.timestamp < ends && i.trialUsed < trialQuota) { v.trialActive = true; v.trialDocsLeft = trialQuota - i.trialUsed; } } } // ------------------------------------------------------------------ // Owner // ------------------------------------------------------------------ function setPricing(uint256 _feePerDocument, uint256 _planPrice, uint64 _planDuration, uint32 _planQuota) external onlyOwner { _setPricing(_feePerDocument, _planPrice, _planDuration, _planQuota); } function setTrial(uint64 _trialDuration, uint32 _trialQuota) external onlyOwner { _setTrial(_trialDuration, _trialQuota); } /// @notice Gives (or removes) the verified issuer badge. /// The first verification starts the free trial period. function setVerified(address issuer, bool verified) external onlyOwner { Issuer storage i = _issuers[issuer]; if (!i.exists) revert NotAnIssuer(); i.verified = verified; if (verified && i.trialStart == 0) i.trialStart = uint64(block.timestamp); emit IssuerVerified(issuer, verified); } function setBlocked(address issuer, bool blocked) external onlyOwner { Issuer storage i = _issuers[issuer]; if (!i.exists) revert NotAnIssuer(); i.blocked = blocked; emit IssuerBlocked(issuer, blocked); } function setPaused(bool _paused) external onlyOwner { paused = _paused; emit Paused(_paused); } /// @notice Withdraws revenue. The destination is ALWAYS the owner's wallet. function withdraw(uint256 amount) external onlyOwner nonReentrant { if (amount > address(this).balance) revert InsufficientBalance(); totalWithdrawn += amount; (bool ok, ) = payable(owner).call{value: amount}(""); if (!ok) revert TransferFailed(); emit Withdrawn(owner, amount); } /// @notice Two-step transfer. `address(0)` cancels. function transferOwnership(address newOwner) external onlyOwner { pendingOwner = newOwner; emit OwnershipTransferStarted(owner, newOwner); } function acceptOwnership() external { if (msg.sender != pendingOwner) revert NotPendingOwner(); emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; pendingOwner = address(0); } // ------------------------------------------------------------------ // Internal // ------------------------------------------------------------------ function _setPricing(uint256 fee, uint256 price, uint64 duration, uint32 quota) private { if (price == 0 || duration == 0 || duration > MAX_PLAN_DURATION || quota == 0) revert InvalidPricing(); feePerDocument = fee; planPrice = price; planDuration = duration; planQuota = quota; emit PricingChanged(fee, price, duration, quota); } function _setTrial(uint64 duration, uint32 quota) private { if (duration > MAX_TRIAL_DURATION) revert InvalidTrial(); trialDuration = duration; trialQuota = quota; emit TrialChanged(duration, quota); } function _recordId(address issuer, bytes32 hash) private pure returns (bytes32) { return keccak256(abi.encode(issuer, hash)); } function _record(bytes32 id) private view returns (Record memory r) { Doc storage d = _docs[id]; if (d.issuer == address(0)) return r; Issuer storage i = _issuers[d.issuer]; r.found = true; r.hash = d.hash; r.issuer = d.issuer; r.issuerName = i.name; r.issuerVerified = i.verified && !i.blocked; r.issuerBlocked = i.blocked; r.registeredAt = d.registeredAt; r.validUntil = d.validUntil; r.docType = d.docType; r.revoked = d.revoked; r.shortCode = d.shortCode; } function _activeIssuer(address who) private view returns (Issuer storage i) { i = _issuers[who]; if (!i.exists) revert NotAnIssuer(); if (i.blocked) revert IssuerIsBlocked(); } /// @dev true if this registration is free (active plan or trial period). function _consumeFree(Issuer storage i) private returns (bool) { if (i.planUntil > block.timestamp && i.planDocsLeft > 0) { i.planDocsLeft -= 1; return true; } if ( i.verified && i.trialStart != 0 && block.timestamp < uint256(i.trialStart) + trialDuration && i.trialUsed < trialQuota ) { i.trialUsed += 1; return true; } return false; } function _store(bytes32 hash, uint8 docType, uint64 validUntil, bool paid) private { if (hash == bytes32(0)) revert InvalidHash(); if (docType > MAX_DOC_TYPE) revert InvalidDocType(); if (validUntil != 0 && validUntil <= block.timestamp) revert InvalidValidity(); bytes32 id = _recordId(msg.sender, hash); if (_docs[id].issuer != address(0)) revert AlreadyRegistered(); bytes8 code = bytes8(id); if (_shortCodes[code] != bytes32(0)) revert ShortCodeTaken(); _docs[id] = Doc({ hash: hash, issuer: msg.sender, registeredAt: uint64(block.timestamp), validUntil: validUntil, docType: docType, revoked: false, shortCode: code }); _shortCodes[code] = id; _claimants[hash].push(msg.sender); totalDocuments += 1; emit DocumentRegistered(hash, msg.sender, code, docType, validUntil, paid); } }