Mvmultifactor.sol
Overview
The Multifactor contract implements a multi-factor authentication system for secure transaction management and key handling on the blockchain. It manages ephemeral public keys (factors), JSON Web Key (JWK) data, and security cards, allowing controlled authorization of transactions through multiple cryptographic proofs and signatures. It also maintains a queue of pending transactions requiring confirmation from security cards before execution, enabling stronger security for value transfers.
The contract supports adding, updating, and deleting cryptographic factors and keys, managing ownership and recovery mechanisms, and interacting with a mirrored contract instance for whitelist updates. It enforces expiration policies on keys and transactions to ensure ongoing security.
Data Structures
Transaction
Represents a queued transaction requiring confirmation.
id (
uint64): Unique transaction identifier.creator (
uint256): Ephemeral public key of the transaction creator.dest (
address): Destination address of the transfer.value (
uint128): Amount of nanograms to transfer.cc (
mapping(uint32 => varuint32)): ECC token amounts by currency code.sendFlags (
uint16): Flags for sending internal messages.payload (
TvmCell): Payload for the outbound internal message.bounce (
bool): Bounce flag for the outbound message header.
JWKData
Represents JSON Web Key modulus data.
modulus (
bytes): The modulus bytes.modulus_expire_at (
uint64): Expiration timestamp of the modulus.
Constants and Flags
version (
string): Contract version "1.0.1".FLAG_PAY_FWD_FEE_FROM_BALANCE(uint8): Flag for paying forward fees from contract balance.FLAG_SEND_ALL_REMAINING (
uint8): Flag instructing node to send all remaining balance.
State Variables
_factors_ordered_by_timestamp(mapping(uint256 => uint256)): Maps combined expiration timestamp and ephemeral public key keys to ephemeral public keys, ordered by expiration._factors_len(uint8): Count of active ephemeral public keys._root(address): Address of the root contract._name(string): Name identifier for this contract instance._owner_pubkey(uint256, static): Owner's master public key (seed phrase)._candidate_new_owner_pubkey_and_expiration(optional(uint256, uint64)): Candidate new owner pubkey and expiration._pub_recovery_key(uint256): Public key for recovery._jwk_update_key(uint256): Public key authorized to update JWK data._root_provider_certificates(mapping(uint256 => bytes)): Root provider certificates indexed by certificate serial number._jwk_modulus_data(mapping(uint256 => JWKData)): Stores JWK modulus data indexed by hashedkid._jwk_modulus_data_len(uint8): Number of stored JWK modulus entries._start_point_jwk(optional(uint256, JWKData)): Iterator start point for cleaning expired JWKs._zkid(string): Identifier for zero-knowledge provider._index_mod_4(uint8): Index mod 4 used in cryptographic operations._iss_base_64(string): Base64 encoded issuer string._lv_provider_bytes(bytes): Provider-related bytes._use_security_card(bool): Enables or disables security card authentication._m_security_cards(mapping(uint256 => bool)): Authorized security card public keys._m_security_cards_len(uint8): Count of security cards._m_transactions(mapping(uint64 => Transaction)): Queued transactions awaiting security card confirmation._m_transactions_len(uint8): Number of pending transactions._min_value(uint128): Minimum value allowed for transfers._max_cleanup_txns(uint256): Maximum number of transactions to clean up during expiration._force_remove_oldest(bool): Flag to force removal of the oldest ZKP factor when max count reached._whiteListOfAddress(mapping(address => bool)): Whitelist of addresses allowed to receive payloads._verification_key_index(uint32): Index used for cryptographic verification.
Constructor
Initializes the contract with provided parameters including contract name, cryptographic keys, proofs, zero-knowledge identifiers, provider information, and root certificates.
Parameters:
name(string): Contract instance name.zkid(string): Zero-knowledge identifier.proof(bytes): Cryptographic proof for initialization.epk(uint256): Ephemeral public key.epk_sig(bytes): Signature of ephemeral public key.epk_expire_at(uint64): Expiration timestamp of ephemeral public key.jwk_modulus(bytes): JWK modulus bytes.kid(bytes): Key ID for the JWK modulus.jwk_modulus_expire_at (
uint64): Expiration timestamp for JWK modulus.index_mod_4(uint8): Index mod 4 for cryptographic usage.iss_base_64(string): Base64 encoded issuer string.provider(string): Provider name.header_base_64(string): Base64 encoded header.pub_recovery_key(uint256): Recovery public key.pub_recovery_key_sig(bytes): Signature of recovery key.jwk_update_key(uint256): Public key authorized to update JWK.jwk_update_key_sig (
bytes): Signature of JWK update key.root_provider_certificates(mapping(uint256 => bytes)): Root provider certificates.index(uint128): Index for contract address calculation.
Initialization Steps:
Validates input parameters and signatures.
Verifies cryptographic proof against the provided data.
Derives root address and validates sender.
Initializes state variables including keys, certificates, whitelist, and provider bytes.
Deploys a Mirror contract instance for whitelist management.
Key Functionalities
Factor Management
addZKPfactor- Adds a new zero-knowledge proof (ZKP) factor with validation of proof and key expiration. Returnstrueon success.deleteZKPfactorByItself- Deletes a ZKP factor by its expiration timestamp if called by the factor owner.cleanExpiredZKPFactors- Cleans expired ZKP factors from storage (private).cleanOldestZKPFactor- Removes the oldest ZKP factor if forced removal is enabled (private).cleanAllExpiredZKPFactors- Public method to clean all expired ZKP factors after verifying sender.deleteZKPfactoranddeleteZKPfactor_- Owner-only methods to delete factors by expiration or ephemeral key.
JWK Management
addJwkModulus- Adds a new JWK modulus entry after validating provider certificates and running WASM verification.deleteJwkModulusByUpdateJwkKey- Deletes a JWK modulus entry by authorized JWK update key.cleanExpiredJwks- Cleans expired JWK keys from storage (private).cleanAllExpiredJwks- Public method to clean expired JWKs after verifying sender.deleteJwkModulusByFactor- Deletes a JWK modulus using factor authorization.deleteJwkModulus- Owner-only method to delete a JWK modulus entry.cleanAllJwks- Owner-only method to purge all JWK modulus data.
Transaction Management
submitTransaction- Submits a new transaction for transfer. If security cards are enabled, queues the transaction for confirmation; otherwise, executes immediately.confirmTransaction- Confirms and executes a queued transaction by a security card public key.removeExpiredTransactions - Removes expired transactions from the queue (private).
sendTransaction- Sends a transaction immediately if security cards are off, validating signatures and whitelists.getTransaction,getTransactions,getTransactionIds- Getters to retrieve transaction details or IDs.
Security Cards
addSecurityCard- Adds a new security card public key, which enables security card functionality.turnOffSecurityCards/turnOnSecurityCards- Enables or disables the use of security cards.deleteSecurityCard- Deletes a specific security card.deleteAllSecurityCards- Removes all security cards and disables the feature.getSecurityCardKeys- Returns all security card public keys.
Owner and Recovery Key Management
updateRecoveryPhrase- Updates the recovery public key with signature validation.updateJwkUpdateKey- Updates the JWK update public key with signature validation.updateSeedPhrase- Updates the owner public key with signature validation.changeSeedPhrase- Proposes a new owner public key using factor authorization.acceptCandidateSeedPhrase- Recovery key accepts the proposed new owner public key.deleteCandidateSeedPhrase- Deletes the candidate owner public key proposal.
Whitelist Management
cleanWhiteList- Clears the whitelist except the root after verifying factor authorization.updateWhiteList- Updates whitelist on the Mirror contract instance.setWhiteList- Adds an address to the whitelist, verifying sender and limits.
Auxiliary Functions
setWasmHash - Sets the WASM hash used for JWK verification.
setForceRemoveOldest- Sets flag to force removal of oldest ZKP factor.addRootProviderCertificate,deleteRootProviderCertificate,cleanRootProviderCertificates- Manage root provider certificates.setMaxCleanupTxns- Sets the maximum transactions to clean during expiration.setMinValue - Sets minimum allowed value for transfers.
generateTrxId- Generates unique transaction IDs.getExpirationBound- Calculates expiration boundary timestamp.getSendFlags - Returns send flags based on
allBalanceflag.getZKPEphemeralPublicKeys- Returns all stored ephemeral public keys.get_epk_expire_at- Returns expiration timestamp for a given ephemeral public key.getVersion- Returns contract version and name.getTimeStamp - Returns current block timestamp.
Important Implementation Details and Algorithms
Key Expiration and Ordering: Ephemeral public keys and JWK data are stored in mappings ordered by a combined key consisting of a 64-bit expiration timestamp left-shifted by 192 bits concatenated with 192 lower bits of the key data. This ordering allows efficient iteration and cleanup of expired entries.
Signature and Proof Validation: Multiple cryptographic verifications are performed using
tvm.checkSignand zero-knowledge proof validation throughgosh.vergrth16andgosh.poseidonto ensure authenticity and integrity of keys and transactions.WASM-based JWK Verification: The contract uses a WASM module to verify TLS data for JWK modulus updates dynamically, ensuring up-to-date and valid key data from providers.
Security Card Multi-Signature: When enabled, transactions require confirmation by an authorized security card public key, enhancing security through multi-factor approval.
Transaction Queue Management: Transactions are queued and assigned unique IDs, with automatic cleanup of expired transactions to avoid storage bloat.
Whitelist Enforcement: Outbound transactions with payloads are restricted to a whitelist of approved addresses, maintained via Mirror contract interactions for distributed management.
Interactions with Other Contracts and Components
Modifiers.sol: Provides modifiers such as onlyOwnerPubkey and
acceptthat enforce access control and message acceptance.VerifiersLib.sol: Likely provides cryptographic verification utilities used for checking signatures and proofs.
MobileVerifiersContractRoot.sol: The root contract address is stored and used for authorization and hierarchical control.
Mirror.sol: Used to deploy and interact with a mirror contract instance that manages whitelist updates and synchronization.
Gosh Library: Provides cryptographic primitives (
poseidon,vergrth16, runwasmconcatmultiarg) for proof verification and WASM execution.
The contract assumes a tightly coupled environment where these external components provide necessary cryptographic and blockchain utilities.
Usage Examples
Adding a New ZKP Factor
bool added = multifactor.addZKPfactor(
proof,
epk,
kid,
header_base_64,
epk_expire_at
);
require(added, "Failed to add ZKP factor");
Submitting a Transaction (queued if security cards enabled)
uint64 transactionId = multifactor.submitTransaction(
epk_expire_at,
dest,
value,
cc,
bounce,
allBalance,
payload
);
if (transactionId == 0) {
// Transaction executed immediately
} else {
// Transaction queued for confirmation
}
Confirming a Queued Transaction
multifactor.confirmTransaction(transactionId);
Updating Recovery Key by Owner
multifactor.updateRecoveryPhrase(new_pub_recovery_key, new_pub_recovery_key_sig);
Managing Security Cards
multifactor.addSecurityCard(pubkey, pubkey_sig);
multifactor.turnOnSecurityCards();
multifactor.deleteSecurityCard(pubkey);
Mermaid Diagram
classDiagram
class Multifactor {
+Transaction
+JWKData
-_factors_ordered_by_timestamp: mapping
-_factors_len: uint8
-_root: address
-_name: string
-_owner_pubkey: uint256
-_candidate_new_owner_pubkey_and_expiration: optional
-_pub_recovery_key: uint256
-_jwk_update_key: uint256
-_root_provider_certificates: mapping
-_jwk_modulus_data: mapping
-_jwk_modulus_data_len: uint8
-_start_point_jwk: optional
-_zkid: string
-_index_mod_4: uint8
-_iss_base_64: string
-_lv_provider_bytes: bytes
-_use_security_card: bool
-_m_security_cards: mapping
-_m_security_cards_len: uint8
-_m_transactions: mapping
-_m_transactions_len: uint8
-_min_value: uint128
-_max_cleanup_txns: uint256
-_force_remove_oldest: bool
-_whiteListOfAddress: mapping
-_verification_key_index: uint32
+constructor()
+addZKPfactor()
+deleteZKPfactorByItself()
+cleanExpiredZKPFactors()
+cleanOldestZKPFactor()
+cleanAllExpiredZKPFactors()
+addJwkModulus()
+deleteJwkModulusByUpdateJwkKey()
+cleanExpiredJwks()
+cleanAllExpiredJwks()
+deleteJwkModulusByFactor()
+submitTransaction()
+confirmTransaction()
+sendTransaction()
+addSecurityCard()
+turnOffSecurityCards()
+turnOnSecurityCards()
+deleteSecurityCard()
+deleteAllSecurityCards()
+updateRecoveryPhrase()
+updateJwkUpdateKey()
+updateSeedPhrase()
+changeSeedPhrase()
+acceptCandidateSeedPhrase()
+deleteCandidateSeedPhrase()
+cleanWhiteList()
+updateWhiteList()
+setWhiteList()
+getTransaction()
+getTransactions()
+getTransactionIds()
+getZKPEphemeralPublicKeys()
+getSecurityCardKeys()
+get_epk_expire_at()
+getVersion()
}