All files / src/upgrade upgrade.ts

100% Statements 57/57
100% Branches 0/0
91.66% Functions 11/12
100% Lines 54/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 2963x                         3x         3x           3x                       3x 3x 3x                                                         3x                                                 51x           51x             51x         51x                 2x 2x 2x                                 3x         6x 6x 6x                   9x         9x 3x 3x   9x 9x                         3x 15x     15x       15x     12x           15x 15x 15x 15x       15x                             3x 6x     6x 6x 6x                   6x     3x           6x 6x 6x                       3x           3x         3x                             9x       9x 9x 9x     9x 9x      
import {
  Bool,
  method,
  Permissions,
  Provable,
  SmartContract,
  State,
  state,
  VerificationKey,
  Field,
  Struct,
  UInt32,
} from "o1js";
import {
  loadIndexedMerkleMap,
  createIpfsURL,
  IndexedMapSerialized,
} from "zkcloudworker";
import {
  Storage,
  UpgradeAuthorityBase,
  VerificationKeyUpgradeData,
  UpgradeAuthorityAnswer,
} from "../contracts";
import {
  UpgradeAuthorityDatabase,
  ValidatorsState,
  UpgradeDatabaseState,
  ValidatorsList,
  ValidatorsVotingProof,
  ValidatorDecisionType,
  UpgradeDatabaseStatePacked,
  checkValidatorsList,
} from "./validators";
 
export {
  VerificationKeyUpgradeAuthority,
  UpgradeAuthorityDatabase,
  ValidatorsListEvent,
  ValidatorsListData,
};
 
/**
 * Interface representing the data for a list of validators.
 */
interface ValidatorsListData {
  validators: {
    publicKey: string;
    authorizedToVote: boolean;
  }[];
  validatorsCount: number;
  hashSum: string;
  root: string;
  map: IndexedMapSerialized;
}
 
/**
 * Event emitted when the validators list is updated.
 */
class ValidatorsListEvent extends Struct({
  validators: ValidatorsState,
  storage: Storage,
}) {}
 
/**
 * Error messages for the VerificationKeyUpgradeAuthority contract.
 */
const VerificationKeyUpgradeAuthorityErrors = {
  WrongNewVerificationKeyHash: "Wrong new verification key hash",
};
 
/**
 * **VerificationKeyUpgradeAuthority** is a smart contract that provides a secure mechanism
 * for upgrading the verification keys of other contracts without requiring redeployment.
 * It manages a list of validators who can vote on upgrade proposals, ensuring that only
 * authorized upgrades are applied.
 *
 * **Key Features:**
 * - **Verification Key Management**: Allows for secure upgrades of verification keys for other contracts.
 * - **Validators Governance**: Maintains a list of authorized validators who can vote on upgrade proposals.
 * - **Secure Voting Mechanism**: Implements Zero-Knowledge proofs to validate votes from validators without revealing sensitive information.
 * - **Upgrade Database Management**: Keeps track of upgrade proposals and their validity periods.
 * - **Event Emissions**: Emits events when validators list or upgrade database is updated.
 */
class VerificationKeyUpgradeAuthority
  extends SmartContract
  implements UpgradeAuthorityBase
{
  /**
   * The hash of the verification key.
   * @type {State<Field>}
   */
  @state(Field) verificationKeyHash = State<Field>();
 
  /**
   * The hash representing the current state of the validators list.
   * @type {State<Field>}
   */
  @state(Field) validators = State<Field>();
 
  /**
   * Packed state containing the upgrade database information.
   * @type {State<UpgradeDatabaseStatePacked>}
   */
  @state(UpgradeDatabaseStatePacked)
  upgradeDatabasePacked = State<UpgradeDatabaseStatePacked>();
 
  /**
   * The events emitted by the VerificationKeyUpgradeAuthority contract.
   */
  events = {
    validatorsList: ValidatorsListEvent,
    updateDatabase: UpgradeDatabaseState,
  };
 
  /**
   * Deploys the contract and sets the initial state.
   */
  async deploy() {
    await super.deploy();
    this.upgradeDatabasePacked.set(UpgradeDatabaseState.empty().pack());
    this.account.permissions.set({
      ...Permissions.default(),
      setVerificationKey:
        // The contract needs to be redeployed in the case of an upgrade.
        Permissions.VerificationKey.impossibleDuringCurrentVersion(),
      setPermissions: Permissions.impossible(),
    });
  }
 
  /**
   * Initializes the contract with validators and sets the verification key hash.
   *
   * @param {ValidatorsState} validators - The initial validators state.
   * @param {Storage} storage - Off-chain storage information, e.g., IPFS hash.
   * @param {Field} verificationKeyHash - The hash of the verification key.
   */
  @method
  async initialize(
    validators: ValidatorsState,
    storage: Storage,
    verificationKeyHash: Field
  ) {
    this.account.provedState.requireEquals(Bool(false));
    await this.setValidatorsList(validators, storage);
    this.verificationKeyHash.set(verificationKeyHash);
  }
 
  /**
   * Sets the validators list and emits an event.
   *
   * @param {ValidatorsState} validators - The validators state to set.
   * @param {Storage} storage - The storage associated with the validators list.
   */
  async setValidatorsList(validators: ValidatorsState, storage: Storage) {
    this.validators.set(validators.hash());
    // This does not create a constraint on the storage,
    // serves to prevent deployment errors.
    // Can be replaced with Data Availability proof in the future.
    // TODO: consider using Celestia DA for this.
    const map = await Provable.witnessAsync(ValidatorsList, async () => {
      const { map } = await checkValidatorsList({ validators, storage });
      return map;
    });
    map.root.assertEquals(validators.root);
    this.emitEvent(
      "validatorsList",
      new ValidatorsListEvent({ validators, storage })
    );
  }
 
  /**
   * Verifies the upgrade data provided by another contract.
   *
   * @param {VerificationKeyUpgradeData} data - The upgrade data to verify.
   * @returns {Promise<UpgradeAuthorityAnswer>} - The answer indicating verification result.
   */
  @method.returns(UpgradeAuthorityAnswer)
  public async verifyUpgradeData(data: VerificationKeyUpgradeData) {
    const upgradeDatabase = UpgradeDatabaseState.unpack(
      this.upgradeDatabasePacked.getAndRequireEquals()
    );
    this.network.globalSlotSinceGenesis.requireBetween(
      upgradeDatabase.validFrom,
      UInt32.MAXINT()
    );
    const map = await Provable.witnessAsync(
      UpgradeAuthorityDatabase,
      async () => {
        return await loadIndexedMerkleMap({
          url: createIpfsURL({ hash: upgradeDatabase.storage.toString() }),
          type: UpgradeAuthorityDatabase,
        });
      }
    );
    map.root.assertEquals(upgradeDatabase.root);
    const key = data.hash();
    const newVerificationKeyHash = map.get(key);
    newVerificationKeyHash.assertEquals(
      data.newVerificationKeyHash,
      VerificationKeyUpgradeAuthorityErrors.WrongNewVerificationKeyHash
    );
    return new UpgradeAuthorityAnswer({
      // Should be public key of the next upgrade authority in case
      // new version of o1js breaks the verification key of upgrade authority
      nextUpgradeAuthority: upgradeDatabase.nextUpgradeAuthority,
      isVerified: Bool(true),
    });
  }
 
  /**
   * Updates the upgrade database after validator consensus.
   *
   * @param {ValidatorsVotingProof} proof - The proof of validators voting.
   * @param {VerificationKey} vk - The verification key to validate the proof.
   */
  @method
  async updateDatabase(proof: ValidatorsVotingProof, vk: VerificationKey) {
    const oldUpgradeDatabase = UpgradeDatabaseState.unpack(
      this.upgradeDatabasePacked.getAndRequireEquals()
    );
    const upgradeDatabase = proof.publicInput.decision.upgradeDatabase;
    upgradeDatabase.version.assertGreaterThan(oldUpgradeDatabase.version);
    await this.checkValidatorsDecision(
      proof,
      vk,
      ValidatorDecisionType["updateDatabase"]
    );
 
    // This does not create a constraint on the storage,
    // serves to prevent deployment errors.
    // Can be replaced with Data Availability proof in the future.
    // TODO: consider using Celestia DA for this.
    const map = await Provable.witnessAsync(
      UpgradeAuthorityDatabase,
      async () => {
        return await loadIndexedMerkleMap({
          url: createIpfsURL({ hash: upgradeDatabase.storage.toString() }),
          type: UpgradeAuthorityDatabase,
        });
      }
    );
    map.root.assertEquals(upgradeDatabase.root);
    this.upgradeDatabasePacked.set(upgradeDatabase.pack());
    this.emitEvent("updateDatabase", upgradeDatabase);
  }
 
  /**
   * Updates the validators list based on validator votes.
   *
   * @param {ValidatorsState} validators - The new validators state.
   * @param {Storage} storage - The storage associated with the validators list.
   * @param {ValidatorsVotingProof} proof - The proof of validators voting.
   * @param {VerificationKey} vk - The verification key to validate the proof.
   */
  @method // add proof of validators voting
  async updateValidatorsList(
    validators: ValidatorsState,
    storage: Storage,
    proof: ValidatorsVotingProof,
    vk: VerificationKey
  ) {
    await this.checkValidatorsDecision(
      proof,
      vk,
      ValidatorDecisionType["updateValidatorsList"]
    );
    await this.setValidatorsList(validators, storage);
  }
 
  /**
   * Checks the validators' decision by verifying the provided proof.
   *
   * @param {ValidatorsVotingProof} proof - The proof to verify.
   * @param {VerificationKey} vk - The verification key to validate the proof.
   * @param {Field} decisionType - The type of decision being validated.
   */
  async checkValidatorsDecision(
    proof: ValidatorsVotingProof,
    vk: VerificationKey,
    decisionType: Field
  ) {
    this.network.globalSlotSinceGenesis.requireBetween(
      UInt32.zero,
      proof.publicInput.decision.expiry
    );
    vk.hash.assertEquals(this.verificationKeyHash.getAndRequireEquals());
    proof.verify(vk);
    proof.publicInput.decision.validators
      .hash()
      .assertEquals(this.validators.getAndRequireEquals());
    proof.publicInput.decision.decisionType.assertEquals(decisionType);
    proof.publicInput.decision.contractAddress.assertEquals(this.address);
  }
}