Ir para o conteúdo

02 — Smart Contracts (Chaincodes)

The federated-governance-java package contains three Java chaincodes for Hyperledger Fabric 2.5+. Each is annotated with @Contract and implements ContractInterface. The default entry point is org.hyperledger.fabric.contract.ContractRouter.


1. ExperimentContractSmartContract

Annotation: @Contract(name = "ExperimentContractChaincode") @Default

Responsibility: manage the lifecycle of a federated experiment contract — from creation to closure — and the registration of the authorized training code.

Contract state machine

Diagrama PlantUML 1

Ver código-fonte PlantUML
    @startuml "ExperimentContractSmartContract — Contract State Machine"
    !theme plain
    skinparam shadowing false

    title Contract State Machine — ExperimentContractSmartContract

    [*] --> DRAFT

    DRAFT --> DRAFT : registerTrainingCode
    DRAFT --> PUBLISHED : publishExperimentContract\n(requires code)

    PUBLISHED --> ACTIVE : activateExperimentContract\n(requires code)

    ACTIVE --> PAUSED : pauseExperimentContract
    ACTIVE --> CLOSED : closeExperimentContract
    ACTIVE --> REVOKED : revokeExperimentContract

    PAUSED --> ACTIVE : activateExperimentContract

    @enduml

Valid transitions defined in requireAllowedTransition():

Current status Allowed next status
DRAFT PUBLISHED
PUBLISHED ACTIVE, CLOSED, REVOKED
ACTIVE PAUSED, CLOSED, REVOKED
PAUSED ACTIVE, CLOSED, REVOKED

Operations

Method Type Main parameters Description
createExperimentContract SUBMIT experimentId, contractVersion, contractHash, contractUri, coordinatorId, validFrom, validTo Creates the contract with status DRAFT. Fails if it already exists.
registerTrainingCode SUBMIT experimentId, contractVersion, codeHash, codeUri, signature, manifestHash, entrypoint Registers the training JAR. Requires the contract to be in DRAFT or PUBLISHED. Only one code is allowed per version.
publishExperimentContract SUBMIT experimentId, contractVersion DRAFT → PUBLISHED transition. Requires registered code.
activateExperimentContract SUBMIT experimentId, contractVersion PUBLISHED → ACTIVE or PAUSED → ACTIVE transition. Requires registered code.
pauseExperimentContract SUBMIT experimentId, contractVersion, reasonHash ACTIVE → PAUSED transition. reasonHash must have the sha256: prefix.
closeExperimentContract SUBMIT experimentId, contractVersion, finalReportHash Closes the contract. finalReportHash must have the sha256: prefix.
revokeExperimentContract SUBMIT experimentId, contractVersion, reasonHash Revokes the contract. reasonHash must have the sha256: prefix.
getExperimentContract EVALUATE experimentId, contractVersion Returns the JSON of the ExperimentContractAsset.
experimentContractExists EVALUATE experimentId, contractVersion Returns a boolean.

Critical validations

  • contractHash and manifestHash must start with sha256:.
  • Code can only be registered while the status is DRAFT or PUBLISHED (CONTRACT_IMMUTABLE if attempted after activation).
  • Each version accepts only one code (TRAINING_CODE_ALREADY_REGISTERED).
  • Publication and activation require registered code (TRAINING_CODE_REQUIRED).
  • Invalid transitions throw INVALID_CONTRACT_TRANSITION.
  • The test dataset defined by the researcher stays in the off-chain document pointed to by contractUri; the world state only records the contractHash, which also covers the evaluation_dataset section.
  • The test dataset policy must prevent distribution to clients (researcher_only_never_to_clients).

Assets written to the world state

  • ExperimentContractAsset — composite key (experiment_contract, experimentId, contractVersion)
  • TrainingCodeAsset — composite key (training_code, experimentId, contractVersion, codeHash)

2. ClientConsentSmartContract

Annotation: @Contract(name = "ClientConsentChaincode")

Responsibility: record a client's acceptance, rejection, or revocation for a specific version of the experiment contract.

Diagrama PlantUML 2

Ver código-fonte PlantUML
    @startuml "ClientConsentSmartContract — Consent State Machine"
    !theme plain
    skinparam shadowing false

    title Consent State Machine — ClientConsentSmartContract

    [*] --> ACCEPTED : acceptExperimentContract\n(requires contract ACTIVE\nand identical hash)
    ACCEPTED --> REVOKED : revokeClientConsent

    [*] --> REJECTED : rejectExperimentContract

    @enduml

Compatibility: records written before the typo fix may contain EXPCEPTED in the world state. The chaincode accepts both on read (CONSENT_ACCEPTED and CONSENT_EXPCEPTED). Every new write uses CONSENT_ACCEPTED exclusively.

Operations

Method Type Main parameters Description
acceptExperimentContract SUBMIT experimentId, contractVersion, clientId, acceptedContractHash, signature Accepts the contract. Requires the contract to be ACTIVE and acceptedContractHash == contract_hash on-chain. Writes ACCEPTED to the world state.
rejectExperimentContract SUBMIT experimentId, contractVersion, clientId, reasonHash Records a rejection. reasonHash must have the sha256: prefix.
revokeClientConsent SUBMIT experimentId, contractVersion, clientId, reasonHash Revokes acceptance. Accepts current status ACCEPTED or EXPCEPTED (legacy).
getClientConsentStatus EVALUATE experimentId, contractVersion, clientId Returns a string with the status (ACCEPTED, REJECTED, REVOKED). Legacy records may return EXPCEPTED.
getClientConsent EVALUATE experimentId, contractVersion, clientId Returns the full JSON of the ClientConsentAsset.
listAcceptedClients EVALUATE experimentId, contractVersion Returns a JSON array with all client assets in ACCEPTED or EXPCEPTED (legacy) status.

Critical validations

  • For acceptance: the contract must be in ACTIVE status (CONTRACT_NOT_ACTIVE).
  • For acceptance: acceptedContractHash must equal the contract_hash of the on-chain contract (CONTRACT_HASH_MISMATCH). This guarantees that the client accepted the exact registered version of the contract.
  • For revocation: the current consent must be ACCEPTED or EXPCEPTED (legacy) (CONSENT_NOT_ACTIVE otherwise).
  • All required fields are validated (empty or null = VALIDATION_FAILED).

Asset written to the world state

  • ClientConsentAsset — composite key (consent, experimentId, contractVersion, clientId)

3. FederatedExperimentSmartContract

Annotation: @Contract(name = "FederatedExperimentChaincode")

Responsibility: record immutable evidence of every execution step of the federated experiment: rounds, datasets, preflights, local updates, aggregations, and global models.

Call flow within a round

1. registerTrainingRound        (orchestrator — start of round)
2. registerDatasetEvidence      (client — local dataset evidence)
3. registerPreflightHash        (client — preflight result)
4. registerLocalUpdateHash      (client — hash of the submitted update)
   ... [repeated for each participating client]
5. registerAggregationHash      (aggregator — aggregation result with quorum)
6. registerGlobalModelVersion   (aggregator — candidate global model)
7. registerTrainingCompletion   (orchestrator — experiment closure)

Operations

Method Type Main parameters Description
registerTrainingRound SUBMIT experimentId, roundId, roundConfigHash Registers the start of a round. roundId must be an integer. Produces an AuditEvent.
registerDatasetEvidence SUBMIT experimentId, contractVersion, clientId, datasetHash, metadataHash, recordCount, schemaVersion, dataPathHash Registers local dataset evidence. Idempotent: a second call with the same values is accepted; divergent values are rejected.
registerPreflightHash SUBMIT experimentId, roundId, clientId, preflightHash Registers the preflight result. Produces an AuditEvent.
registerLocalUpdateHash SUBMIT experimentId, roundId, clientId, updateHash Registers the hash of the client's local update. Produces an AuditEvent.
registerAggregationHash SUBMIT experimentId, roundId, aggregationReportHash, quorumStatus Registers the aggregation result along with the quorum status. Produces an AuditEvent.
registerGlobalModelVersion SUBMIT experimentId, modelVersion, modelHash, modelUri, promotionDecision, aggregationReportHash Registers the candidate global model. modelVersion must be an integer. Rejects overwriting with divergent values.
registerTrainingCompletion SUBMIT experimentId, finalStatus, finalReportHash Registers the closure of the experiment. Produces an AuditEvent.
getDatasetEvidence EVALUATE experimentId, contractVersion, clientId Returns the JSON of the DatasetEvidenceAsset.
getGlobalModelVersion EVALUATE experimentId, modelVersion Returns the JSON of the GlobalModelAsset.
listAuditEvents EVALUATE experimentId Returns a JSON array with all AuditEventAsset records of the experiment, ordered by composite key.

Critical invariants

  • DatasetEvidenceAsset is unique per (experimentId, contractVersion, clientId). A second call with the same data is accepted (idempotency). A second call with different data throws DATASET_EVIDENCE_ALREADY_EXISTS.
  • GlobalModelAsset is unique per (experimentId, modelVersion). Attempting to overwrite with a different hash or URI throws GLOBAL_MODEL_ALREADY_EXISTS.
  • All *Hash fields must have the sha256: prefix.
  • roundId and modelVersion must be valid integers (Long).

Assets written to the world state

  • AuditEventAsset — composite key (audit, experimentId, roundId, txId)
  • DatasetEvidenceAsset — composite key (dataset_evidence, experimentId, contractVersion, clientId)
  • GlobalModelAsset — composite key (global_model, experimentId, modelVersion)

Shared utilities (util package)

LedgerConstants

Defines all status constants and world state object types:

// Contract status
STATUS_DRAFT      = "DRAFT"
STATUS_PUBLISHED  = "PUBLISHED"
STATUS_ACTIVE     = "ACTIVE"
STATUS_PAUSED     = "PAUSED"
STATUS_CLOSED     = "CLOSED"
STATUS_REVOKED    = "REVOKED"

// Consent status
CONSENT_ACCEPTED  = "ACCEPTED"    // canonical value; every new write uses this
CONSENT_EXPCEPTED = "EXPCEPTED"   // @Deprecated — historical typo; kept for reading legacy ledger data
CONSENT_REJECTED  = "REJECTED"
CONSENT_REVOKED   = "REVOKED"

// Object types for composite keys
OBJECT_EXPERIMENT_CONTRACT = "experiment_contract"
OBJECT_TRAINING_CODE       = "training_code"
OBJECT_CONSENT             = "consent"
OBJECT_AUDIT               = "audit"
OBJECT_GLOBAL_MODEL        = "global_model"
OBJECT_DATASET_EVIDENCE    = "dataset_evidence"

StateKeys

Centralizes composite key creation via ctx.getStub().createCompositeKey():

Method Key components
experiment(ctx, experimentId, contractVersion) (experiment_contract, experimentId, contractVersion)
trainingCode(ctx, experimentId, contractVersion, codeHash) (training_code, experimentId, contractVersion, codeHash)
consent(ctx, experimentId, contractVersion, clientId) (consent, experimentId, contractVersion, clientId)
audit(ctx, experimentId, roundId, txId) (audit, experimentId, roundId, txId)
model(ctx, experimentId, modelVersion) (global_model, experimentId, modelVersion)
datasetEvidence(ctx, experimentId, contractVersion, clientId) (dataset_evidence, experimentId, contractVersion, clientId)

Validation

Three kinds of validation, all of which throw ChaincodeException("...", "VALIDATION_FAILED"):

  • required(name, value) — rejects null or blank.
  • requireHash(name, value) — calls required and requires the sha256: prefix.
  • requireInteger(name, value) — calls required and requires a value parseable as Long.

Json

JSON serialization with no external dependencies (does not use Jackson). Methods:

  • object(Map<String,String>) — serializes a map as a JSON object.
  • array(List<String>) — serializes a list of already-serialized JSON strings.
  • withField(json, field, value) — replaces or inserts a field in an existing JSON string.
  • field(json, field) — extracts a field's value by name.
  • fieldEquals(json, field, expected) — compares a field's value.

In-memory simulators

For local development and testing without Fabric, each chaincode has a corresponding simulator:

Real Fabric chaincode In-memory simulator Location
ExperimentContractSmartContract ExperimentContractChaincode modules/federated-chaincode/
ClientConsentSmartContract ClientConsentChaincode modules/federated-chaincode/
FederatedExperimentSmartContract FederatedExperimentChaincode modules/federated-chaincode/

The simulators use ConcurrentHashMap instead of the Fabric world state. The same business invariants are enforced in both: state transitions, evidence uniqueness, idempotency. This ensures that local tests validate the same flows that the real Fabric network would execute.