/** * HeavenCoin — offline independent work-handoff source verification v1. * Requires TWO human-downloaded first-party source files in the same directory: * 1. This file saved as local-work-verify.mjs * 2. The existing unchanged local receipt key verifier, saved as * local-receipt-verify.mjs. Its pinned SHA-256 is checked BEFORE import. * * Node 20+. Zero npm packages, network calls, logins, wallet access, cloud * services, uploads, or database writes. * * Usage: * node local-work-verify.mjs receipt.json provider-proof.json recipient-proof.json redacted-candidate.json * * These files may contain private information. Do not share them publicly. * Mathematical validity of two KEY signatures is not independent proof of * two HUMAN signers, legally valid consent, work performed, or payment. */ import {createHash} from "node:crypto"; import {readFileSync,lstatSync} from "node:fs"; import {resolve} from "node:path"; import {fileURLToPath,pathToFileURL} from "node:url"; const EXISTING_VERIFIER_SHA256= "35df598acc0154cd2cb50b0c37c64ea2bfd688a195e91591127d8bc6280a1e9d"; const VERIFY_FILE="local-receipt-verify.mjs"; const MAX_RECEIPT=262144,MAX_PACKET=4096; const HASH=/^[a-f0-9]{64}$/; const sha=s=>createHash("sha256").update(s,"utf8").digest("hex"); const requiredKeys=(o,keys)=> !!o&&typeof o==="object"&&!Array.isArray(o)&& Object.keys(o).sort().join("|")===keys.slice().sort().join("|"); const assert=(cond,label)=>{if(!cond)throw Error(label);}; const fields=[ "receiptId","title","providerAlias","recipientAlias","kind","description", "quantity","unit","requestedInReturn","timing","completionCriteria", "consentAndAuthority","correctionRoute" ]; const candidateFields=[ "format","sourceRef","agreementSha256","snapshotSha256", "sourceFormat","sourceVersion","work","claimedCompletionEvents", "distinctClaimedCompletionRoles","distinctSigningKeys", "twoValidSignaturesForSnapshot","containsPriorCorrections", "concernHistoryPresent","handoffStatus","sourceReceiptNotSubmitted", "realPeopleIndependentlyVerified","workIndependentlyVerified", "accountantOrReviewerApproved","doubleCountingIndependentlyRuledOut", "journalPostingsCreated","spendableUnitsIssued", "financialOrRegulatoryClearance", "privatelyHeldProofsRequiredForLaterReview","generatedAt" ]; const falseFlags=[ "realPeopleIndependentlyVerified","workIndependentlyVerified", "accountantOrReviewerApproved","doubleCountingIndependentlyRuledOut", "journalPostingsCreated","spendableUnitsIssued", "financialOrRegulatoryClearance" ]; const trueFlags=[ "distinctClaimedCompletionRoles","distinctSigningKeys", "twoValidSignaturesForSnapshot","sourceReceiptNotSubmitted", "privatelyHeldProofsRequiredForLaterReview" ]; function readBounded(path,bytes){ const stat=lstatSync(path); assert(stat.isFile()&&!stat.isSymbolicLink()&&stat.size>0&&stat.size<=bytes, "Input is not a nonempty bounded regular file"); const raw=readFileSync(path); assert(raw.byteLength>0&&raw.byteLength<=bytes,"Input size changed"); const value=new TextDecoder("utf-8",{fatal:true}).decode(raw); return {raw,json:JSON.parse(value)}; } function checkCandidate(packet){ assert(requiredKeys(packet,candidateFields), "Redacted candidate has unsupported fields"); assert(packet.format==="heavencoin.local-work-accounting-handoff.v1"&& packet.sourceFormat==="heavencoin-voluntary-service-receipt"&& packet.sourceVersion===1&& packet.handoffStatus==="pending-independent-human-review"&& packet.claimedCompletionEvents===2&& packet.concernHistoryPresent===false, "Redacted candidate status or origin is invalid"); for(const field of falseFlags) assert(packet[field]===false,"Candidate asserts unavailable verification"); for(const field of trueFlags) assert(packet[field]===true,"Candidate lacks required exact evidence declaration"); assert(typeof packet.agreementSha256==="string"&& HASH.test(packet.agreementSha256)&& typeof packet.snapshotSha256==="string"&& HASH.test(packet.snapshotSha256)&& packet.sourceRef==="hc-local-service:"+packet.agreementSha256, "Candidate source fingerprints are invalid"); assert(typeof packet.containsPriorCorrections==="boolean", "Invalid correction history flag"); const work=packet.work; assert(requiredKeys(work,["kind","quantity","unit"])&& ["service","goods"].includes(work.kind)&& ["hours","items","projects","bundles"].includes(work.unit)&& typeof work.quantity==="string"&& /^(?:0|[1-9]\d{0,8})(?:\.\d{1,8})?$/.test(work.quantity)&& Number(work.quantity)>0,"Candidate work quantity invalid"); assert(typeof packet.generatedAt==="string"&& /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(packet.generatedAt)&& Number.isFinite(Date.parse(packet.generatedAt))&& Date.parse(packet.generatedAt)<=Date.now()+300000, "Candidate review timestamp invalid"); return packet; } function localRootAndSnapshot(receipt){ // The existing pinned verifier already validates STRICT receipt v1 // structure, UTF-8, timestamps, trim/length rules and ordered events. const a=receipt.agreement; const clean=fields.map(field=>typeof a[field]==="string"? a[field].trim():a[field]); const ordered=receipt.events.map(e=>[ e.sequence,e.kind,e.role,e.statement.trim(), e.evidenceReference.trim(),e.recordedAt ]); return { root:sha(JSON.stringify([ "heavencoin.local-work-root.v1",receipt.agreementRecordedAt,clean ])), snapshot:sha(JSON.stringify([ "heavencoin.service-receipt-snapshot.v1", receipt.agreementRecordedAt,clean,ordered ])) }; } async function validatedExistingVerifier(){ const absolute=resolve(fileURLToPath(new URL("./"+VERIFY_FILE,import.meta.url))); const raw=lstatSync(absolute); assert(raw.isFile()&&!raw.isSymbolicLink()&&raw.size<=262144, "The existing independent verifier is missing or unbounded"); const source=readFileSync(absolute); assert(sha(source.toString("utf8"))===EXISTING_VERIFIER_SHA256, "Existing local-receipt-verify.mjs differs from pinned original source"); const loaded=await import(pathToFileURL(absolute).href); assert(typeof loaded.verifySavedReceipt==="function", "Existing verifier API unavailable"); return loaded.verifySavedReceipt; } export async function recheckSavedWorkHandoff( receiptFile,providerProofFile,recipientProofFile,candidateFile ){ const candidate=checkCandidate(readBounded(candidateFile,MAX_PACKET).json); // Only AFTER the original unchanged verifier's code is authenticated // is it imported. No incoming JSON is executed. const verify=await validatedExistingVerifier(); const firstReceipt=readBounded(receiptFile,MAX_RECEIPT); const proof=verify(receiptFile,providerProofFile,recipientProofFile); const lastReceipt=readBounded(receiptFile,MAX_RECEIPT); assert(sha(firstReceipt.raw)===sha(lastReceipt.raw), "Source file changed during signature review"); assert(proof.verified===true&& proof.first?.claimedRole==="provider"&& proof.second?.claimedRole==="recipient"&& proof.rolesOpposite===true&&proof.distinctPublicKeys===true&& proof.first?.validSignature===true&& proof.second?.validSignature===true, "Both claimed-role P-256 signatures did not verify"); const receipt=lastReceipt.json; const events=receipt.events; const completions=events.filter(e=>e.kind==="completion"); assert(completions.length===2&& completions.some(e=>e.role==="provider")&& completions.some(e=>e.role==="recipient"), "Both separately claimed completion statements are required"); assert(!events.some(e=>e.kind==="concern"), "Recorded concern requires a separate human dispute review"); const {root,snapshot}=localRootAndSnapshot(receipt); assert(proof.sourceSha256===snapshot, "Source history does not match independently signed snapshot"); assert(candidate.agreementSha256===root&& candidate.snapshotSha256===snapshot&& candidate.sourceRef==="hc-local-service:"+root, "Handoff source references do not match the underlying receipt"); assert(candidate.work.kind===receipt.agreement.kind&& candidate.work.unit===receipt.agreement.unit&& candidate.work.quantity===receipt.agreement.quantity&& candidate.containsPriorCorrections===events.some(e=>e.kind==="correction"), "Handoff work facts or correction status are inconsistent"); return { format:"heavencoin.offline-local-work-source-check.v1", sourceRef:candidate.sourceRef, snapshotSha256:snapshot, evidenceConsistent:true, validDistinctKeysClaimingOppositeRoles:true, claimedCompletionStatements:2, claimedWork:{...candidate.work}, reportedCorrectionsPresent:candidate.containsPriorCorrections, independentHumanIdentityVerified:false, independentHumanConsentVerified:false, actualWorkIndependentlyVerified:false, absenceOfDuplicateClaimsVerified:false, accountingApprovalGranted:false, monetaryValueOrTransferVerified:false, independentConsensusVerified:false }; } async function main(){ const files=process.argv.slice(2); if(files.length!==4){ process.stderr.write( "Usage: node local-work-verify.mjs receipt.json provider-proof.json recipient-proof.json redacted-candidate.json\n"+ "Also place the unchanged local-receipt-verify.mjs in this directory.\n"); process.exitCode=2; return; } try{ const result=await recheckSavedWorkHandoff(...files); process.stdout.write(JSON.stringify(result,null,2)+"\n"); }catch{ // Do not echo source content, private file names, partial JSON or user details. process.stderr.write( "Source recheck REFUSED. Verify the original receipt, both exact-key proofs, "+ "the unchanged pinned verifier, and the private redacted candidate.\n"); process.exitCode=1; } } if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)) void main();