Multi-Signature Wallets
Multi-signature (multisig) wallets require multiple parties to sign transactions before execution, providing enhanced security for shared assets.
Multi-Signature Patterns
Basic M-of-N Multisig
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract MultiSigWallet {
struct Transaction {
address to;
uint256 value;
bytes data;
uint256 confirmations;
bool executed;
mapping(address => bool) confirmationsBy;
}
address[] public owners;
uint256 public required;
uint256 public transactionCount;
mapping(uint256 => Transaction) public transactions;
modifier onlyOwners() {
require(isOwner[msg.sender], "Not an owner");
_;
}
modifier onlyRequired() {
require(owners.length >= required, "Invalid required");
_;
}
constructor(address[] memory _owners, uint256 _required) {
require(_owners.length > 0, "Owners required");
require(_required > 0 && _required <= _owners.length, "Invalid required");
for (uint256 i = 0; i < _owners.length; i++) {
address owner = _owners[i];
require(owner != address(0), "Invalid owner");
require(!isOwner[owner], "Owner not unique");
isOwner[owner] = true;
owners.push(owner);
}
required = _required;
}
function submitTransaction(
address to,
uint256 value,
bytes calldata data
) external onlyOwners returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
to: to,
value: value,
data: data,
confirmations: 0,
executed: false
});
transactionCount++;
emit TransactionSubmitted(transactionId, to, value, data);
}
function confirmTransaction(uint256 transactionId) external onlyOwners {
Transaction storage txn = transactions[transactionId];
require(!txn.confirmationsBy[msg.sender], "Already confirmed");
require(!txn.executed, "Already executed");
txn.confirmationsBy[msg.sender] = true;
txn.confirmations++;
emit TransactionConfirmed(transactionId, msg.sender);
}
function executeTransaction(uint256 transactionId) external onlyOwners {
Transaction storage txn = transactions[transactionId];
require(txn.confirmations >= required, "Insufficient confirmations");
require(!txn.executed, "Already executed");
txn.executed = true;
(bool success, ) = txn.to.call{value: txn.value}(txn.data);
require(success, "Execution failed");
emit TransactionExecuted(transactionId);
}
}
Gnosis Safe Integration
Safe Contract Architecture
Safe SDK Integration
import { ethers } from 'ethers';
import { SafeFactory } from '@safe-global/protocol-kit';
async function deploySafe() {
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
const safeFactory = await SafeFactory.init({
provider,
signer
});
const safeAccountConfig = {
owners: [
'0x1234567890123456789012345678901234567890',
'0xABCDEF1234567890ABCDEF1234567890ABCDEF12',
'0x9876543210987654321098765432109876543210'
],
threshold: 2
};
const safe = await safeFactory.deploySafeAccount(safeAccountConfig);
console.log('Safe deployed:', safe.getAddress());
}
Threshold Signatures
Threshold signatures distribute key generation and signing across multiple parties.
Shamir's Secret Sharing
Where:
- = reconstructed secret
- = Lagrange coefficient
- = individual shares
- = prime number
Lagrange Coefficient Formula
Threshold Signature Scheme
contract ThresholdSignature {
uint256 public constant THRESHOLD = 2;
uint256 public constant SHARES = 3;
struct Share {
uint256 x;
uint256 y;
bool used;
}
mapping(address => Share[]) public shares;
mapping(bytes32 => uint256) public signatureCount;
function submitShare(
bytes32 messageHash,
uint256 x,
uint256 y
) external {
shares[msg.sender].push(Share(x, y, true));
signatureCount[messageHash]++;
if (signatureCount[messageHash] >= THRESHOLD) {
_reconstruct(messageHash);
}
}
function _reconstruct(bytes32 messageHash) internal {
// Lagrange interpolation
uint256 result = 0;
// ... reconstruction logic
}
}
Key Management
Hierarchical Deterministic (HD) Keys
contract KeyManager {
struct Key {
bytes32 publicKey;
uint8 keyType; // 0: signing, 1: encryption, 2: meta
bool active;
uint256 addedAt;
}
mapping(address => Key[]) public keys;
mapping(address => mapping(uint256 => bool)) public keyOwners;
function addKey(
bytes32 publicKey,
uint8 keyType
) external {
keys[msg.sender].push(Key({
publicKey: publicKey,
keyType: keyType,
active: true,
addedAt: block.timestamp
}));
}
function revokeKey(uint256 index) external {
require(index < keys[msg.sender].length, "Invalid index");
keys[msg.sender][index].active = false;
}
}
Key Rotation Schedule
| Key Type | Rotation Period | Grace Period | Backup Required |
|---|---|---|---|
| Master Key | 90 days | 7 days | Yes |
| Session Key | 24 hours | 1 hour | No |
| Recovery Key | 180 days | 30 days | Yes |
| Admin Key | 30 days | 7 days | Yes |
Social Recovery
Social recovery allows trusted contacts to help restore access.
Guardian-Based Recovery
contract SocialRecovery {
struct Guardian {
address addr;
uint256 weight;
bool active;
bool voted;
}
struct RecoveryRequest {
address newOwner;
uint256 votes;
uint256 expiresAt;
bool executed;
}
mapping(address => Guardian[]) public guardians;
mapping(address => RecoveryRequest) public pendingRecovery;
uint256 public constant RECOVERY_DELAY = 48 hours;
uint256 public constant VOTE_PERIOD = 7 days;
function proposeRecovery(
address newOwner,
uint256 threshold
) external {
require(guardians[msg.sender].length > 0, "No guardians");
pendingRecovery[msg.sender] = RecoveryRequest({
newOwner: newOwner,
votes: 0,
expiresAt: block.timestamp + VOTE_PERIOD,
executed: false
});
}
function voteForRecovery(address account) external {
Guardian storage guardian = _getGuardian(account, msg.sender);
require(guardian.active, "Not an active guardian");
require(!guardian.voted, "Already voted");
guardian.voted = true;
pendingRecovery[account].votes += guardian.weight;
if (pendingRecovery[account].votes >= _getThreshold(account)) {
_executeRecovery(account);
}
}
}
Recovery Flow Diagram
Time-Locks
Time-locks add a delay before transaction execution, allowing for security reviews.
contract TimeLock {
uint256 public constant MIN_DELAY = 1 days;
uint256 public constant MAX_DELAY = 30 days;
mapping(bytes32 => uint256) public queuedTransactions;
function queue(
address target,
uint256 value,
bytes calldata data,
uint256 delay
) external onlyGovernance {
require(delay >= MIN_DELAY && delay <= MAX_DELAY, "Invalid delay");
bytes32 txHash = keccak256(abi.encode(target, value, data, block.timestamp));
queuedTransactions[txHash] = block.timestamp + delay;
emit TransactionQueued(txHash, target, value, data, delay);
}
function execute(
address target,
uint256 value,
bytes calldata data
) external onlyGovernance {
bytes32 txHash = keccak256(abi.encode(target, value, data, block.timestamp));
require(queuedTransactions[txHash] != 0, "Not queued");
require(block.timestamp >= queuedTransactions[txHash], "Too early");
delete queuedTransactions[txHash];
(bool success, ) = target.call{value: value}(data);
require(success, "Execution failed");
emit TransactionExecuted(txHash);
}
}
Trade-offs
| Feature | Simple Multisig | Threshold Sig | Social Recovery |
|---|---|---|---|
| Complexity | Low | High | Medium |
| Gas Cost | Medium | Low | High |
| Key Management | Simple | Complex | Medium |
| Recovery | None | None | Excellent |
| Security | Medium | High | High |
Real-World Example: Gnosis Safe on Mainnet
// Example: Creating a 2-of-3 Safe
import { ethers } from 'ethers';
import { SafeFactory } from '@safe-global/protocol-kit';
async function createMultisig() {
const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_KEY');
const safeFactory = await SafeFactory.init({
provider,
signer: new ethers.Wallet(PRIVATE_KEY, provider)
});
const safe = await safeFactory.deploySafeAccount({
owners: [
'0x1234567890123456789012345678901234567890',
'0xABCDEF1234567890ABCDEF1234567890ABCDEF12',
'0x9876543210987654321098765432109876543210'
],
threshold: 2
});
console.log('Safe deployed at:', safe.getAddress());
// Create a transaction
const txData = {
to: '0xRecipientAddress',
value: ethers.parseEther('1.0'),
data: '0x'
};
const safeTransaction = await safe.createTransaction({
transactions: [txData]
});
// Sign with first owner
const signature1 = await safe.signTransaction(safeTransaction);
// Execute with second owner's signature
const executeTx = await safe.executeTransaction(safeTransaction);
console.log('Transaction executed:', executeTx.hash);
}
Interview Questions
-
Explain the difference between M-of-N multisig and threshold signatures. What are the trade-offs of each approach?
-
How does Gnosis Safe handle key rotation and guardian management? What happens if a guardian is compromised?
-
Design a social recovery system for a DAO treasury that requires 3-of-5 guardian approval with a 48-hour time-lock.
Quiz Questions
-
What is the minimum number of confirmations required in a 2-of-3 multisig wallet?
- A) 1
- B) 2
- C) 3
- D) 4
-
In Shamir's Secret Sharing, what is the Lagrange coefficient used for?
- A) Encrypting shares
- B) Reconstructing the secret
- C) Generating shares
- D) Verifying signatures
-
What is the purpose of a time-lock in a multisig wallet?
- A) Speed up transactions
- B) Add a delay for security review
- C) Reduce gas costs
- D) Increase privacy
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions