7.2 KiB
Executable File
7.2 KiB
Executable File
Multi-Blockchain Architecture Design
Problem Statement
Need separate blockchains for different nations:
- test nation → test blockchain (isolated)
- ants nation → production blockchain (isolated)
- Each town belongs to ONE nation and participates in THAT nation's blockchain only
Solution: Nation-Scoped Blockchains
File Structure
/var/lib/apxtowns/data/
├── apxtri/
│ ├── blockchain/
│ │ ├── test/ # Test nation blockchain
│ │ │ ├── blocks/
│ │ │ │ ├── 0.json
│ │ │ │ ├── 1.json
│ │ │ ├── uptime/
│ │ │ │ ├── farm.json
│ │ │ │ ├── wall.json
│ │ │ ├── transactions/
│ │ │ └── utxo/
│ │ ├── ants/ # Production nation blockchain
│ │ │ ├── blocks/
│ │ │ ├── uptime/
│ │ │ ├── transactions/
│ │ │ └── utxo/
Key Changes
1. Blockchain Module (Per-Nation State)
// models/Blockchain.js
class Blockchain {
static blockchains = {}; // {nationId: {blockchain: [], pendingTx: []}}
static _getState(nation) {
if (!this.blockchains[nation]) {
this.blockchains[nation] = {
blockchain: [],
pendingTransactions: [],
receivedBlocks: {}
};
}
return this.blockchains[nation];
}
static getBlockchain(nation = process.env.NATION) {
return this._getState(nation).blockchain;
}
}
2. UptimeTracker (Per-Nation Heartbeats)
// models/UptimeTracker.js
static async getAllTownsWithUptime(nation = process.env.NATION) {
const uptimeDir = path.join(DATA_PATH, 'apxtri/blockchain', nation, 'uptime');
// Only returns towns from SAME nation
}
3. Consensus (Per-Nation Rounds)
// models/Consensus.js
static async runConsensusRound(nation = process.env.NATION) {
// Only interacts with towns in SAME nation
const allTowns = await UptimeTracker.getAllTownsWithUptime(nation);
const townsInNation = allTowns.filter(t => t.nation === nation);
}
Town Creation Endpoint
POST /apxtri/towns
Purpose: Initialize new town and sync with nation's blockchain
Request:
{
"townId": "newtown",
"nation": "test",
"domainName": "newtown.example.com",
"mayorId": "alice"
}
Headers: {
"xalias": "alice",
"xhash": "pgp-signature"
}
Validation Steps:
- ✅ Verify PGP signature (xalias = mayorId)
- ✅ Check townId doesn't exist in ANY nation
- ✅ Check nation exists (validate against allowed list)
- ✅ Verify domain resolves and is reachable
- ✅ Check if requesting town is authorized (admin/druid)
Actions:
- Create town entry in database
- Determine nation's current leader
- Request blockchain sync from leader
- Initialize local blockchain state for that nation
- Start consensus participation for that nation
- Generate initial APX3 allocation (bootstrap)
Response:
{
"status": 201,
"ref": "Towns",
"msg": "town_created_successfully",
"data": {
"townId": "newtown",
"nation": "test",
"blockchainHeight": 1234,
"syncedFrom": "farm",
"consensusEnabled": true,
"initialBalance": 100
}
}
Blockchain Synchronization
Initial Sync Process
When new town joins:
1. Find Leader
└─> Query /apxtri/blockchain/leader?nation=test
2. Request Full Chain
└─> GET /apxtri/blockchain/sync?nation=test&from=0
3. Validate Blocks
└─> Verify each block signature
└─> Check vote counts (≥66%)
└─> Validate transactions
4. Apply Locally
└─> Create local blockchain state
└─> Apply all transactions
└─> Build UTXO set
5. Start Participation
└─> Begin sending heartbeats
└─> Join consensus rounds
Continuous Sync
// Sync any missing blocks every minute
setInterval(async () => {
const localHeight = Blockchain.getBlockchain(nation).length;
const leaderHeight = await fetchLeaderHeight(nation);
if (leaderHeight > localHeight) {
const missingBlocks = await fetchBlocks(nation, localHeight, leaderHeight);
for (const block of missingBlocks) {
await Blockchain.addBlock(block, nation);
}
}
}, 60 * 1000);
Configuration
Nation Configuration File
// schema/nations.json
{
"test": {
"name": "Test Network",
"blockReward": 10,
"genesisBlock": {
"index": 0,
"timestamp": 1705750800000,
"transactions": [],
"hash": "genesis-test",
"validator": "genesis"
}
},
"ants": {
"name": "Production Network",
"blockReward": 10,
"genesisBlock": {
"index": 0,
"timestamp": 1705750800000,
"transactions": [],
"hash": "genesis-ants",
"validator": "genesis"
}
}
}
Environment Variables
# .env for each town
NATION=test # Which blockchain network
TOWN=farm # Town identifier
CONSENSUS_ENABLED=true
API Endpoints
GET /apxtri/blockchain/leader
Get current leader for a nation
GET /apxtri/blockchain/leader?nation=test
Response: {
"status": 200,
"data": {
"leader": "farm",
"roundNumber": 52341,
"uptimeScore": 0.95
}
}
GET /apxtri/blockchain/sync
Sync blockchain for a nation
GET /apxtri/blockchain/sync?nation=test&from=0&to=100
Response: {
"status": 200,
"data": {
"nation": "test",
"blocks": [...],
"currentHeight": 1234
}
}
POST /apxtri/towns (New Town Creation)
POST /apxtri/towns
Headers: {xalias, xhash, xtribe, xlang}
Body: {
townId, nation, domainName, mayorId
}
Response: {
"status": 201,
"data": {
"townId": "newtown",
"nation": "test",
"syncComplete": true
}
}
Implementation Plan
Phase 1: Namespace Blockchain by Nation
- Update Blockchain.js to support per-nation state
- Update UptimeTracker.js to filter by nation
- Update Consensus.js to scope by nation
- Add nation parameter to all blockchain operations
Phase 2: Town Creation Endpoint
- Implement POST /apxtri/towns validation
- Add domain verification (DNS + HTTP check)
- Add authorization checks (druid/admin)
- Generate town entry with PGP keys
Phase 3: Blockchain Sync
- Implement GET /apxtri/blockchain/leader
- Implement GET /apxtri/blockchain/sync
- Add sync logic to town creation
- Add continuous sync monitoring
Phase 4: Genesis Blocks
- Create genesis block for each nation
- Initialize on first startup
- Prevent double-initialization
Security Considerations
- Nation Isolation: Towns can ONLY interact with same nation
- Domain Verification: Must prove ownership via HTTP challenge
- Authorization: Only admins/druids can create towns
- Sync Validation: All blocks verified before applying
- PGP Signatures: Town creation requires valid mayor signature
Benefits
✅ Isolated Testing: Test blockchain won't affect production ✅ Scalability: Each nation is independent network ✅ Geographic Optimization: Nations can be region-specific ✅ Fault Tolerance: Failure in one nation doesn't affect others ✅ Clean Separation: Dev/prod environments completely isolated