* clear

* feat: Add everything

* fix: Commenht
This commit is contained in:
Prad Nukala
2025-10-03 14:45:52 -04:00
committed by GitHub
parent 43b4a11c06
commit 13e6c3e84d
1935 changed files with 655061 additions and 40058 deletions
+221
View File
@@ -0,0 +1,221 @@
---
title: "Authorization with UCAN"
description: "Comprehensive guide to creating, validating, and managing User-Controlled Authorization Network (UCAN) tokens"
sidebarTitle: Client Authorization
icon: "badge-check"
---
# UCAN Token Operations
User-Controlled Authorization Networks (UCAN) provide a decentralized authorization mechanism that enables flexible, portable, and secure token-based access control.
## Overview
UCAN tokens are JWT-based authorization tokens that allow:
- Decentralized identity verification
- Granular access control
- Delegatable permissions
- Cryptographic proof of authorization
## Token Structure
A UCAN token consists of:
- Issuer DID
- Audience DID
- Capabilities (Attenuations)
- Proofs (Optional parent tokens)
- Time-based constraints
## Creating Origin Tokens
An origin token is the first token in a delegation chain:
```go
type NewOriginTokenRequest struct {
AudienceDID string // Target DID
Attenuations []map[string]any // Token restrictions
Facts []string // Additional claims
NotBefore int64 // Token activation time
ExpiresAt int64 // Token expiration time
}
// Example origin token creation
originToken := NewOriginTokenRequest{
AudienceDID: "did:sonr:example-recipient",
Attenuations: []{
{
"capability": "read",
"resource": "/storage/documents"
}
},
Facts: ["authenticated_user"],
NotBefore: time.Now().Unix(),
ExpiresAt: time.Now().Add(24 * time.Hour).Unix()
}
```
## Creating Attenuated Tokens
Attenuated tokens derive from existing tokens, further restricting capabilities:
```go
type NewAttenuatedTokenRequest struct {
ParentToken string // Previous token
AudienceDID string // New token recipient
Attenuations []map[string]any // Further restrictions
Facts []string // Additional claims
NotBefore int64 // Token activation time
ExpiresAt int64 // Token expiration time
}
// Example attenuated token
attenuatedToken := NewAttenuatedTokenRequest{
ParentToken: originTokenString,
AudienceDID: "did:sonr:delegated-user",
Attenuations: []{
{
"capability": "read",
"resource": "/storage/documents/public"
}
}
}
```
## Token Validation Workflow
```go
func ValidateUCANToken(token string) (bool, error) {
// 1. Parse the token
parsedToken, err := jwt.Parse(token, keyFunc)
if err != nil {
return false, err
}
// 2. Verify issuer DID
issuerDID := parsedToken.Claims["iss"]
if !isDIDValid(issuerDID) {
return false, errors.New("invalid issuer DID")
}
// 3. Check audience
audienceDID := parsedToken.Claims["aud"]
if !isCurrentUserAudience(audienceDID) {
return false, errors.New("token not intended for this audience")
}
// 4. Validate time constraints
if isTokenExpired(parsedToken) {
return false, errors.New("token has expired")
}
// 5. Check capabilities
capabilities := parsedToken.Claims["att"]
if !validateCapabilities(capabilities) {
return false, errors.New("insufficient capabilities")
}
// 6. Verify proofs (if present)
proofs := parsedToken.Claims["prf"]
if !validateProofChain(proofs) {
return false, errors.New("invalid proof chain")
}
return true, nil
}
```
## Capability Patterns
### Read Capabilities
```json
{
"capability": "read",
"resource": "/storage/documents",
"conditions": {
"max_size": "10MB",
"allowed_types": ["pdf", "txt"]
}
}
```
### Write Capabilities
```json
{
"capability": "write",
"resource": "/storage/documents",
"conditions": {
"max_files": 5,
"max_file_size": "50MB"
}
}
```
## Practical Examples
### Decentralized File Sharing
```go
// Create an origin token for file access
originToken := NewOriginTokenRequest{
AudienceDID: "did:sonr:collaborator",
Attenuations: []{
{
"capability": "read",
"resource": "/project/design-docs"
},
{
"capability": "write",
"resource": "/project/design-docs/comments"
}
},
ExpiresAt: time.Now().Add(30 * 24 * time.Hour).Unix()
}
// Later, create a more restricted token
limitedToken := NewAttenuatedTokenRequest{
ParentToken: originTokenString,
AudienceDID: "did:sonr:junior-designer",
Attenuations: []{
{
"capability": "read",
"resource": "/project/design-docs/public"
}
}
}
```
## Security Considerations
- Use the shortest possible token lifetime
- Implement granular capabilities
- Validate all tokens before use
- Rotate keys regularly
- Log and monitor token usage
## Performance Optimization
- Cache validated tokens
- Use efficient JWT parsing
- Implement token revocation lists
## Advanced Topics
- [DID Module](/blockchain/modules/did/)
- [DWN Architecture](/blockchain/modules/dwn/architecture)
- [Service Registry](/blockchain/modules/svc/)
## Error Handling
```go
type UCANError struct {
Code string
Message string
Details map[string]any
}
```
By leveraging UCAN tokens, you can create a flexible, secure, and decentralized authorization system that puts users in control of their access.
+411
View File
@@ -0,0 +1,411 @@
---
title: Transactions
description: Transaction types, fee structures, and token mechanics for SNR within the Sonr network
sidebarTitle: Broadcast Transactions
icon: "send"
---
## Overview
SNR token transactions power the revolutionary Sonr ecosystem, enabling gasless onboarding, stake-based service registration, and UCAN-authorized operations. The unique architecture allows for both traditional fee-based transactions and innovative gasless user experiences.
<Note>
Sonr features both traditional fee-based transactions and revolutionary
gasless operations like vault claiming, enabling zero-barrier user onboarding
while maintaining network security through economic incentives.
</Note>
## Transaction Types
### Basic Transfers
The foundation of the SNR economy consists of peer-to-peer token transfers:
<CardGroup>
<Card title="Simple Transfers">
Direct SNR transfers between addresses with minimal gas fees
</Card>
<Card title="Multi-send">
Batch transfers to multiple recipients in a single transaction
</Card>
<Card title="Scheduled Transfers">
Time-locked transfers with vesting or release conditions
</Card>
</CardGroup>
### Module-Specific Transactions
Each Sonr core module enables specialized transaction types with specific SNR token requirements:
#### Service Module (x/svc) Transactions
- **MsgRegisterService**: Register a new service with TLD domain verification and capability requests
- **MsgUpdateService**: Update service metadata or request additional permissions
- **DNS Verification**: Simple DNS TXT record verification for domain ownership
- **Stake Requirements**: Services must stake SNR tokens based on requested capabilities
#### DWN Module (x/dwn) Transactions
- **MsgClaimVault**: **Gasless** transaction for claiming user vaults during onboarding
- **Vault Configuration Updates**: Paid transactions for advanced vault settings and WASM runtime upgrades
- **Cross-Chain Operations**: SNR fees for multi-chain vault management and bridging
- **MPC Operations**: Transaction fees for multi-party computation within secure enclaves
#### UCAN Module (x/ucan) Transactions
- **MsgIssueRootCapability**: Request MPC threshold signing for root capability tokens
- **MsgSubmitThresholdShare**: Validators submit MPC shares for capability creation
- **MsgRevokeCapability**: Revoke previously issued capability tokens on-chain
- **Delegation Chain Processing**: Computational fees for validating complex authorization chains
#### DID Module (x/did) Transactions
- **DID Registration**: Fees for creating new decentralized identifiers
- **MsgLinkAuthentication**: Add WebAuthn credentials or other authentication methods
- **MsgLinkAssertion**: Link identity claims and verifications to DIDs
- **MsgExecuteTx**: Execute UCAN-authorized transactions on behalf of DIDs
## Fee Structure
### Dual Fee Model
Sonr implements a revolutionary dual fee model supporting both traditional gas fees and gasless operations:
```math
\text{Fee} = \begin{cases}
0 & \text{for gasless operations (vault claiming)} \\
\text{Base Cost} + (\text{Gas Used} \times \text{Gas Price}) & \text{for standard transactions}
\end{cases}
```
<Warning>
While basic vault claiming is gasless, advanced operations like service
registration, MPC signing, and cross-chain transactions require SNR tokens for
network security and spam prevention.
</Warning>
### Fee Components
<CardGroup>
<Card title="MPC Computation">
Multi-party computation costs for threshold signing and capability issuance
</Card>
<Card title="Stake-Based Security">
Service registration fees that are burned or sent to community pool
</Card>
<Card title="Cross-Chain Operations">
IBC and InterchainAccount transaction costs for bridgeless operations
</Card>
<Card title="Identity Operations">
DID registration, authentication linking, and credential management
</Card>
</CardGroup>
### Economic Mechanisms
The network implements sophisticated economic mechanisms:
1. **Gasless Subsidies**: Network subsidizes vault claiming for zero-barrier onboarding
2. **Stake-Based Pricing**: Service registration costs scale with capability requests
3. **MPC Rewards**: Validators earn additional fees for threshold signing participation
4. **Deflationary Pressure**: Service registration fees are burned, reducing total supply
## Transaction Lifecycle
### Gasless Vault Claiming Flow
```mermaid
graph LR
A[WebAuthn Creation] --> B[Client-Side Vault Config]
B --> C[Submit MsgClaimVault]
C --> D[Network Subsidy Check]
D --> E[Gasless Execution]
E --> F[Vault Active]
```
### Service Registration Flow
```mermaid
graph LR
A[DNS Verification] --> B[Stake Calculation]
B --> C[MsgRegisterService]
C --> D[Capability Request]
D --> E[MPC Signing]
E --> F[Root UCAN Issued]
```
### UCAN Authorization Flow
```mermaid
graph LR
A[Service Request] --> B[Capability Check]
B --> C[User Approval]
C --> D[UCAN Creation]
D --> E[Delegation Chain]
E --> F[Authorized Execution]
```
### Standard Transaction Processing
1. **UCAN Validation**: Check authorization tokens and delegation chains
2. **Module Routing**: Route to appropriate module (svc, dwn, ucan, did)
3. **MPC Coordination**: Multi-party computation for sensitive operations
4. **State Updates**: Update module-specific state and emit events
5. **Fee Distribution**: Distribute fees to validators, burn pool, and treasury
## Advanced Features
### UCAN-Powered Automation
Enable sophisticated authorization patterns:
<CardGroup>
<Card title="Capability Delegation">
Services receive granular, time-limited permissions from users
</Card>
<Card title="Agent Execution">
Motr Vaults execute pre-authorized actions without user intervention
</Card>
<Card title="Subscription Automation">
Recurring payments and service interactions through UCAN tokens
</Card>
</CardGroup>
### Multi-Party Computation Integration
Leverage MPC for secure operations:
- **Threshold Signing**: Validators collaborate to issue root capabilities
- **Key Sharding**: No single point of failure for vault key management
- **Secure Enclaves**: WASM-based computation with hardware security
- **Privacy Preservation**: Zero-knowledge proofs for sensitive operations
### Cross-Module Interactions
Transactions can interact with multiple Sonr modules in powerful combinations:
```typescript
// Example: Complete user onboarding with service registration
const tx = {
messages: [
// DID Module: Create decentralized identity
{
type: "did/MsgCreateDID",
creator: "sonr1abc...",
document: didDocument,
webauthnCredential: credential,
},
// DWN Module: Claim gasless vault
{
type: "dwn/MsgClaimVault",
creator: "did:sonr:alice123",
vaultConfig: vaultCID,
mpcThreshold: 3,
},
// Service Module: Register domain service
{
type: "svc/MsgRegisterService",
creator: "did:sonr:alice123",
domain: "alice-app.com",
capabilities: ["dwn:read", "dwn:write"],
stakeAmount: "5000usnr",
},
// UCAN Module: Request root capability
{
type: "ucan/MsgIssueRootCapability",
issuer: "did:sonr:alice123",
audience: "alice-app.com",
capabilities: ["service:register"],
},
],
fee: {
amount: [{ denom: "usnr", amount: "5000" }], // Only service registration fee
gasLimit: "500000",
},
memo: "Complete onboarding: Identity + Vault + Service + Capabilities",
};
// Example: Cross-chain payment automation
const paymentTx = {
messages: [
// UCAN: Validate payment authority
{
type: "ucan/MsgValidateCapability",
token: ucanPaymentToken,
requestedAction: "payment:send",
},
// DID: Execute authorized transaction
{
type: "did/MsgExecuteTx",
signer: "did:sonr:alice123",
targetChain: "osmosis-1",
transaction: swapTransaction,
authorization: ucanToken,
},
],
};
```
## Performance Optimization
### Module-Specific Batching
Optimize transactions by batching within module boundaries:
1. **DWN Operations**: Batch vault updates and data operations
2. **Service Operations**: Group domain verifications and capability requests
3. **UCAN Processing**: Batch capability validations and delegation chains
4. **Cross-Chain Coordination**: Bundle InterchainAccount operations
### Gasless Operation Prioritization
Sonr prioritizes gasless operations to enhance user experience:
<Check>
Gasless vault claiming is prioritized by validators to enable zero-friction
onboarding. Service registration and MPC operations use dynamic pricing based
on network demand and stake requirements.
</Check>
### MPC Coordination Efficiency
Multi-party computation operations are optimized for performance:
```typescript
// MPC threshold signing optimization
interface MPCOptimization {
parallelShares: boolean; // Generate shares in parallel
precomputedCommitments: boolean; // Cache commitments
batchSigning: boolean; // Sign multiple capabilities together
networkSharding: boolean; // Distribute computation load
}
```
## Security Considerations
### Module-Specific Security
- **DID Security**: WebAuthn hardware-backed authentication prevents identity theft
- **UCAN Validation**: Cryptographic proof chains ensure capability authenticity
- **Vault Isolation**: MPC key sharding prevents single points of failure
- **Service Reputation**: Stake-based trust system deters malicious actors
### Zero-Knowledge Privacy
Sonr implements privacy-preserving transaction patterns:
```typescript
// Privacy-preserving operations
interface PrivacyFeatures {
zkProofs: {
ageVerification: boolean; // Prove age without revealing birthdate
balanceProofs: boolean; // Prove sufficient funds without amounts
reputationProofs: boolean; // Prove service quality without data
};
selectiveDisclosure: {
didDocuments: boolean; // Share only necessary identity claims
vaultData: boolean; // Controlled data access permissions
paymentHistory: boolean; // Private transaction records
};
}
```
### Best Practices for Sonr Transactions
1. **UCAN Validation**: Always verify capability tokens before execution
2. **MPC Coordination**: Ensure threshold requirements are met
3. **Gasless Limits**: Monitor gasless operation quotas and fallbacks
4. **Cross-Chain Safety**: Validate IBC channel security and timeouts
## Fee Distribution
SNR transaction fees are distributed to align network incentives:
<CardGroup>
<Card title="Validators (35%)">
Block proposers and MPC threshold signers receive primary rewards
</Card>
<Card title="Burn Pool (25%)">
Service registration fees burned for deflationary pressure
</Card>
<Card title="Community Treasury (25%)">
Development and ecosystem growth funds
</Card>
<Card title="Gasless Subsidy (10%)">
Funds vault claiming and onboarding operations
</Card>
<Card title="IBC Relayers (5%)">
Cross-chain message delivery and InterchainAccount operations
</Card>
</CardGroup>
### Module-Specific Fee Sources
```typescript
// Fee sources by module
interface ModuleFees {
svc: {
domainRegistration: "25% to burn, 75% to validators";
capabilityRequests: "Deposit-based, refundable on completion";
stakeSlashing: "100% to community treasury";
};
dwn: {
vaultClaiming: "Gasless (subsidized by treasury)";
storageOperations: "Standard gas fees";
mpcOperations: "Premium fees for computation";
};
ucan: {
rootCapabilityIssuance: "MPC coordination fees";
delegationValidation: "Minimal computational costs";
revocations: "Standard gas fees";
};
did: {
didRegistration: "One-time identity creation fee";
credentialLinking: "WebAuthn integration costs";
crossChainExecution: "IBC and InterchainAccount fees";
};
}
```
## Future Enhancements
### Revolutionary Capabilities in Development
- **AI-Powered Automation**: Natural language transaction commands through Motr Vault agents
- **Predictive Authorization**: Pre-approve expected transactions based on user patterns
- **W3C Payment Handler**: Native browser integration for seamless Web2/Web3 payments
- **Subscription Automation**: Recurring payments through UCAN capability delegation
- **Privacy-First Operations**: Full zero-knowledge transaction processing
- **Hardware Enclave Integration**: Dedicated Sonr hardware for enhanced security
- **Cross-Chain DeFi**: Seamless DeFi operations across all supported chains
- **Social Recovery Networks**: Trustless account recovery through guardian systems
### Standards-Based Interoperability
Building on open standards for maximum compatibility:
```typescript
// Future standards integration
interface FutureStandards {
w3cCompliance: {
paymentHandlerAPI: "Native browser payment integration";
webauthnLevel3: "Enhanced biometric authentication";
didCore2: "Next-generation identity standards";
};
crossChainStandards: {
ibcV2: "Enhanced cross-chain capabilities";
cosmwasmCompatibility: "Universal smart contract execution";
evmIntegration: "Ethereum Virtual Machine support";
};
privacyStandards: {
zkStarks: "Scalable zero-knowledge proofs";
selectiveDisclosure: "W3C verifiable credentials";
confidentialComputing: "Hardware-backed privacy";
};
}
```
+48
View File
@@ -0,0 +1,48 @@
---
title: "Configuring a Validator Node"
sidebarTitle: "Command Line"
description: "Setup a validator node on the Sonar Network in your local environment"
icon: "terminal"
---
**1. Initialize a blockchain node**
```sh
sonrd init localnet
```
**2. Generate account keys**
```sh
sonrd keys add test-validator
```
**3. Add the account to the genesis file**
```sh
sonrd add-genesis-account $(sonrd keys show test-validator -a) 1000000000000000000000000000stake,1000000000000000000000000000snr
```
**4. Generate a genesis transaction**
```sh
sonrd gentx test-validator 1000000000000000000000000000stake --chain-id localnet
```
**5. Collect genesis transactions**
```sh
sonrd collect-gentxs
```
**6. Validate the genesis file**
```sh
sonrd validate-genesis
```
**7. Start the blockchain node**
```sh
sonrd start
```
+8
View File
@@ -0,0 +1,8 @@
---
title: Production Network Deployment
description: Complete guide for becoming a Sonr blockchain validator - from setup to operations
icon: "ship"
sidebarTitle: Deploy Network & Services
---
+8
View File
@@ -0,0 +1,8 @@
---
title: Local Development Setup
description: Complete guide for becoming a Sonr blockchain validator - from setup to operations
icon: "code"
sidebarTitle: Setup Your Environment
---
+173
View File
@@ -0,0 +1,173 @@
---
title: Requesting Permissions
description: A guide to setting up and managing wallet connections with the Sonr decentralized identity system
icon: "shield-check"
---
Sonr provides a seamless and secure way for users to connect their wallets to decentralized applications. This guide covers the different methods for establishing and managing wallet connections, from simple browser-based interactions to backend service integrations.
## The Sonr Connection Model
Unlike traditional Web3 wallets that require browser extensions, Sonr uses a combination of WebAuthn and Decentralized Identifiers (DIDs) to create a secure, passwordless connection experience.
<CardGroup>
<Card title="User-Centric" href="/blockchain/modules/did/">
Users control their identity and grant permissions to applications, not the
other way around.
</Card>
<Card title="Passwordless" href="/blockchain/modules/did/">
WebAuthn enables biometric and security key authentication, eliminating the
need for seed phrases.
</Card>
<Card title="Multi-Device" href="/blockchain/modules/dwn/">
Users can securely access their Vault from any device with a modern web
browser.
</Card>
</CardGroup>
## Connecting in the Browser
For web applications, the Sonr SDK provides a simple way to initiate a wallet connection.
<Steps>
<Step>
### 1. Initialize the SDK
First, initialize the Sonr SDK in your application. For this example, we'll use the CDN version.
```html
<script type="module">
import { Sonr } from "https://cdn.jsdelivr.net/npm/@sonr/sdk";
const sonr = new Sonr({ httpUrl: "http://localhost:1317" });
</script>
```
</Step>
<Step>
### 2. Request Authentication
Use the `sonr.authenticate()` method to prompt the user to connect their wallet. This will trigger the browser's WebAuthn flow.
```javascript
async function connectWallet() {
try {
const session = await sonr.authenticate();
console.log("Wallet connected!", session);
// You now have a secure session with the user's Vault
} catch (error) {
console.error("Failed to connect wallet:", error);
}
}
```
</Step>
<Step>
### 3. Handle the Session
The `session` object returned from `authenticate()` contains the user's DID and a UCAN token with the requested permissions. You can use this session to interact with the user's Vault.
```javascript
// Example: Get the user's balance
const balance = await session.vault.getAccountBalance();
console.log("User balance:", balance);
```
</Step>
</Steps>
## Backend Wallet Connections
For backend services, you can use the Sonr SDK to interact with user Vaults on behalf of your application.
<Steps>
<Step>
### 1. Service Registration
Your backend service must be registered on the Sonr network. This provides your service with its own DID and allows it to request permissions from users.
{/* Service registration documentation is referenced but not yet available in the docs structure */}
</Step>
<Step>
### 2. Requesting Permissions
Your service can request permissions from users by generating a UCAN request. This is typically done through a user-facing application.
```typescript
// Example: Requesting permission to read a user's profile
const ucanRequest = await sonr.ucan.request({
audience: "did:sonr:your-service-did",
resource: `dwn://user-did/profile/read`,
});
// Present this request to the user to be signed by their Vault
```
</Step>
<Step>
### 3. Using Delegated Capabilities
Once a user has approved your request, you will receive a delegated UCAN token. You can use this token to perform actions on the user's behalf.
```go
// Example: Using a delegated UCAN in a Go backend
import "github.com/sonr-io/sonr/x/sonr/pkgs/sdk"
func GetUserProfile(userDID string, delegatedUcan string) (*Profile, error) {
sonr, _ := sdk.NewSonr(rpcEndpoint, "")
// Use the delegated UCAN to access the user's profile
profile, err := sonr.GetUserProfile(userDID, delegatedUcan)
if err != nil {
return nil, err
}
return profile, nil
}
```
</Step>
</Steps>
## Managing Connections
### Checking Connection Status
You can check the current connection status at any time:
```javascript
const session = await sonr.getSession();
if (session) {
console.log("User is connected:", session.did);
} else {
console.log("User is not connected.");
}
```
### Disconnecting
To disconnect a wallet, simply clear the session from your application's state:
```javascript
await sonr.logout();
console.log("User has been disconnected.");
```
This will revoke the current session's UCAN token, but it will not remove any permissions the user has granted to your service.
## Security Considerations
- **UCAN Scopes**: Always request the minimum permissions necessary for your application to function.
- **Token Storage**: Securely store delegated UCAN tokens on your backend. Never expose them on the client-side.
- **Revocation**: Your application should handle UCAN revocations gracefully.
## Next Steps
- [Sending Payments](/highway/wallets/sending-payments)
- [Understanding UCANs](/blockchain/modules/svc/ucan)
- [Explore DWN Architecture](/blockchain/modules/dwn/)
+254
View File
@@ -0,0 +1,254 @@
---
title: Build with Sonr
description: The peer-to-peer identity and asset management system that makes Web3 as easy as Web2 through DID documents, WebAuthn, and IPFS—providing users with secure, portable decentralized identity
sidebarTitle: "Installation"
icon: "download"
---
## Summary
Sonr is a Cosmos SDK blockchain that simplifies Web3 through **Decentralized Identity (DIDs)**, **passwordless authentication (WebAuthn)**, and **user-controlled agents (Vaults)**. Developers integrate crypto features using standard web technologies. Validators secure a network bridging Web2 and Web3. Users gain digital sovereignty without complexity.
## What is Sonr?
Sonr transforms blockchain interaction through four innovations:
1. **W3C-compliant DIDs** replace wallet addresses
2. **WebAuthn** eliminates seed phrases
3. **Personal Vaults** automate blockchain operations
4. **UCAN permissions** prevent unlimited approvals
These components create a system where users onboard in 30 seconds using biometrics, developers add crypto features with HTML forms, and validators earn rewards securing digital sovereignty.
## Why Sonr Matters
### Current Problems
Traditional Web3 forces users to:
- Manage 24-word seed phrases
- Install browser extensions
- Understand gas fees
- Navigate multiple wallets
One mistake loses everything.
### Sonr's Solution
Sonr provides:
- **30-second onboarding** with Face ID or fingerprint
- **No seed phrases** through WebAuthn security
- **No gas fees** for account creation
- **Universal compatibility** across all devices
- **Automatic recovery** via social and biometric methods
## Core Architecture
<CardGroup>
<Card title="Decentralized Identity (DID)" href="/blockchain/modules/did/">
W3C-compliant identity system using WebAuthn for passwordless authentication
</Card>
<Card title="Decentralized Web Nodes (DWN)" href="/blockchain/modules/dwn/">
Personal Vaults acting as user-controlled agents for blockchain interactions
</Card>
<Card title="UCAN Authorization" href="/blockchain/modules/svc/ucan">
Capability-based permissions replacing dangerous unlimited approve patterns
</Card>
<Card title="Service Registry" href="/blockchain/modules/svc/">
Stake-based trust system for service discovery and DNS verification
</Card>
</CardGroup>
## For Developers
### Integration Benefits
Sonr enables crypto features without blockchain knowledge:
- **Use existing skills**: HTML, CSS, JavaScript
- **Zero dependencies**: No SDKs or wallet libraries
- **Progressive enhancement**: Start simple, add features
- **Enterprise ready**: Integrates with existing auth systems
### Simple Payment Example
Transform any HTML form into a crypto payment interface:
```html
<form hx-post="/api/sonr/payment" hx-target="#result">
<input type="email" name="recipient" placeholder="alice@sonr.id" />
<input type="number" name="amount" placeholder="25.00" />
<select name="currency">
<option value="USDC">USDC</option>
<option value="ATOM">ATOM</option>
</select>
<button type="submit">Send Payment</button>
</form>
```
Users approve with biometrics. Vaults handle transactions. No wallet connections required.
### Developer Resources
<CardGroup>
<Card title="Browser Integration" href="/quickstart/browser">
Web browser integration patterns and examples
</Card>
<Card title="Highway Wallet" href="/highway/">
Highway system powering user sovereignty
</Card>
<Card title="Payment Integration" href="/highway/wallets/sending-payments">
Payment integration guide
</Card>
<Card title="Blockchain Modules" href="/blockchain/">
Core blockchain modules and architecture
</Card>
</CardGroup>
## For Validators
### Network Components
Validators secure four critical systems:
<CardGroup>
<Card title="Blockchain Core" href="/blockchain/">
Cosmos SDK with IBC for cross-chain operations
</Card>
<Card title="Token Economics" href="/blockchain/token/">
Tokenomics, staking, and governance
</Card>
<Card title="Highway Proxy" href="/highway/">
HTTP bridge supporting WebAuthn authentication
</Card>
<Card title="Validator Setup" href="/quickstart/validators">
Validator node setup and operations
</Card>
</CardGroup>
### Validator Operations
Validators perform five key functions:
1. **Validate identities**: Process DID operations and WebAuthn credentials
2. **Execute Vaults**: Run capability delegations and revocations
3. **Bridge chains**: Process IBC and InterchainAccount transactions
4. **Verify services**: Validate DNS ownership and registrations
5. **Coordinate MPC**: Participate in multi-party key management
### Economic Incentives
- **Block rewards**: Earn from transaction fees and inflation
- **Service fees**: Share revenue from registrations
- **MEV protection**: Built-in maximal extractable value prevention
- **Sustainable model**: Long-term network health design
## Key Concepts
### Identity Management
<CardGroup>
<Card title="Identity System" href="/blockchain/modules/did/">
W3C DIDs with WebAuthn for digital sovereignty
</Card>
<Card title="DID Module" href="/blockchain/modules/did/">
Blockchain implementation of identity management
</Card>
</CardGroup>
### Data Sovereignty
<CardGroup>
<Card title="DWN Module" href="/blockchain/modules/dwn/">
Personal Vaults for user-controlled data and agents
</Card>
<Card title="Blockchain Network" href="/blockchain/network">
Network architecture and specifications
</Card>
</CardGroup>
### Authorization System
<CardGroup>
<Card title="UCAN Module" href="/blockchain/modules/svc/ucan">
Capability-based permissions for secure delegation
</Card>
<Card title="Service Module" href="/blockchain/modules/svc/">
Registration, verification, and trust management
</Card>
</CardGroup>
### Cross-Chain Features
<CardGroup>
<Card title="Blockchain Network" href="/blockchain/network">
Network architecture and cross-chain features
</Card>
<Card title="Payment Handler" href="/highway/wallets/sending-payments">
W3C API for seamless crypto payments
</Card>
</CardGroup>
## Getting Started
### Developers
Build Web3 applications without blockchain complexity:
<CardGroup>
<Card title="Quick Start" href="/quickstart/">
Create your first Sonr application in 10 minutes
</Card>
<Card title="Browser Integration" href="/quickstart/browser">
Real-world integration patterns for web applications
</Card>
<Card title="CLI Tools" href="/quickstart/cli">
Command line tools and utilities
</Card>
</CardGroup>
### Validators
Secure the future of digital sovereignty:
<CardGroup>
<Card title="Node Setup" href="/quickstart/validators">
Complete validator installation guide
</Card>
<Card title="Token Economics" href="/blockchain/token/">
Token distribution, staking, and governance
</Card>
<Card title="Security" href="/reference/security/">
Security practices and compliance
</Card>
</CardGroup>
### Users
Experience true digital ownership:
<CardGroup>
<Card title="Create Identity" href="/blockchain/modules/did/onboarding">
30-second setup with biometric authentication
</Card>
<Card title="Use Your Vault" href="/blockchain/modules/dwn/">
Master your personal Web3 agent
</Card>
<Card title="Security Guide" href="/reference/security/">
Privacy and sovereignty protection
</Card>
</CardGroup>
## Next Steps
<Note title="Ready to Build?" type="success">
**Developers**: Start with the [Quick Start Guide](/quickstart/) to build your first Sonr application.
**Validators**: Follow the [Node Setup Guide](/quickstart/validators) to join the network.
**Users**: [Create your identity](/blockchain/modules/did/onboarding) in under 30 seconds.
</Note>
Explore the concepts above or dive into specific topics using the navigation menu. Join us in building the sovereign internet where identity belongs to individuals, not platforms.
+158
View File
@@ -0,0 +1,158 @@
---
title: Sending Payments
description: A guide for sending payments and transactions on the Sonr blockchain network
icon: "credit-card"
---
Sending payments on the Sonr network is designed to be simple and secure, whether you are building a user-facing application or a backend service. This guide covers the different ways to initiate and manage payments.
## The Sonr Payment Model
Sonr payments are built on a capability-based system using UCANs. This means that instead of signing every transaction, users delegate permission to their Vault to execute payments within predefined limits.
<CardGroup>
<Card title="Programmable Payments" href="/blockchain/modules/svc/ucan">
Automate recurring payments and subscriptions with UCANs.
</Card>
<Card title="Cross-Chain Transfers" href="/blockchain/network">
Send assets to other blockchains seamlessly through IBC.
</Card>
<Card title="Token Economics" href="/blockchain/token/">
Learn about token distribution and transaction fees.
</Card>
</CardGroup>
## Sending a Simple Transfer
This example demonstrates how to send a simple transfer from a user's Vault in a browser application.
<Steps>
<Step>
### 1. Authenticate the User
First, ensure the user is authenticated and you have a valid session.
```javascript
import { Sonr } from "@sonr/sdk";
const sonr = new Sonr({ httpUrl: "http://localhost:1317" });
const session = await sonr.authenticate();
```
</Step>
<Step>
### 2. Request Payment Capability
Before sending a payment, your application must request the necessary permission from the user.
```javascript
const paymentCapability = await session.vault.requestCapability({
action: "bank/send",
constraints: {
maxAmount: "10000000usnr", // 10 SNR
to: "snr1..._recipient_address_...",
},
});
if (!paymentCapability.approved) {
throw new Error("Payment not authorized by user");
}
```
</Step>
<Step>
### 3. Execute the Payment
Once you have the capability, you can execute the payment.
```javascript
const result = await session.vault.send({
to: "snr1..._recipient_address_...",
amount: "1000000usnr", // 1 SNR
ucan: paymentCapability.ucan, // Provide the authorized UCAN
});
console.log(`Payment successful! TxHash: ${result.txhash}`);
```
</Step>
</Steps>
## Backend Payments
For backend services, payments can be initiated using a delegated UCAN.
<Steps>
<Step>
### 1. Obtain a Delegated UCAN
Your service must first obtain a delegated UCAN from the user that grants permission to send payments on their behalf.
</Step>
<Step>
### 2. Use the Go SDK to Send
Your Go backend can use the delegated UCAN to send a payment.
```go
package main
import (
"context"
"fmt"
"github.com/sonr-io/sonr/x/sonr/pkgs/sdk"
)
func SendPaymentOnBehalfOfUser(userDID, recipientAddress, amount, delegatedUcan string) error {
sonr, _ := sdk.NewSonr(rpcEndpoint, "")
// The SDK will automatically use the UCAN for authorization
result, err := sonr.SendFrom(userDID, recipientAddress, amount, delegatedUcan)
if err != nil {
return err
}
fmt.Printf("Payment sent! TxHash: %s\n", result.TxHash)
return nil
}
```
</Step>
</Steps>
## Cross-Chain Payments
Sonr supports cross-chain payments through the Inter-Blockchain Communication (IBC) protocol.
### Sending to another IBC-enabled chain
```javascript
const result = await session.vault.send({
to: "osmo1..._recipient_address_...", // An Osmosis address
amount: "1000000usdc", // 1 USDC
via: "ibc/transfer/channel-0", // The IBC channel to use
});
console.log(`Cross-chain payment successful! TxHash: ${result.txhash}`);
```
## Querying Payment History
You can query a user's payment history from their Vault.
```javascript
const history = await session.vault.getPaymentHistory({ limit: 10 });
console.log("Payment History:", history.records);
```
## Next Steps
- [Explore the UCAN authorization model](/blockchain/modules/svc/ucan)
- [Learn about blockchain modules](/blockchain/)
- [See the API Reference](/reference/)
@@ -0,0 +1,191 @@
---
title: "Migrating from Centralized to Decentralized Authentication"
description: "A comprehensive guide to migrating from centralized 8787 endpoints to decentralized OIDC authentication with WebAuthn"
sidebarTitle: "Decentralized Authentication"
icon: "key"
---
# Migrating from Centralized to Decentralized Authentication
## Overview
Sonr is transitioning from a centralized authentication model using 8787 endpoints to a fully decentralized, privacy-preserving authentication system leveraging OpenID Connect (OIDC), Self-Issued OpenID Provider (SIOP), and WebAuthn technologies.
### Key Improvements
- **Decentralization**: Move from centralized identity management to self-sovereign identity
- **WebAuthn Integration**: Hardware-backed, phishing-resistance authentication
- **Gasless Onboarding**: Zero-cost user registration and transactions
- **Automatic Vault Creation**: Seamless user experience with instant identity setup
- **Enhanced Privacy**: DID-based authentication with verifiable presentations
## Architecture Comparison
### Old Architecture: Centralized 8787 Endpoints
- Centralized authentication server
- Fixed credential storage
- Limited authentication methods
- Higher security risks
### New Architecture: Decentralized OIDC Provider
```mermaid
graph TD
A[User Device] --> B{WebAuthn Registration}
B --> |Credential Generation| C[Blockchain Bridge]
C --> |Broadcast Credential| D[Sonr Blockchain]
D --> |Create DID| E[User's Decentralized Identity]
E --> |SIOP Flow| F[OIDC Provider]
F --> |Verifiable Presentation| G[Service Provider]
```
## Migration Steps
### 1. Prerequisites
- Go 1.24.1+
- Cosmos SDK v0.50.14
- WebAuthn-compatible browser/device
- Updated Sonr SDK
### 2. Configuration Changes
#### Environment Variables
<CodeGroup>
```bash title="Old Configuration"
# Centralized auth endpoints
AUTH_ENDPOINT=https://8787.sonr.io/auth
AUTH_CLIENT_ID=legacy-client-id
```
```bash title="New Configuration"
# Decentralized OIDC configuration
OIDC_PROVIDER_URL=https://oidc.sonr.network
WEBAUTHN_ORIGIN=https://your-app.com
DID_RESOLVER_URL=https://did.sonr.network
```
</CodeGroup>
### 3. Endpoint Migration
| Old Endpoint | New Endpoint | Changes |
| ---------------- | -------------------- | ----------------------- |
| `/auth/login` | `/oidc/authorize` | OIDC authorization flow |
| `/auth/register` | `/webauthn/register` | WebAuthn registration |
| `/auth/token` | `/oidc/token` | Token issuance via SIOP |
### 4. API Changes
#### Request Format
<CodeGroup>
```json title="Legacy Request"
{
"username": "user@example.com",
"password": "legacy-password"
}
```
```json title="New WebAuthn Request"
{
"challenge": "base64-encoded-challenge",
"attestation": {
"type": "public-key",
"id": "credential-id",
"rawId": "base64-encoded-raw-credential",
"response": {
"clientDataJSON": "...",
"attestationObject": "..."
}
}
}
```
</CodeGroup>
### 5. WebAuthn Integration
#### Registration Flow
1. Generate registration challenge
2. Create WebAuthn credential
3. Broadcast credential to blockchain
4. Automatically create user vault
5. Issue decentralized identifier (DID)
#### Code Example
```go title="WebAuthn Registration Handler"
func (s *Server) HandleWebAuthnRegistration(w http.ResponseWriter, r *http.Request) {
// 1. Validate WebAuthn attestation
credential, err := s.webAuthnService.VerifyRegistration(attestationData)
// 2. Broadcast to blockchain
didDoc, err := s.blockchainBridge.CreateDID(credential)
// 3. Create user vault
vault, err := s.vaultService.CreateVault(didDoc)
// 4. Issue OIDC token
token := s.oidcService.IssueToken(didDoc)
}
```
### 6. SIOP (Self-Issued OpenID Provider)
#### Key Concepts
- Verifiable Presentations
- Decentralized Identifiers (DIDs)
- User-controlled authentication
### 7. Error Handling
#### Migration Errors
| Error Code | Description | Mitigation |
| ------------------------ | ---------------------- | -------------------- |
| `AUTH_LEGACY_DEPRECATED` | Legacy auth method | Upgrade client |
| `WEBAUTHN_UNSUPPORTED` | Device incompatibility | Use alternative auth |
| `DID_RESOLUTION_FAILED` | Identity verification | Retry registration |
### 8. Testing Migration
```bash
# Validate WebAuthn registration
sonr webauthn test-registration
# Verify OIDC provider
sonr oidc validate-provider
# Check DID resolution
sonr did resolve did:sonr:example
```
### 9. Breaking Changes
- Legacy password authentication removed
- Token format changed to JWT with DID claims
- New client libraries required
- WebAuthn mandatory for registration
## Rollback Procedure
If issues arise:
1. Maintain legacy user mappings
2. Provide fallback authentication
3. Gradual, opt-in migration
## Conclusion
This migration represents a significant leap in authentication security and user privacy. By adopting WebAuthn, SIOP, and blockchain-backed identities, we're creating a more robust, user-controlled authentication ecosystem.
## Support
- [Sonr Developer Docs](/docs)
- [WebAuthn Specification](https://www.w3.org/TR/webauthn-2/)
- [OIDC Community](https://openid.net/developers/specs/)
+233
View File
@@ -0,0 +1,233 @@
---
title: "Motor WASM Service Worker Usage"
description: "Comprehensive guide to using the Motor WASM service worker for secure browser-based DWN and Wallet APIs"
icon: "microchip"
sidebarTitle: "Motor WASM"
---
<Info>
Motor is a WebAssembly service worker providing secure, client-side cryptographic operations and decentralized web node (DWN) capabilities.
</Info>
## Overview
Motor is a WebAssembly-powered service worker that enables:
- Secure client-side cryptographic operations
- Decentralized Web Node (DWN) APIs
- Cross-platform support for browsers and Node.js
<CardGroup cols={2}>
<Card title="DWN API" icon="database">
Create, read, update, and delete records with optional encryption
</Card>
<Card title="Wallet API" icon="wallet" color="#22863a">
UCAN token generation, digital signatures, and verification
</Card>
</CardGroup>
## Prerequisites
<Check>
- Node.js 20+ and pnpm
- Browser with Service Worker support
- HTTP/HTTPS server for WASM files
</Check>
## Installation
<CodeGroup>
```bash npm
npm install @sonr.io/es
```
```bash pnpm
pnpm add @sonr.io/es
```
```bash yarn
yarn add @sonr.io/es
```
</CodeGroup>
## Usage Examples
### Basic Initialization
<Tabs>
<Tab title="Browser Auto-Detection">
```typescript
import { createMotorPlugin } from '@sonr.io/es/client/motor';
// Automatically detects browser vs Node.js environment
const plugin = await createMotorPlugin();
// Get issuer DID
const issuer = await plugin.getIssuerDID();
console.log('Issuer DID:', issuer.issuer_did);
```
</Tab>
<Tab title="Browser Service Worker">
```typescript
import { createMotorPluginForBrowser } from '@sonr.io/es/client/motor';
const plugin = await createMotorPluginForBrowser('/motor-worker', {
auto_register_worker: true,
worker_scope: '/',
debug: true,
});
// Create UCAN origin token
const tokenResponse = await plugin.newOriginToken({
audience_did: 'did:sonr:audience123',
attenuations: [{ can: ['sign', 'verify'], with: 'vault://my-vault' }],
});
```
</Tab>
<Tab title="Node.js">
```typescript
import { createMotorPluginForNode } from '@sonr.io/es/client/motor';
const plugin = await createMotorPluginForNode('http://localhost:8080', {
max_retries: 3,
retry_delay: 1000,
timeout: 5000,
debug: true,
});
```
</Tab>
</Tabs>
### Record Operations
<CodeGroup>
```typescript DWN Create
const createResult = await plugin.createRecord({
schema: 'https://schema.org/Person',
data: JSON.stringify({ name: 'Alice Smith' }),
is_encrypted: false,
});
```
```typescript DWN Read
const record = await plugin.readRecord({
record_id: createResult.record_id,
});
```
```typescript DWN Update
await plugin.updateRecord({
record_id: createResult.record_id,
data: JSON.stringify({ name: 'Alice Johnson' }),
});
```
```typescript DWN Delete
const deleteResult = await plugin.deleteRecord({
record_id: createResult.record_id,
});
```
</CodeGroup>
### Encrypted Records
```typescript
const sensitiveData = {
ssn: '123-45-6789',
medical_record: 'Confidential information',
};
const encryptedRecord = await plugin.createRecord({
schema: 'https://schema.org/MedicalRecord',
data: JSON.stringify(sensitiveData),
is_encrypted: true, // Enable encryption
});
// Automatic decryption on read
const decryptedRecord = await plugin.readRecord({
record_id: encryptedRecord.record_id,
});
```
## Deployment
<Tabs>
<Tab title="Development">
```bash
cd dist/wasm
python3 -m http.server 8080
# Access at http://localhost:8080/test.html
```
</Tab>
<Tab title="Production (Nginx)">
```nginx
location /motor/ {
alias /path/to/dist/wasm/;
# CORS and MIME types
add_header 'Access-Control-Allow-Origin' '*';
location ~ \.wasm$ {
add_header 'Content-Type' 'application/wasm';
}
}
```
</Tab>
<Tab title="CDN">
```html
<script src="https://cdn.example.com/motor/wasm_exec.js"></script>
<script>
navigator.serviceWorker.register(
'https://cdn.example.com/motor/motr-sw.js'
);
</script>
```
</Tab>
</Tabs>
## Troubleshooting
<Accordion title="Common Issues">
<Accordion.Panel title="Service Worker Not Registering">
- Ensure HTTPS or localhost
- Check browser console
- Verify service worker file path
</Accordion.Panel>
<Accordion.Panel title="WASM Module Loading">
- Check MIME type: `application/wasm`
- Verify CORS headers
- Match `wasm_exec.js` with Go version
</Accordion.Panel>
</Accordion>
## Browser Compatibility
| Browser | Minimum Version | Support |
|---------|----------------|---------|
| Chrome | 89+ | Full |
| Firefox | 89+ | Full |
| Safari | 15.4+ | Good |
| Edge | 89+ | Full |
<Warning>
Requires HTTPS or localhost for service worker functionality
</Warning>
## Performance Tips
<Tip>
- Use TinyGo for smaller WASM binaries
- Enable browser caching
- Lazy load Motor plugin
- Limit service worker scope
</Tip>
## Support
- **GitHub**: [Issues](https://github.com/sonr-io/sonr/issues)
- **Docs**: [Motor WASM Documentation](https://docs.sonr.io/motor-wasm)
- **Discord**: [Sonr Community](https://discord.gg/sonr)
+279
View File
@@ -0,0 +1,279 @@
---
title: Validator Node Onboarding
description: Complete guide for becoming a Sonr blockchain validator from setup to operations
icon: "boxes"
sidebarTitle: Become a Validator
---
## Overview
Sonr is a Cosmos SDK-based blockchain focused on decentralized identity and asset management. This guide provides comprehensive information for validators interested in securing the Sonr network and participating in its specialized identity infrastructure ecosystem.
<Note>
Sonr is currently in testnet/development phase. While there's no confirmed
mainnet launch date, early participation in testnet operations is highly
recommended for prospective validators.
</Note>
## Network Positioning
Sonr differentiates itself within the Cosmos ecosystem through:
- **Decentralized Identity Focus**: Implementing W3C DID standards and WebAuthn integration
- **Highway Architecture**: Specialized node infrastructure for identity services
- **Fast Wallet Generation**: 600ms wallet creation with IPFS storage capabilities
- **Developer Tools**: React SDKs and identity-focused APIs
## Hardware Requirements
Professional validator operations require substantial infrastructure investment to ensure network security and reliability.
### Essential Specifications
<Card title="CPU">
**Minimum**: 4 cores x86 processor **Recommended**: 8+ cores for production
</Card>
<Card title="RAM">
**Minimum**: 16GB with NVMe swap **Recommended**: 32GB+ for optimal
performance
</Card>
<Card title="Storage">
**Required**: 1TB+ NVMe SSD **Note**: Regular SSDs often insufficient for
I/O demands
</Card>
<Card title="Network">
**Minimum**: 100Mbps dedicated bandwidth **Usage**: Multi-gigabyte daily
traffic expected
</Card>
### Infrastructure Investment
- **Initial Setup**: Professional-grade hardware required for reliable operations
- **Monthly Operating**: Tier 3+ datacenter colocation recommended for optimal performance
- **Redundancy**: Full backup server with identical specifications required
## Quick Setup with NPX
Sonr provides an NPX-based tool to streamline validator deployment:
```bash
npx @sonr/validator-setup my-validator --chain=sonr-testnet-1
```
The interactive wizard guides you through:
<Steps>
<Step>
### Network Configuration Select testnet or mainnet and configure chain
parameters
</Step>
<Step>
### Hardware Verification Automated check of system requirements and
recommendations
</Step>
<Step>### Key Generation Secure key creation with HSM support options</Step>
<Step>
### Sentry Architecture Deploy protective sentry node infrastructure
</Step>
<Step>
### Monitoring Setup Install Prometheus + Grafana monitoring stack
</Step>
<Step>
### Security Hardening Configure firewalls and security best practices
</Step>
</Steps>
## Network Parameters
### Validator Network Structure
For a 50-validator network with 1 billion token supply:
#### Early Network Phase (30% staking ratio)
- **Inflation**: 15% (bootstrap incentives)
- **Validator Participation**: Commission-based earnings structure
- **Delegator Rewards**: High early participation incentives
#### Bootstrap Phase (50% staking ratio)
- **Inflation**: 12% (balanced growth)
- **Validator Participation**: Balanced commission structure
- **Delegator Rewards**: Sustainable growth incentives
#### Mature Network (67% staking ratio)
- **Inflation**: 7% (long-term stability)
- **Validator Participation**: Stable commission structure
- **Delegator Rewards**: Long-term participation incentives
### Recommended Parameters
- **Minimum validator stake**: 1,000,000 SNR (0.1% of supply)
- **Optimal self-bond**: 2,000,000 SNR (0.2% of supply)
- **Commission range**: 5-15% (5% mandatory minimum)
- **Inflation range**: 5-18% with 8% target at 65% staking
- **Unbonding period**: 21 days standard
## Operational Considerations
### Infrastructure Requirements
Validators should ensure adequate infrastructure to support reliable network participation.
### Reward Sources
- **Block Rewards**: Inflation-based token issuance for network security
- **Transaction Fees**: Gas fees and proposer bonuses from network activity
- **Additional Rewards**: ICS rewards, cross-chain fees, and ecosystem participation
## Security Architecture
### Sentry Node Design
Implement a multi-layered security approach:
```
Internet → Sentry Nodes (3-5) → Private Network → Validator Node
```
### Critical Security Implementations
<Card title="Key Management">
- Hardware Security Modules (HSM) - Tendermint Key Management System (TMKMS)
- Remote signing capabilities
</Card>
<Card title="Network Security">
- Geographic distribution across datacenters - Automated double-sign
prevention - Comprehensive monitoring and alerting
</Card>
<Card title="Operational Security">
- 99.9%+ uptime requirements - Encrypted backups across locations - Strict
access controls and audits
</Card>
### Key Types
1. **Consensus Key**: Hot key for block signing (ed25519)
2. **Operator Key**: Cold storage for validator transactions (secp256k1)
3. **Node Key**: P2P network identification
## Implementation Roadmap
### Phase 1: Testnet Participation (Months 1-3)
<Note type="warning">
Begin with testnet operations to gain experience without operational risk.
</Note>
- Hardware procurement and datacenter setup
- Team training on Cosmos SDK operations
- Security procedure development
- Community engagement and reputation building
### Phase 2: Infrastructure Preparation (Month 4)
- Deploy production hardware in Tier 3+ datacenters
- Implement sentry node architecture across regions
- Configure monitoring and alerting systems
- Establish 24/7 operational procedures
### Phase 3: Mainnet Genesis (Month 5+)
- Participate in genesis ceremony
- Self-bond required SNR tokens (1-2M recommended)
- Configure optimal commission rates (start at 5-7%)
- Launch validator with foundation delegation support
### Phase 4: Operational Excellence (Ongoing)
- Maintain 99.9%+ uptime through redundant systems
- Actively participate in governance proposals
- Provide regular updates to delegators
- Contribute to ecosystem development
## Foundation Support Programs
### Delegation Program
Sonr implements a foundation delegation program allocating 10-15% of total supply:
- **Coverage**: 30-35 validators (60-70% of active set)
- **Requirements**: 3-month testnet participation
- **Terms**: 6-12 month delegation periods
- **Renewal**: Performance-based criteria
- **Focus**: Geographic distribution and community contributions
### Testnet Incentives
- **Monthly Rewards**: Testnet participation incentives for active validators
- **Mainnet Slots**: Top performers receive guaranteed mainnet positions
- **Foundation Delegations**: 6-month delegations of 2M tokens for top testnet validators
## Monitoring and Operations
### Prometheus Metrics
- System metrics (CPU, RAM, disk, network)
- Tendermint consensus metrics (height, voting power, peer count)
- Custom application metrics (missed blocks, proposal statistics)
### Critical Alerts
- Low peer count (less than 5 peers)
- High block time intervals
- Resource utilization warnings
- Disk space projections
### Grafana Dashboards
- Real-time performance monitoring
- Historical trend analysis
- Multi-validator comparison views
## Risk Management
### Technical Risks
- **Double-signing prevention**: Proper key management and TMKMS
- **State corruption recovery**: Automated backup systems
- **Network partitions**: Geographic distribution strategies
- **Upgrade failures**: Staging environment testing
### Operational Risks
- **Network participation**: Maintain consistent validator performance
- **Delegation concentration**: Limits on single delegator exposure
- **Commission optimization**: Community-competitive rates
- **Infrastructure management**: Efficient operational procedures
## Future Opportunities
As Sonr matures, validators can explore additional network services:
- **Relayer Operations**: IBC connection services
- **RPC Endpoints**: Developer infrastructure services
- **Archive Nodes**: Historical data provision
- **Identity Services**: Custom solutions leveraging Sonr infrastructure
- **Interchain Security**: Consumer chain participation
## Getting Started
<Card title="Join Testnet" href="/guides/validators/testnet">
Start with testnet participation to gain operational experience
</Card>
<Card title="Hardware Setup" href="/guides/validators/setup">
Detailed hardware and infrastructure deployment guide
</Card>
<Card title="Security Guide" href="/guides/validators/security">
Comprehensive security implementation and best practices
</Card>
<Card title="Monitoring" href="/guides/validators/monitoring">
Setup monitoring and alerting systems for your validator
</Card>
<Note type="success">
Sonr presents a compelling opportunity for validators seeking exposure to the
decentralized identity market within the Cosmos ecosystem. Early preparation
and professional operations are key to success.
</Note>
+172
View File
@@ -0,0 +1,172 @@
---
title: "PDK Environment Configuration"
description: "Comprehensive guide to configuring the Pluggable Development Kit (PDK) for Sonr plugins"
icon: "gear"
---
# PDK Environment Configuration
The Pluggable Development Kit (PDK) provides a flexible configuration system for managing plugin environments, MPC enclaves, and runtime settings.
## Environment Variables
### Core PDK Variables
| Variable | Type | Description | Default |
| -------------- | -------- | --------------------------------- | ------------------ |
| `chain_id` | `string` | Target blockchain network | `"sonr-testnet-1"` |
| `enclave` | `object` | MPC enclave configuration | `{}` |
| `vault_config` | `object` | Vault and key management settings | `{}` |
| `log_level` | `string` | Logging verbosity | `"info"` |
## Enclave Configuration
### Basic Enclave Setup
```json
{
"enclave": {
"id": "unique-enclave-identifier",
"key_type": "secp256k1",
"threshold": 2,
"participants": [
{ "id": "participant1", "public_key": "..." },
{ "id": "participant2", "public_key": "..." }
]
}
}
```
### Advanced Enclave Parameters
```json
{
"enclave": {
"security_level": "high",
"attestation_mode": "remote",
"key_rotation_interval": "1h",
"backup_strategy": "distributed"
}
}
```
## Vault Configuration
### Key Management Settings
```json
{
"vault_config": {
"storage_backend": "ipfs",
"encryption": {
"algorithm": "aes-256-gcm",
"key_derivation": "pbkdf2"
},
"access_control": {
"mode": "role-based",
"default_role": "viewer"
}
}
}
```
## Logging Configuration
```json
{
"log_level": "debug",
"log_format": "json",
"log_outputs": [
{ "type": "stdout" },
{ "type": "file", "path": "/var/log/sonr/pdk.log" }
]
}
```
## Performance Tuning
```json
{
"performance": {
"max_concurrent_tasks": 10,
"task_timeout": "5m",
"memory_limit": "512MB",
"cpu_allocation": 2
}
}
```
## Security Hardening
```json
{
"security": {
"require_mfa": true,
"allowed_key_types": ["secp256k1", "ed25519"],
"audit_logging": true,
"rate_limiting": {
"max_requests_per_minute": 100
}
}
}
```
## Plugin-Specific Configuration
```json
{
"plugins": {
"motor": {
"mpc_mode": "distributed",
"token_generation_rate_limit": 10
},
"did": {
"supported_methods": ["did:key", "did:sonr"]
}
}
}
```
## Environment Loading Precedence
1. Environment Variables
2. Configuration Files
3. Default Values
## Best Practices
- Use environment-specific configurations
- Implement strict access controls
- Rotate encryption keys regularly
- Monitor and log configuration changes
- Use minimal privilege principles
## Example Configuration Loading
```go
func loadPDKConfiguration() (*PDKConfig, error) {
// Load from environment variables
config := &PDKConfig{}
// Override with config file if exists
configFile, err := ioutil.ReadFile("/etc/sonr/pdk.json")
if err == nil {
json.Unmarshal(configFile, config)
}
return config, nil
}
```
## Troubleshooting
- Check `log_level` for detailed diagnostics
- Validate JSON configuration syntax
- Verify key and enclave configurations
## Advanced Topics
For more complex PDK configurations, refer to:
- [DWN Plugin Documentation](/blockchain/modules/dwn/plugin)
- [DWN Architecture Overview](/blockchain/modules/dwn/architecture)
+7
View File
@@ -0,0 +1,7 @@
---
title: "Registering a Domain"
description: "Comprehensive guide to creating, validating, and managing User-Controlled Authorization Network (UCAN) tokens"
icon: "key"
---
+438
View File
@@ -0,0 +1,438 @@
---
title: "Sign in with Sonr: Developer Guide"
description: "OAuth 2.0 authentication for decentralized applications with UCAN capabilities"
sidebarTitle: "Sign in with Sonr"
icon: "key"
---
<Info>
This guide covers OAuth 2.0 authentication for decentralized applications using Sonr's advanced Web3 capabilities.
</Info>
## Overview
Sign in with Sonr provides OAuth 2.0 authentication for decentralized applications, combining traditional OAuth flows with Web3 capabilities through UCAN (User Controlled Authorization Networks) delegation.
<CardGroup cols={2}>
<Card title="OAuth 2.0 + OIDC" icon="lock">
Industry-standard authentication with OpenID Connect
</Card>
<Card title="WebAuthn Support" icon="fingerprint">
Passwordless authentication with hardware security
</Card>
<Card title="UCAN Capabilities" icon="network">
Fine-grained permission delegation for Web3
</Card>
<Card title="Decentralized Identity" icon="id-card">
W3C DID-based identity management
</Card>
</CardGroup>
## Quick Start
### Installation
<CodeGroup>
```bash npm
npm install @sonr.io/ui
```
```bash pnpm
pnpm add @sonr.io/ui
```
```bash yarn
yarn add @sonr.io/ui
```
</CodeGroup>
### Basic Implementation
<CodeGroup>
```tsx React
import { SignInWithSonr } from '@sonr.io/ui';
function App() {
return (
<SignInWithSonr
clientId="your-client-id"
redirectUri="http://localhost:3000/callback"
scopes={['openid', 'profile', 'vault:read']}
/>
);
}
```
</CodeGroup>
## Configuration
### OAuth Client Registration
<CodeGroup>
```typescript Configuration
const clientConfig = {
clientId: 'your-client-id',
clientSecret: 'your-client-secret', // Only for confidential clients
redirectUris: ['http://localhost:3000/callback'],
grantTypes: ['authorization_code', 'refresh_token'],
responseTypes: ['code'],
scopes: ['openid', 'profile', 'vault:read', 'vault:write'],
tokenEndpointAuthMethod: 'none', // For public clients
};
```
</CodeGroup>
### Environment Variables
<CodeGroup>
```env OAuth Endpoints
# OAuth Endpoints
NEXT_PUBLIC_SONR_CLIENT_ID=your-client-id
NEXT_PUBLIC_REDIRECT_URI=http://localhost:3000/callback
NEXT_PUBLIC_AUTH_URL=https://auth.sonr.io/oauth/authorize
NEXT_PUBLIC_TOKEN_URL=https://auth.sonr.io/oauth/token
NEXT_PUBLIC_USERINFO_URL=https://auth.sonr.io/oauth/userinfo
```
</CodeGroup>
## OAuth Scopes & UCAN Capabilities
<Tabs>
<Tab title="Standard Scopes">
<table>
<thead>
<tr>
<th>Scope</th>
<th>Description</th>
<th>UCAN Capabilities</th>
</tr>
</thead>
<tbody>
<tr>
<td>`openid`</td>
<td>OpenID Connect identity</td>
<td>Basic identity claims</td>
</tr>
<tr>
<td>`profile`</td>
<td>User profile information</td>
<td>Name, picture, metadata</td>
</tr>
<tr>
<td>`email`</td>
<td>Email address</td>
<td>Email and verification status</td>
</tr>
<tr>
<td>`offline_access`</td>
<td>Refresh token issuance</td>
<td>Long-lived access</td>
</tr>
</tbody>
</table>
</Tab>
<Tab title="Vault Scopes">
<table>
<thead>
<tr>
<th>Scope</th>
<th>Description</th>
<th>UCAN Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>`vault:read`</td>
<td>Read vault contents</td>
<td>`vault/read`, `vault/list`</td>
</tr>
<tr>
<td>`vault:write`</td>
<td>Modify vault contents</td>
<td>`vault/write`, `vault/create`, `vault/update`</td>
</tr>
<tr>
<td>`vault:delete`</td>
<td>Delete vault items</td>
<td>`vault/delete`</td>
</tr>
<tr>
<td>`vault:admin`</td>
<td>Full vault control</td>
<td>All vault actions</td>
</tr>
</tbody>
</table>
</Tab>
</Tabs>
## Integration Examples
<Tabs>
<Tab title="React Hooks">
<CodeGroup>
```tsx React Hooks
import { useSignInWithSonr } from '@sonr.io/ui';
function LoginComponent() {
const {
user,
token,
isAuthenticated,
isLoading,
signIn,
signOut,
refreshToken,
} = useSignInWithSonr({
clientId: 'your-client-id',
redirectUri: 'http://localhost:3000/callback',
scopes: ['openid', 'profile', 'vault:read'],
});
if (isLoading) return <div>Loading...</div>;
if (isAuthenticated) {
return (
<div>
<p>Welcome, {user.name}!</p>
<button onClick={signOut}>Sign Out</button>
</div>
);
}
return <button onClick={signIn}>Sign in with Sonr</button>;
}
```
</CodeGroup>
</Tab>
<Tab title="Next.js App Router">
<CodeGroup>
```tsx Next.js Layout
// app/layout.tsx
import { AuthProvider } from '@/components/AuthProvider';
export default function RootLayout({ children }) {
return (
<html>
<body>
<AuthProvider>{children}</AuthProvider>
</body>
</html>
);
}
```
```tsx Auth Provider
'use client';
import { createContext, useContext, useEffect, useState } from 'react';
import { OAuth2Client } from '@sonr.io/ui';
const AuthContext = createContext();
export function AuthProvider({ children }) {
const [client] = useState(() => new OAuth2Client({
clientId: process.env.NEXT_PUBLIC_SONR_CLIENT_ID,
redirectUri: process.env.NEXT_PUBLIC_REDIRECT_URI,
}));
// ... authentication logic
return (
<AuthContext.Provider value={{ client, /* ... */ }}>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => useContext(AuthContext);
```
</CodeGroup>
</Tab>
</Tabs>
## Advanced Features
### Custom Authorization
<CodeGroup>
```tsx Custom Authorization
<SignInWithSonr
clientId="your-client-id"
redirectUri="http://localhost:3000/callback"
authorizationUrl="https://auth.sonr.io/oauth/authorize"
state={generateRandomState()} // CSRF protection
scopes={['openid', 'profile', 'vault:admin']}
// Additional parameters
onAuthStart={() => console.log('Starting auth...')}
onAuthError={(error) => console.error('Auth failed:', error)}
/>
```
</CodeGroup>
### Token Management
<CodeGroup>
```typescript Token Management
const client = new OAuth2Client(config);
// Check authentication status
if (client.isAuthenticated()) {
// Get current access token
const accessToken = client.getAccessToken();
// Refresh token before expiry
const newToken = await client.refreshToken();
// Get user information
const userInfo = await client.getUserInfo();
// Revoke tokens on logout
await client.logout();
}
```
</CodeGroup>
## Security Considerations
<Warning>
Always implement robust security practices when integrating authentication.
</Warning>
### PKCE Implementation
<CodeGroup>
```typescript PKCE Configuration
const client = new OAuth2Client({
clientId: 'public-client',
pkce: true, // Enabled by default for public clients
});
```
</CodeGroup>
### State Parameter Prevention
<CodeGroup>
```typescript State Validation
// Generate random state
const state = crypto.randomUUID();
sessionStorage.setItem('oauth_state', state);
// Validate on callback
const returnedState = params.get('state');
const savedState = sessionStorage.getItem('oauth_state');
if (returnedState !== savedState) {
throw new Error('State mismatch - possible CSRF attack');
}
```
</CodeGroup>
## Troubleshooting
<Accordion title="Common Authentication Issues">
<AccordionItem title="CORS Errors">
- Ensure your redirect URI is whitelisted
- Check allowed origins in OAuth server config
</AccordionItem>
<AccordionItem title="Invalid Grant">
- Authorization code can only be used once
- Code expires after 10 minutes
- Verify redirect URI matches exactly
</AccordionItem>
<AccordionItem title="Token Expiry">
- Implement automatic refresh before expiry
- Handle refresh token rotation
</AccordionItem>
</Accordion>
<Note>
Enable debug mode for additional troubleshooting insights:
```typescript
const client = new OAuth2Client({
clientId: 'your-client-id',
debug: true, // Enable console logging
});
```
</Note>
## API Reference
### SignInWithSonr Props
```typescript
interface SignInWithSonrProps {
clientId: string;
redirectUri: string;
authorizationUrl?: string;
scopes?: string[];
state?: string;
variant?: 'default' | 'outline' | 'ghost' | 'dark';
size?: 'default' | 'sm' | 'lg';
isLoading?: boolean;
text?: string;
showLogo?: boolean;
onAuthStart?: () => void;
onAuthError?: (error: Error) => void;
}
```
## Resources
<CardGroup cols={2}>
<Card
title="OAuth 2.0 Specification"
href="https://datatracker.ietf.org/doc/html/rfc6749"
>
RFC 6749 - OAuth 2.0 Authorization Framework
</Card>
<Card
title="OpenID Connect"
href="https://openid.net/specs/openid-connect-core-1_0.html"
>
Core specification for identity layers
</Card>
<Card
title="UCAN Specification"
href="https://github.com/ucan-wg/spec"
>
User Controlled Authorization Networks
</Card>
<Card
title="WebAuthn"
href="https://www.w3.org/TR/webauthn/"
>
Web Authentication API specification
</Card>
</CardGroup>
## Support
<CardGroup cols={3}>
<Card
title="GitHub"
icon="github"
href="https://github.com/sonr-io/sonr"
>
Report issues or contribute
</Card>
<Card
title="Documentation"
icon="book"
href="https://sonr.dev"
>
Explore full documentation
</Card>
<Card
title="Discord"
icon="discord"
href="https://discord.gg/sonr"
>
Join our community
</Card>
</CardGroup>
+286
View File
@@ -0,0 +1,286 @@
---
title: "Sonr Vault Plugin with Dexie.js Persistence"
description: "Comprehensive guide to using the Sonr Vault Plugin with persistent storage and multi-account support"
sidebarTitle: "Vault Plugin Usage"
icon: "lock"
---
# Sonr Vault Plugin: Persistent Storage and Account Management
## Overview
The Sonr Vault Plugin provides a powerful, secure, and flexible way to manage cryptographic operations with persistent storage using Dexie.js and IndexedDB. This guide will walk you through the plugin's features, setup, and advanced usage patterns.
<Callout type="info">
**Key Features**
- 🔐 Account-based database separation
- 💾 Automatic token persistence
- 🔄 Cross-browser IndexedDB support
- ⚡ Backward compatibility
- 🧹 Automatic token and session cleanup
</Callout>
## Installation
Install the Sonr Vault Plugin in your project:
<CodeGroup>
```bash npm
npm install @sonr.io/es
```
```bash yarn
yarn add @sonr.io/es
```
```bash pnpm
pnpm add @sonr.io/es
```
</CodeGroup>
## Basic Usage
### Without Persistence (Default)
The vault plugin is designed to be backward compatible. By default, it operates without persistent storage:
```typescript
import { createVaultClient } from '@sonr.io/es/plugins/vault';
// Create a vault client without persistence
const vault = createVaultClient();
// Initialize the vault
await vault.initialize();
// Create tokens and perform operations as before
const token = await vault.newOriginToken({
audience_did: 'did:example:123',
});
```
### With Persistence Enabled
Enable persistent storage with a simple configuration:
```typescript
import { createVaultClient } from '@sonr.io/es/plugins/vault';
// Create a vault client with persistence
const vault = createVaultClient({
enablePersistence: true,
autoCleanup: true, // Automatically clean up expired tokens
cleanupInterval: 3600000 // Cleanup every hour (in milliseconds)
});
// Initialize with an account address for database separation
const accountAddress = 'sonr1abc123...';
await vault.initialize('/plugin.wasm', accountAddress);
// Tokens are now automatically persisted
const token = await vault.newOriginToken({
audience_did: 'did:example:123',
});
```
## Advanced Features
### Multi-Account Support
Seamlessly switch between accounts and manage their individual databases:
```typescript
// Switch to a different account
await vault.switchAccount('sonr1account2');
// List all accounts with persisted data
const accounts = await vault.listPersistedAccounts();
// Remove an account's data
await vault.removeAccount('sonr1account1');
```
### Token Management
Manually manage persisted tokens:
```typescript
// Get all saved tokens
const tokens = await vault.getPersistedTokens();
// Save a specific token
await vault.saveToken({
token: 'eyJ...',
issuer: 'did:sonr:example',
address: 'sonr1abc...',
});
// Remove expired tokens
await vault.removeExpiredTokens();
```
### State Management
Control vault state persistence:
```typescript
// Manually save current state
await vault.persistState();
// Load persisted state
const state = await vault.loadPersistedState();
// Clear all persisted data for the current account
await vault.clearPersistedState();
```
## Storage Management
Use the `VaultStorageManager` for advanced storage operations:
```typescript
import { VaultStorageManager } from '@sonr.io/es/plugins/vault';
const storageManager = new VaultStorageManager({
enablePersistence: true,
});
// Request persistent storage
const isPersisted = await storageManager.requestPersistentStorage();
// Check storage status and estimate
const status = await storageManager.tryPersistWithoutPromptingUser();
const estimate = await storageManager.getStorageEstimate();
```
## Configuration Options
Customize the vault's storage behavior:
<TypeTable
columns={[
{ name: 'enablePersistence', type: 'boolean', description: 'Enable IndexedDB storage' },
{ name: 'storageQuotaRequest', type: 'number', description: 'Storage quota to request in bytes' },
{ name: 'autoCleanup', type: 'boolean', description: 'Enable automatic token/session cleanup' },
{ name: 'cleanupInterval', type: 'number', description: 'Cleanup interval in milliseconds' }
]}
/>
## Browser Compatibility
The Vault Plugin works with most modern browsers:
<Table>
<TableHead>
<TableRow>
<TableCell>Browser</TableCell>
<TableCell>Minimum Version</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableCell>Chrome/Edge</TableCell>
<TableCell>23+</TableCell>
</TableRow>
<TableRow>
<TableCell>Firefox</TableCell>
<TableCell>16+</TableCell>
</TableRow>
<TableRow>
<TableCell>Safari</TableCell>
<TableCell>10+</TableCell>
</TableRow>
<TableRow>
<TableCell>Opera</TableCell>
<TableCell>15+</TableCell>
</TableRow>
<TableRow>
<TableCell>iOS Safari</TableCell>
<TableCell>10+</TableCell>
</TableRow>
<TableRow>
<TableCell>Chrome for Android</TableCell>
<TableCell>All versions</TableCell>
</TableRow>
</TableBody>
</Table>
## Storage Limits
Storage availability varies by browser:
<Table>
<TableHead>
<TableRow>
<TableCell>Browser</TableCell>
<TableCell>Storage Limit</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableCell>Chrome/Edge</TableCell>
<TableCell>60% of total disk space</TableCell>
</TableRow>
<TableRow>
<TableCell>Firefox</TableCell>
<TableCell>50% of free disk space</TableCell>
</TableRow>
<TableRow>
<TableCell>Safari</TableCell>
<TableCell>Starts at 1GB, can request more</TableCell>
</TableRow>
<TableRow>
<TableCell>Mobile Browsers</TableCell>
<TableCell>Varies by device</TableCell>
</TableRow>
</TableBody>
</Table>
## Security Considerations
<Callout type="warning">
- Databases are isolated by account address
- No private keys or sensitive cryptographic material are stored
- Only UCAN tokens and metadata are persisted
- Always use HTTPS in production
- Consider encrypting sensitive data before storage
</Callout>
## Troubleshooting
### Storage Not Persisting
1. Verify you're running on HTTPS
2. Check that IndexedDB is enabled in browser settings
3. Confirm available storage quota
4. Explicitly request persistent storage
```typescript
try {
await vault.initialize('/plugin.wasm', accountAddress);
} catch (error) {
if (error.code === 'VAULT_NOT_INITIALIZED') {
// Handle initialization error
}
}
```
## Migration Guide
To migrate from non-persistent to persistent storage:
```typescript
// Before (non-persistent)
const vault = createVaultClient();
await vault.initialize();
// After (with persistence)
const vault = createVaultClient({
enablePersistence: true,
});
await vault.initialize('/plugin.wasm', accountAddress);
```
<Callout type="success">
**No other code changes are required!** All existing methods work the same way.
</Callout>
+294
View File
@@ -0,0 +1,294 @@
---
title: VRF Key Management
description: Guide to managing VRF keys for multi-validator encryption
---
# VRF Key Management
VRF (Verifiable Random Function) keys are essential for consensus-based encryption in multi-validator Sonr networks. This guide explains how VRF keys work, how to manage them, and how to troubleshoot common issues.
## Overview
VRF keys enable:
- **Deterministic randomness** in distributed systems
- **Multi-validator encryption** key derivation
- **Consensus-based key rotation** when validator sets change
- **Secure encryption** without requiring shared secrets
## Automatic Generation
VRF keys are automatically generated when you initialize a new node:
```bash
snrd init <moniker> --chain-id sonrtest_1-1
```
This creates:
- VRF keypair at `~/.sonr/vrf_secret.key`
- Deterministic generation from chain-id
- Secure 0600 permissions (owner read/write only)
## VRF Key Commands
The `snrd keys vrf` command suite provides complete VRF key management:
### Show VRF Key Information
Display your node's VRF public key and verify configuration:
```bash
snrd keys vrf show
```
Example output:
```
VRF Key Information:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Path: /home/user/.sonr/vrf_secret.key
Public Key: d2d8f52119ba12f7f41b004314e3d040526393f09ba434f5b4196c4242ddac0d
Key Size: 64 bytes
Public Key Size: 32 bytes
Permissions: -rw-------
Modified: 2025-09-27 00:33:11
✓ VRF keys are properly configured
```
### Verify VRF Functionality
Test that VRF keys are working correctly:
```bash
snrd keys vrf verify
```
This performs:
- VRF key loading
- Public key derivation
- Test VRF computation with proof
- Cryptographic verification
### Generate New VRF Keys
Generate or regenerate VRF keys (with backup):
```bash
# Generate for current chain
snrd keys vrf generate
# Generate for specific chain
snrd keys vrf generate --chain-id sonrtest_1-1
# Force regenerate (creates backup)
snrd keys vrf generate --force
```
**⚠️ Warning**: Regenerating VRF keys will invalidate existing consensus-based encryption keys. Only do this if you understand the implications.
## Multi-Validator Testnet Setup
When setting up a multi-validator testnet, ensure each validator generates unique VRF keys:
### Using Scripts
The testnet scripts automatically generate VRF keys:
```bash
# Single node testnet
CHAIN_ID="sonrtest_1-1" CLEAN=true bash scripts/test_node.sh
# Multi-node testnet with Starship
make start
```
### Manual Setup
For manual validator setup:
1. **Initialize each validator**:
```bash
snrd init validator-01 --chain-id sonrtest_1-1
```
2. **Verify VRF keys**:
```bash
snrd keys vrf verify
```
3. **Check permissions**:
```bash
ls -la ~/.sonr/vrf_secret.key
# Should show: -rw------- (0600)
```
## Encryption Configuration
VRF keys are only required when encryption is enabled. You can control encryption via module parameters:
### Check Encryption Status
```bash
snrd query dwn params
```
Look for the `encryption_enabled` field.
### Disable Encryption
If you don't need encryption features, you can disable them:
```bash
# Via governance proposal
snrd tx gov submit-proposal param-change proposal.json
```
With `proposal.json`:
```json
{
"title": "Disable DWN Encryption",
"description": "Disable encryption features",
"changes": [
{
"subspace": "dwn",
"key": "EncryptionEnabled",
"value": "false"
}
]
}
```
## Troubleshooting
### Error: "VRF keys not loaded"
**Cause**: VRF keys are missing or corrupted.
**Solution**:
1. Check if keys exist:
```bash
ls -la ~/.sonr/vrf_secret.key
```
2. If missing, generate keys:
```bash
snrd keys vrf generate --chain-id sonrtest_1-1
```
3. If present but corrupted, regenerate:
```bash
snrd keys vrf generate --force
```
### Error: "Failed to check and perform key rotation"
**Cause**: VRF keys not available during EndBlock, but encryption is enabled.
**Solution**:
1. Verify VRF keys:
```bash
snrd keys vrf verify
```
2. Or disable encryption if not needed:
```bash
# Check current params
snrd query dwn params
# Submit governance proposal to disable
```
### Incorrect Permissions
**Cause**: VRF key file has insecure permissions.
**Fix**:
```bash
chmod 0600 ~/.sonr/vrf_secret.key
```
### Single-Node vs Multi-Validator
- **Single-node development**: Works without VRF keys (deterministic fallback)
- **Multi-validator testnet**: Requires VRF keys for consensus encryption
- **Production**: Always use VRF keys with proper security
## Security Best Practices
### Key Storage
- **Never share** VRF private keys between validators
- **Backup** VRF keys securely (offline storage)
- **Rotate** validator nodes if keys are compromised
- **Monitor** file permissions regularly
### File Permissions
Always ensure restrictive permissions:
```bash
# Check permissions
ls -la ~/.sonr/vrf_secret.key
# Fix if needed
chmod 0600 ~/.sonr/vrf_secret.key
chown $(whoami):$(whoami) ~/.sonr/vrf_secret.key
```
### Key Backup
Backup your VRF keys securely:
```bash
# Create encrypted backup
tar -czf vrf-backup.tar.gz -C ~/.sonr vrf_secret.key
gpg --symmetric --cipher-algo AES256 vrf-backup.tar.gz
# Store vrf-backup.tar.gz.gpg securely offline
```
### Recovery
Restore from backup:
```bash
# Decrypt backup
gpg --decrypt vrf-backup.tar.gz.gpg > vrf-backup.tar.gz
# Extract to correct location
tar -xzf vrf-backup.tar.gz -C ~/.sonr/
# Verify permissions
chmod 0600 ~/.sonr/vrf_secret.key
snrd keys vrf verify
```
## Advanced Topics
### Deterministic Generation
VRF keys are generated deterministically from the chain-id using SHA256. This means:
- Same chain-id = same VRF keys
- Different validators should use different chain configurations
- Re-running `snrd init` with same chain-id produces same keys
### VRF Algorithm
Sonr uses **VRF based on Ed25519** (Curve25519):
- Private key: 64 bytes (32 bytes secret + 32 bytes public)
- Public key: 32 bytes
- Proof: 80 bytes
- Output: 32 bytes of verifiable randomness
### Consensus Encryption
Multi-validator encryption key derivation:
1. Each validator computes VRF output from consensus input
2. VRF outputs are combined to derive encryption key
3. Automatic rotation when validator set changes
4. Keys are never transmitted over network
## See Also
- [Configure Local Node](/guides/configure-local-node) - Node setup guide
- [Development](/guides/development) - Development environment setup
- [Deployment](/guides/deployment) - Production deployment guide
+562
View File
@@ -0,0 +1,562 @@
---
title: VRF Key Migration Guide
description: Migrate existing validator nodes to use VRF keys without downtime
---
# VRF Key Migration Guide
This guide provides step-by-step instructions for adding VRF keys to existing Sonr validator nodes that were initialized before VRF key support was added.
## Overview
VRF (Verifiable Random Function) keys are required for:
- Multi-validator encryption features (added in v0.1.12)
- Consensus-based key rotation
- Secure encryption key derivation
Existing nodes initialized before v0.1.12 may not have VRF keys generated.
## Pre-Migration Checklist
Before starting the migration:
- [ ] **Backup** your validator keys and configuration
- [ ] **Identify** which validators need VRF keys
- [ ] **Plan** migration during low-traffic period
- [ ] **Coordinate** with other validators (for governance proposals)
- [ ] **Test** on testnet first
## Migration Scenarios
### Scenario 1: Encryption Not Needed
If your network doesn't use encryption features, you can disable encryption instead of generating VRF keys.
**Option A: Disable via Governance**
1. Create governance proposal:
```bash
cat > disable-encryption-proposal.json <<EOF
{
"messages": [
{
"@type": "/cosmos.params.v1beta1.MsgUpdateParams",
"authority": "sonr10d07y265gmmuvt4z0w9aw880jnsr700j8yv32t",
"params": {
"encryption_enabled": false
}
}
],
"metadata": "Disable encryption until VRF keys are configured",
"deposit": "10000000usnr",
"title": "Disable DWN Encryption",
"summary": "Temporary disable encryption to allow gradual VRF key rollout"
}
EOF
```
2. Submit proposal:
```bash
snrd tx gov submit-proposal disable-encryption-proposal.json \
--from validator \
--chain-id sonrtest_1-1 \
--gas auto \
--gas-adjustment 1.5
```
3. Vote and wait for execution.
**Option B: Genesis Parameter (New Networks Only)**
For new networks, set in genesis:
```json
{
"app_state": {
"dwn": {
"params": {
"encryption_enabled": false
}
}
}
}
```
### Scenario 2: Gradual Migration (Recommended)
Migrate validators one at a time to minimize risk.
**Step 1: Disable Encryption Temporarily**
Follow Scenario 1, Option A to disable encryption via governance.
**Step 2: Generate VRF Keys for Each Validator**
On each validator node:
1. **Stop the validator** (optional, but recommended):
```bash
systemctl stop snrd
# or
pkill snrd
```
2. **Generate VRF keys**:
```bash
snrd keys vrf generate --chain-id sonrtest_1-1
```
3. **Verify generation**:
```bash
snrd keys vrf show
snrd keys vrf verify
```
4. **Check permissions**:
```bash
ls -la ~/.sonr/vrf_secret.key
# Should show: -rw------- (0600)
```
5. **Restart validator**:
```bash
systemctl start snrd
# or start manually
```
6. **Verify node is syncing**:
```bash
snrd status | jq '.SyncInfo'
```
**Step 3: Verify All Validators Have VRF Keys**
On each validator, run:
```bash
snrd keys vrf verify
```
All validators should show:
```
✓ VRF keys are fully functional
```
**Step 4: Re-enable Encryption**
Once all validators have VRF keys:
1. Create governance proposal:
```bash
cat > enable-encryption-proposal.json <<EOF
{
"messages": [
{
"@type": "/cosmos.params.v1beta1.MsgUpdateParams",
"authority": "sonr10d07y265gmmuvt4z0w9aw880jnsr700j8yv32t",
"params": {
"encryption_enabled": true
}
}
],
"metadata": "Re-enable encryption after VRF key deployment",
"deposit": "10000000usnr",
"title": "Enable DWN Encryption",
"summary": "Re-enable encryption now that all validators have VRF keys"
}
EOF
```
2. Submit and execute proposal.
### Scenario 3: Coordinated Network Upgrade
For critical production networks, coordinate a network-wide upgrade.
**Phase 1: Preparation (1-2 weeks before)**
1. **Announce upgrade** to all validators
2. **Share migration plan** and timeline
3. **Test on testnet** with same validator set
4. **Prepare rollback plan**
**Phase 2: Pre-Upgrade (1 day before)**
1. **Verify all validators** are ready:
```bash
# Check validator set
snrd query staking validators --output json | jq '.validators[] | {moniker, status}'
```
2. **Backup critical data**:
```bash
# Backup validator state
tar -czf validator-backup-$(date +%Y%m%d).tar.gz \
~/.sonr/config/ \
~/.sonr/data/priv_validator_state.json
```
3. **Sync upgrade binary**:
```bash
# Ensure all validators have same version
snrd version
```
**Phase 3: Migration Window**
1. **Stop network** at agreed block height:
```bash
# All validators stop
systemctl stop snrd
```
2. **Generate VRF keys** on each validator:
```bash
snrd keys vrf generate --chain-id sonrtest_1-1
snrd keys vrf verify
```
3. **Verify permissions**:
```bash
chmod 0600 ~/.sonr/vrf_secret.key
```
4. **Restart validators** in coordination:
```bash
systemctl start snrd
```
5. **Monitor network recovery**:
```bash
# Watch consensus
snrd status | jq '.SyncInfo.catching_up'
# Watch block production
watch -n 1 'snrd status | jq ".SyncInfo.latest_block_height"'
```
**Phase 4: Post-Migration Verification**
1. **Check all validators online**:
```bash
snrd query tendermint-validator-set | jq '.validators[].address'
```
2. **Verify VRF functionality**:
```bash
# On each validator
snrd keys vrf verify
```
3. **Test encryption features**:
```bash
# Create encrypted record
snrd tx dwn create-record \
--protocol "encrypted-protocol" \
--data "test-data" \
--from validator
```
4. **Monitor for errors**:
```bash
journalctl -u snrd -f | grep -i "vrf\|encryption"
```
## Rollback Procedures
If issues arise during migration:
### Emergency Rollback
1. **Stop affected validators**:
```bash
systemctl stop snrd
```
2. **Disable encryption via governance** (if network is running):
```bash
# Submit emergency proposal
snrd tx gov submit-proposal disable-encryption-proposal.json --expedited
```
3. **Restore from backup**:
```bash
# Stop node
systemctl stop snrd
# Restore backup
tar -xzf validator-backup-YYYYMMDD.tar.gz -C ~/
# Restart
systemctl start snrd
```
4. **Verify recovery**:
```bash
snrd status
```
### Gradual Rollback
If only some validators have issues:
1. Keep VRF keys on working validators
2. Remove VRF keys from problematic validators:
```bash
mv ~/.sonr/vrf_secret.key ~/.sonr/vrf_secret.key.backup
```
3. Disable encryption temporarily
4. Debug issues before retry
## Validation & Testing
### Pre-Migration Testing
Test on a private testnet first:
```bash
# Setup test network
CHAIN_ID="test-migration" make localnet
# Test VRF generation
snrd keys vrf generate --chain-id test-migration
snrd keys vrf verify
# Test with encryption enabled
snrd query dwn params
# Test key rotation
# (trigger validator set change)
```
### Post-Migration Validation
After migration, verify:
1. **All validators have VRF keys**:
```bash
# On each validator
snrd keys vrf show
```
2. **No VRF errors in logs**:
```bash
journalctl -u snrd --since "1 hour ago" | grep -i "vrf" | grep -i "error"
# Should return nothing
```
3. **Encryption working**:
```bash
snrd query dwn params | jq '.params.encryption_enabled'
# Should return: true
```
4. **Key rotation functional**:
```bash
# Check encryption state
snrd query dwn encryption-state
```
## Troubleshooting
### Issue: "VRF keys not loaded"
**Cause**: Keys not generated or file permissions incorrect.
**Fix**:
```bash
# Regenerate keys
snrd keys vrf generate --chain-id <your-chain-id> --force
# Fix permissions
chmod 0600 ~/.sonr/vrf_secret.key
# Verify
snrd keys vrf verify
```
### Issue: "Failed to check and perform key rotation"
**Cause**: Encryption enabled but VRF keys missing on some validators.
**Fix**:
1. Identify validators without VRF keys
2. Temporarily disable encryption
3. Generate VRF keys on all validators
4. Re-enable encryption
### Issue: Network Stalled During Migration
**Cause**: Too many validators offline simultaneously.
**Fix**:
1. Ensure >2/3 voting power online
2. Coordinate restart timing
3. Use smaller migration windows per validator
### Issue: Inconsistent VRF Keys
**Cause**: Different chain-id used during generation.
**Fix**:
```bash
# Check chain-id in genesis
jq '.chain_id' ~/.sonr/config/genesis.json
# Regenerate with correct chain-id
snrd keys vrf generate --chain-id <correct-chain-id> --force
```
## Best Practices
### Before Migration
- ✅ Test on testnet with same topology
- ✅ Backup all validator data
- ✅ Document rollback procedures
- ✅ Prepare monitoring dashboards
- ✅ Schedule during low-traffic period
### During Migration
- ✅ Migrate one validator at a time (gradual)
- ✅ Monitor logs continuously
- ✅ Verify each step before proceeding
- ✅ Keep communication channels open
- ✅ Document any issues encountered
### After Migration
- ✅ Verify all validators functional
- ✅ Test encryption features
- ✅ Monitor performance metrics
- ✅ Update documentation
- ✅ Schedule follow-up verification
## Timeline Recommendations
### Small Network (3-5 validators)
- **Preparation**: 3-5 days
- **Migration**: 1-2 hours
- **Verification**: 1 day
### Medium Network (10-20 validators)
- **Preparation**: 1 week
- **Migration**: 4-6 hours (gradual) or 30 minutes (coordinated)
- **Verification**: 2-3 days
### Large Network (50+ validators)
- **Preparation**: 2-3 weeks
- **Migration**: 1-2 days (gradual) or network upgrade
- **Verification**: 1 week
## Support & Resources
- **VRF Key Management Guide**: `/guides/vrf-key-management`
- **GitHub Issues**: https://github.com/sonr-io/sonr/issues
- **Discord**: Validator support channel
- **Documentation**: https://docs.sonr.io
## Appendix: Automation Script
For networks with many validators, use this automation script:
```bash
#!/bin/bash
# vrf-migration.sh - Automated VRF key migration helper
set -e
CHAIN_ID="${CHAIN_ID:-sonrtest_1-1}"
BACKUP_DIR="${BACKUP_DIR:-$HOME/vrf-backup}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Backup existing data
backup_validator() {
log_info "Creating backup..."
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/validator-$(date +%Y%m%d-%H%M%S).tar.gz" \
~/.sonr/config/ \
~/.sonr/data/priv_validator_state.json 2>/dev/null || true
log_info "Backup created at $BACKUP_DIR"
}
# Generate VRF keys
generate_vrf() {
log_info "Generating VRF keys for chain: $CHAIN_ID"
if snrd keys vrf generate --chain-id "$CHAIN_ID"; then
log_info "VRF keys generated successfully"
else
log_error "Failed to generate VRF keys"
exit 1
fi
}
# Verify VRF keys
verify_vrf() {
log_info "Verifying VRF keys..."
if snrd keys vrf verify; then
log_info "VRF keys verified successfully"
else
log_error "VRF key verification failed"
exit 1
fi
}
# Fix permissions
fix_permissions() {
log_info "Fixing VRF key permissions..."
chmod 0600 ~/.sonr/vrf_secret.key
log_info "Permissions set to 0600"
}
# Main migration flow
main() {
log_info "Starting VRF key migration..."
log_info "Chain ID: $CHAIN_ID"
# Backup
backup_validator
# Generate keys
generate_vrf
# Fix permissions
fix_permissions
# Verify
verify_vrf
log_info "Migration completed successfully!"
log_info "Please restart your validator node"
}
# Run migration
main
```
Save and run:
```bash
chmod +x vrf-migration.sh
CHAIN_ID="sonrtest_1-1" ./vrf-migration.sh
```