← Back to Research
Overview
Smart contracts for conditional delivery, auto-expiry, time-locked messages, escrow, and programmable workflows embedded in email.
Problem Statement
Email is static: - No conditional logic - No time-based triggers - No automated workflows - No programmable delivery rules - Manual intervention required for complex scenarios
Vision
Traditional: Send message -> Delivered immediately -> Sits in inbox forever
Programmable:
- Send message -> Deliver ONLY IF conditions met
- Time-locked: Deliver on specific date/time
- Escrow: Require confirmation before reveal
- Auto-expire: Delete after N days
- Conditional access: Unlock based on events
- Workflow triggers: Auto-forward, auto-reply, auto-file
Use Cases
1. Time-Locked Messages
# Send message to future self
send_message(
to='future-me@msgs.global',
subject='1 Year Reflection',
body='What did I accomplish this year?',
unlock_at='2027-03-07T00:00:00Z'
)
# Birthday messages scheduled years in advance
# Encrypted until delivery time
2. Conditional Delivery
# Only deliver if contract signed
send_message(
to='vendor@company.com',
subject='Payment Confirmation',
condition={
'type': 'smart_contract',
'contract_address': '0x123...',
'event': 'PaymentReceived',
'parameters': {'amount': 50000, 'currency': 'USD'}
}
)
# Only deliver if recipient verifies identity
send_message(
to='recipient@example.com',
subject='Sensitive Information',
condition={
'type': 'identity_verification',
'method': '2FA',
'required_score': 90
}
)
3. Escrow Messages
# Proof of knowledge without revealing (until conditions met)
send_escrow_message(
to='lawyer@lawfirm.com',
subject='Intellectual Property Disclosure',
encrypted_body='[Patent details]',
unlock_conditions={
'both_parties_sign': ['inventor@msgs.global', 'lawyer@lawfirm.com'],
'or_time_elapsed': '90 days'
}
)
# Whistleblower protection: Reveal only if sender doesn't check in
dead_mans_switch(
to='journalist@news.org',
encrypted_body='[Confidential documents]',
sender_must_confirm_alive_every='7 days',
unlock_if_no_confirmation_after='14 days'
)
4. Auto-Expiry
# Self-destructing messages
send_message(
to='team@msgs.global',
subject='2FA Code: 123456',
body='Use this code within 5 minutes',
auto_delete_after='5 minutes',
prevent_forwarding=True,
prevent_copying=True # Client-side enforcement
)
5. Workflow Automation
# Auto-file based on conditions
when_message_received(
from_domain='github.com',
subject_contains='[PR]',
action={
'type': 'auto_file',
'folder': 'Work/Pull Requests',
'and_then': {
'type': 'webhook',
'url': 'https://myapi.com/pr-notification'
}
}
)
# Auto-reply with dynamic content
when_message_received(
to='support@msgs.global',
action={
'type': 'auto_reply',
'template': 'support_ack',
'variables': {
'ticket_id': lambda: generate_ticket_id(),
'eta': lambda: estimate_response_time()
},
'and_then': {
'type': 'forward',
'to': 'support-queue@msgs.global'
}
}
)
Technical Architecture
1. Message Contract Format
{
"message_id": "msg-123@msgs.global",
"from": "alice@msgs.global",
"to": "bob@msgs.global",
"subject": "[Encrypted until unlocked]",
"encrypted_body": "base64-encrypted-content",
"contract": {
"version": "1.0",
"unlock_conditions": [
{
"type": "time_lock",
"unlock_at": "2027-03-07T00:00:00Z"
},
{
"type": "sender_signature",
"required": true
},
{
"type": "recipient_verification",
"method": "2FA"
}
],
"auto_actions": [
{
"type": "auto_delete",
"trigger": "after_read",
"delay": "30 minutes"
}
],
"constraints": {
"max_forwards": 0,
"require_pgp_encryption": true,
"geographic_restriction": ["US", "EU"]
}
},
"contract_hash": "sha256:abc123...",
"contract_signature": "sender-signature"
}
2. Execution Engine
class MessageContractExecutor:
"""Execute programmable message contracts"""
def __init__(self, message_contract):
self.contract = message_contract
self.state = 'pending'
async def evaluate_conditions(self):
"""Check if unlock conditions are met"""
for condition in self.contract['unlock_conditions']:
if not await self.check_condition(condition):
return False
return True
async def check_condition(self, condition):
"""Evaluate individual condition"""
if condition['type'] == 'time_lock':
return datetime.now() >= datetime.fromisoformat(condition['unlock_at'])
elif condition['type'] == 'smart_contract':
# Query blockchain for contract event
event = await query_blockchain(
condition['contract_address'],
condition['event']
)
return event is not None
elif condition['type'] == 'sender_signature':
return verify_signature(
self.contract['contract_hash'],
self.contract['contract_signature']
)
elif condition['type'] == 'recipient_verification':
# Check if recipient verified their identity
return await verify_recipient_identity(
self.contract['to'],
condition['method']
)
elif condition['type'] == 'multi_sig':
# Require N of M parties to sign
signatures = self.get_signatures()
return len(signatures) >= condition['required_signatures']
return False
async def execute(self):
"""Execute contract when conditions met"""
if not await self.evaluate_conditions():
return {'status': 'pending', 'message': 'Conditions not yet met'}
# Conditions met - unlock message
decrypted_body = decrypt_message_body(self.contract['encrypted_body'])
# Deliver to recipient
deliver_message({
'from': self.contract['from'],
'to': self.contract['to'],
'subject': self.contract['subject'],
'body': decrypted_body
})
# Execute auto-actions
await self.execute_auto_actions()
return {'status': 'executed', 'delivered': True}
async def execute_auto_actions(self):
"""Execute automated actions"""
for action in self.contract.get('auto_actions', []):
if action['type'] == 'auto_delete':
if action['trigger'] == 'after_read':
# Schedule deletion after message is read
schedule_deletion(
self.contract['message_id'],
delay=action['delay']
)
elif action['type'] == 'webhook':
# Call webhook when message delivered
await call_webhook(action['url'], {
'message_id': self.contract['message_id'],
'event': 'delivered'
})
3. Condition Monitoring Service
# Background service checking contract conditions
async def contract_monitor():
"""Continuously monitor pending contracts"""
while True:
# Get all pending contracts
pending = db.query("""
SELECT * FROM message_contracts
WHERE state = 'pending'
""")
for contract in pending:
executor = MessageContractExecutor(contract)
# Check if conditions met
if await executor.evaluate_conditions():
# Execute contract
await executor.execute()
# Update state
db.execute("""
UPDATE message_contracts
SET state = 'executed'
WHERE message_id = ?
""", contract['message_id'])
# Sleep between checks
await asyncio.sleep(60) # Check every minute
Integration with msgs.global
Database Schema
-- Programmable message contracts
CREATE TABLE message_contracts (
id SERIAL PRIMARY KEY,
message_id VARCHAR(255) UNIQUE,
sender_email VARCHAR(255),
recipient_email VARCHAR(255),
contract_json JSONB,
contract_hash VARCHAR(64),
encrypted_body BYTEA,
state VARCHAR(20) DEFAULT 'pending', -- pending, executed, expired, cancelled
created_at TIMESTAMP DEFAULT NOW(),
unlock_at TIMESTAMP,
expires_at TIMESTAMP
);
-- Contract execution log
CREATE TABLE contract_executions (
id SERIAL PRIMARY KEY,
contract_id INTEGER REFERENCES message_contracts(id),
event_type VARCHAR(50), -- condition_met, action_executed, expired
event_data JSONB,
executed_at TIMESTAMP DEFAULT NOW()
);
-- Auto-actions queue
CREATE TABLE auto_actions_queue (
id SERIAL PRIMARY KEY,
contract_id INTEGER REFERENCES message_contracts(id),
action_type VARCHAR(50),
action_data JSONB,
execute_at TIMESTAMP,
executed BOOLEAN DEFAULT FALSE
);
CREATE INDEX idx_contracts_state ON message_contracts(state);
CREATE INDEX idx_contracts_unlock ON message_contracts(unlock_at) WHERE state = 'pending';
API Endpoints
@app.route('/api/v1/programmable/send', methods=['POST'])
def send_programmable_message():
"""Send programmable message with contract"""
data = request.json
# Create contract
contract = {
'message_id': generate_message_id(),
'from': request.current_user.email,
'to': data['to'],
'subject': data.get('subject', '[Encrypted]'),
'encrypted_body': encrypt_message(data['body']),
'contract': data['contract'],
'contract_hash': hash_contract(data['contract'])
}
# Sign contract
contract['contract_signature'] = sign_contract(
contract['contract_hash'],
request.current_user.private_key
)
# Store contract
db.execute("""
INSERT INTO message_contracts (
message_id, sender_email, recipient_email,
contract_json, contract_hash, encrypted_body
) VALUES (?, ?, ?, ?, ?, ?)
""", contract['message_id'], contract['from'], contract['to'],
json.dumps(contract['contract']), contract['contract_hash'],
contract['encrypted_body'])
return {'message_id': contract['message_id'], 'status': 'pending'}
@app.route('/api/v1/programmable/<message_id>/status')
def get_contract_status(message_id):
"""Check contract execution status"""
contract = db.query("""
SELECT * FROM message_contracts WHERE message_id = ?
""", message_id)
executor = MessageContractExecutor(contract)
conditions = await executor.evaluate_conditions()
return {
'message_id': message_id,
'state': contract.state,
'conditions_met': conditions,
'unlock_at': contract.unlock_at
}
@app.route('/api/v1/programmable/<message_id>/cancel', methods=['POST'])
def cancel_contract(message_id):
"""Cancel pending contract (sender only)"""
contract = db.query("""
SELECT * FROM message_contracts
WHERE message_id = ? AND sender_email = ?
""", message_id, request.current_user.email)
if contract.state != 'pending':
return {'error': 'Contract already executed'}, 400
db.execute("""
UPDATE message_contracts
SET state = 'cancelled'
WHERE message_id = ?
""", message_id)
return {'status': 'cancelled'}
Example Templates
1. Dead Man's Switch
dead_mans_switch = {
'unlock_conditions': [
{
'type': 'no_sender_checkin',
'period': '14 days'
}
],
'auto_actions': [
{
'type': 'deliver',
'to': ['trusted1@example.com', 'trusted2@example.com']
}
]
}
2. Birthday Time Capsule
birthday_capsule = {
'unlock_conditions': [
{
'type': 'time_lock',
'unlock_at': '2030-03-07T00:00:00Z'
}
],
'auto_actions': [
{
'type': 'deliver'
}
]
}
3. Contract Escrow
escrow_contract = {
'unlock_conditions': [
{
'type': 'multi_sig',
'required_signatures': 2,
'signers': ['party1@msgs.global', 'party2@msgs.global']
},
{
'type': 'or_time_lock',
'unlock_at': '2026-06-01T00:00:00Z' # Auto-release after 3 months
}
]
}
Security Considerations
- Contract Immutability: Once sent, contracts cannot be modified (only cancelled)
- Encryption: Message body encrypted until conditions met
- Signature Verification: All contracts cryptographically signed
- Replay Protection: Contract hash includes timestamp and nonce
- Resource Limits: Prevent DoS (max execution time, max conditions)
Status
🔬 Research & Design Phase
Next Steps
- Define contract specification (JSON schema)
- Build execution engine prototype
- Implement common contract templates
- Security audit of execution logic
- User testing (UX for programming messages)
- Performance testing (monitoring overhead)