Repository files navigation

Priority Fabric Transaction Gateway

A priority-based transaction ordering system integrated with Hyperledger Fabric, featuring a mempool with anti-starvation mechanisms and batch processing.

🎯 What This System Does

This project implements a priority-based transaction gateway that:

  1. Accepts transactions via HTTP API with different priority levels (swap, borrow, lend, transfer)
  2. Queues transactions in a priority mempool with anti-starvation protection
  3. Batches transactions for efficient processing
  4. Submits to Fabric through the complete consensus process:
    • ✅ Endorsement by peers
    • ✅ Ordering by orderer service
    • ✅ Validation and commitment to distributed ledger
    • ✅ Consensus through Raft/BFT

🏗️ Architecture

┌─────────────┐
│ Clients │
└──────┬──────┘
│ HTTP POST /submit
▼
┌─────────────────────────────────┐
│ Transaction Gateway (server.go)│
└──────┬──────────────────────────┘
│
▼
┌──────────────────┐
│ Priority Mempool │ ← Transactions queued by priority
│ - swap (0) │
│ - borrow (1) │
│ - lend (2) │
│ - transfer (3) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Batcher │ ← Groups transactions into batches
│ - Size trigger │ (alternates between priority-only
│ - Time trigger │ and anti-starvation modes)
└──────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ Fabric Gateway SDK (gRPC) │
└──────┬───────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ Hyperledger Fabric Network │
│ ┌────────┐ ┌────────┐ │
│ │ Peer 1 │ │ Peer 2 │ Endorse │
│ └────┬───┘ └────┬───┘ │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ ┌──────────┐ │
│ │ Orderer │ Order │
│ └─────┬────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Commit Block │ │
│ │ to Ledger │ │
│ └──────────────┘ │
└──────────────────────────────────┘

📋 Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose
  • Hyperledger Fabric binaries (included in fabric-samples)
  • fabric-samples repository (already present in your setup)

🚀 Quick Start

Step 1: Deploy Chaincode to Fabric Network

The deployment script will automatically:

  • Start the Fabric test-network (if not running)
  • Package your chaincode
  • Install on both org peers
  • Approve for both organizations
  • Commit to the channel
cd /Users/sathvikcustiv/fabric-dev/priority-fabric-project
./deploy-chaincode.sh

What happens during deployment:

  1. Network Check: Verifies if Fabric network is running, starts if needed
  2. Package: Creates a chaincode package from your Go code
  3. Install: Installs chaincode on Org1 and Org2 peers
  4. Approve: Gets approval from both organizations
  5. Commit: Commits chaincode definition to the channel
  6. Verify: Confirms successful deployment

Step 2: Start Gateway Server with Fabric Integration

# Run in simulation mode (no Fabric connection)
go run . --port=8080
# Run with Fabric integration (connects to network)
go run . --port=8080 --use-fabric
# Custom configuration
go run . --port=8080 --use-fabric --batch-size=50 --batch-timeout=5s --mempool-size=2000

Command-line flags:

  • --port: HTTP server port (default: 8080)
  • --use-fabric: Connect to Fabric network (default: false - simulation mode)
  • --batch-size: Transactions per batch (default: 100)
  • --batch-timeout: Max time before processing batch (default: 2s)
  • --mempool-size: Maximum mempool capacity (default: 1000)
  • --verbose: Enable verbose logging (default: false)

Step 3: Submit Transactions

# Create wallets first (run these commands in a new terminal)
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{ "from": "wallet1", "to": "wallet2", "amount": "100", "txType": "swap" }'

📡 API Endpoints

POST /submit

Submit a new transaction to the mempool.

Request:

{
"from": "address1",
"to": "address2",
"amount": "100.50",
"txType": "swap"
}

Valid Transaction Types:

  • swap - Priority 0 (highest)
  • borrow - Priority 1
  • lend - Priority 2
  • transfer - Priority 3 (lowest)

Response:

{
"transactionId": "a1b2c3d4...",
"status": "queued",
"priority": 0,
"message": "Transaction queued with priority 0"
}

GET /mempool/status

View current mempool statistics.

curl http://localhost:8080/mempool/status

GET /batcher/status

View batcher statistics and processing info.

curl http://localhost:8080/batcher/status

GET /transaction/status?id=

Check status of a specific transaction.

curl http://localhost:8080/transaction/status?id=a1b2c3d4

GET /transactions/completed

View all completed transactions.

curl http://localhost:8080/transactions/completed

GET /health

Health check endpoint.

curl http://localhost:8080/health

🔄 How Priority & Anti-Starvation Works

Priority Levels

Transactions are ordered by priority (0 = highest, 3 = lowest):

  1. swap (0) - Highest priority, processed first
  2. borrow (1) - High priority
  3. lend (2) - Medium priority
  4. transfer (3) - Lowest priority

Anti-Starvation Mechanism

The batcher alternates between two modes:

Odd Batches (1, 3, 5...): Priority-only mode

  • Strictly processes by priority
  • Highest priority transactions first

Even Batches (2, 4, 6...): Quota-based mode

  • Each priority level gets fair quota
  • Prevents low-priority transactions from being starved
  • Ensures all priorities eventually get processed

🔗 Fabric Integration Details

What Happens When You Submit a Transaction

  1. Client submits via HTTP POST to gateway
  2. Gateway validates and adds to mempool (sorted by priority)
  3. Batcher extracts batch when size/timeout threshold reached
  4. For each transaction in batch:
    • Transaction is sent to Fabric peer via gRPC
    • Peer endorses the transaction (executes chaincode)
    • Endorsement returned to gateway
  5. Gateway submits endorsed transaction to orderer
  6. Orderer orders transactions into a block
  7. Block is broadcast to all peers
  8. Peers validate and commit block to ledger
  9. Transaction confirmed - now permanently on blockchain

Consensus Process

Your transactions go through Fabric's complete consensus:

  • Endorsement: Peers execute chaincode and sign results
  • Ordering: Orderer service sequences transactions
  • Validation: Peers verify endorsements and check for conflicts
  • Commitment: Valid transactions written to ledger

🧪 Testing

Run the included test script

# Test with simulation (no Fabric needed)
./test_anti_starvation.sh http://localhost:8080
# The script will:# - Submit 10+ transactions with different priorities# - Show how batching works# - Demonstrate anti-starvation mechanism

Manual testing

# Terminal 1: Start server
go run . --use-fabric --port=8080 --batch-size=5 --batch-timeout=10s
# Terminal 2: Submit various transactions# High priority swap
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user1","to":"user2","amount":"100","txType":"swap"}'# Low priority transfer
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user3","to":"user4","amount":"50","txType":"transfer"}'# Check mempool
curl http://localhost:8080/mempool/status
# View completed transactions
curl http://localhost:8080/transactions/completed

📁 Project Structure

priority-fabric-project/
├── chaincode/ # Smart contract (deployed to Fabric)
│ ├── main.go # Chaincode implementation
│ └── go.mod
├── types/ # Shared data types
│ ├── transaction.go # Transaction structures
│ ├── wallet.go # Wallet structures
│ └── ...
├── fabric_client.go # Fabric Gateway SDK client
├── batcher.go # Transaction batching logic
├── mempool.go # Priority mempool implementation
├── gateway.go # HTTP API gateway
├── server.go # Main server entry point
├── priority_queue.go # Priority queue data structure
├── deploy-chaincode.sh # Chaincode deployment script
└── README.md # This file

🔍 Monitoring & Debugging

View server logs

The server provides detailed logging of:

  • Transaction submissions
  • Mempool operations
  • Batch processing
  • Fabric network communication

Check Fabric network

# View running containers
docker ps
# View peer logs
docker logs peer0.org1.example.com
# View orderer logs
docker logs orderer.example.com

Query chaincode directly

# Set environment for Org1cd /Users/sathvikcustiv/fabric-dev/fabric-samples/test-network
export PATH=${PWD}/../bin:$PATHexport FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
# Create a wallet
peer chaincode invoke \
-o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls \
--cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n wallet \
-c '{"function":"CreateWallet","Args":[]}'# Query a wallet (use address from CreateWallet response)
peer chaincode query \
-C mychannel \
-n wallet \
-c '{"function":"GetWallet","Args":["<wallet-address>"]}'

🛠️ Troubleshooting

"Failed to connect to Fabric"

  • Ensure Fabric network is running: cd fabric-samples/test-network && ./network.sh up createChannel
  • Check Docker containers are running: docker ps
  • Verify chaincode is deployed: Run ./deploy-chaincode.sh

"Chaincode not found"

  • Deploy chaincode: ./deploy-chaincode.sh
  • Check deployment: peer lifecycle chaincode querycommitted -C mychannel -n wallet

Port already in use

  • Kill process on port: lsof -ti:8080 | xargs kill -9
  • Or use different port: go run . --port=8081

Simulation mode when expecting Fabric

  • Ensure you're using --use-fabric flag
  • Check network connectivity to peer (localhost:7051)

📚 Learn More

🎓 Key Concepts Explained

Mempool

A temporary storage area where transactions wait before being processed. Like a priority queue at a bank - VIP customers (high priority) get served first, but regular customers aren't ignored forever.

Batching

Grouping multiple transactions together for efficiency. Instead of submitting transactions one-by-one to Fabric, we batch them to reduce network overhead and improve throughput.

Endorsement

Peers execute the chaincode and sign the result. This proves the transaction was validated by trusted parties before being added to the ledger.

Consensus

The distributed agreement process ensuring all peers have the same ledger state. Your transactions must pass through this to be considered valid.

Anti-Starvation

Mechanism ensuring low-priority transactions eventually get processed, even when high-priority transactions keep arriving.


Built with ❤️ for Hyperledger Fabric

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Priority Fabric Transaction Gateway

A priority-based transaction ordering system integrated with Hyperledger Fabric, featuring a mempool with anti-starvation mechanisms and batch processing.

🎯 What This System Does

This project implements a priority-based transaction gateway that:

  1. Accepts transactions via HTTP API with different priority levels (swap, borrow, lend, transfer)
  2. Queues transactions in a priority mempool with anti-starvation protection
  3. Batches transactions for efficient processing
  4. Submits to Fabric through the complete consensus process:
    • ✅ Endorsement by peers
    • ✅ Ordering by orderer service
    • ✅ Validation and commitment to distributed ledger
    • ✅ Consensus through Raft/BFT

🏗️ Architecture

┌─────────────┐
│ Clients │
└──────┬──────┘
│ HTTP POST /submit
▼
┌─────────────────────────────────┐
│ Transaction Gateway (server.go)│
└──────┬──────────────────────────┘
│
▼
┌──────────────────┐
│ Priority Mempool │ ← Transactions queued by priority
│ - swap (0) │
│ - borrow (1) │
│ - lend (2) │
│ - transfer (3) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Batcher │ ← Groups transactions into batches
│ - Size trigger │ (alternates between priority-only
│ - Time trigger │ and anti-starvation modes)
└──────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ Fabric Gateway SDK (gRPC) │
└──────┬───────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ Hyperledger Fabric Network │
│ ┌────────┐ ┌────────┐ │
│ │ Peer 1 │ │ Peer 2 │ Endorse │
│ └────┬───┘ └────┬───┘ │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ ┌──────────┐ │
│ │ Orderer │ Order │
│ └─────┬────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Commit Block │ │
│ │ to Ledger │ │
│ └──────────────┘ │
└──────────────────────────────────┘

📋 Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose
  • Hyperledger Fabric binaries (included in fabric-samples)
  • fabric-samples repository (already present in your setup)

🚀 Quick Start

Step 1: Deploy Chaincode to Fabric Network

The deployment script will automatically:

  • Start the Fabric test-network (if not running)
  • Package your chaincode
  • Install on both org peers
  • Approve for both organizations
  • Commit to the channel
cd /Users/sathvikcustiv/fabric-dev/priority-fabric-project
./deploy-chaincode.sh

What happens during deployment:

  1. Network Check: Verifies if Fabric network is running, starts if needed
  2. Package: Creates a chaincode package from your Go code
  3. Install: Installs chaincode on Org1 and Org2 peers
  4. Approve: Gets approval from both organizations
  5. Commit: Commits chaincode definition to the channel
  6. Verify: Confirms successful deployment

Step 2: Start Gateway Server with Fabric Integration

# Run in simulation mode (no Fabric connection)
go run . --port=8080
# Run with Fabric integration (connects to network)
go run . --port=8080 --use-fabric
# Custom configuration
go run . --port=8080 --use-fabric --batch-size=50 --batch-timeout=5s --mempool-size=2000

Command-line flags:

  • --port: HTTP server port (default: 8080)
  • --use-fabric: Connect to Fabric network (default: false - simulation mode)
  • --batch-size: Transactions per batch (default: 100)
  • --batch-timeout: Max time before processing batch (default: 2s)
  • --mempool-size: Maximum mempool capacity (default: 1000)
  • --verbose: Enable verbose logging (default: false)

Step 3: Submit Transactions

# Create wallets first (run these commands in a new terminal)
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{ "from": "wallet1", "to": "wallet2", "amount": "100", "txType": "swap" }'

📡 API Endpoints

POST /submit

Submit a new transaction to the mempool.

Request:

{
"from": "address1",
"to": "address2",
"amount": "100.50",
"txType": "swap"
}

Valid Transaction Types:

  • swap - Priority 0 (highest)
  • borrow - Priority 1
  • lend - Priority 2
  • transfer - Priority 3 (lowest)

Response:

{
"transactionId": "a1b2c3d4...",
"status": "queued",
"priority": 0,
"message": "Transaction queued with priority 0"
}

GET /mempool/status

View current mempool statistics.

curl http://localhost:8080/mempool/status

GET /batcher/status

View batcher statistics and processing info.

curl http://localhost:8080/batcher/status

GET /transaction/status?id=

Check status of a specific transaction.

curl http://localhost:8080/transaction/status?id=a1b2c3d4

GET /transactions/completed

View all completed transactions.

curl http://localhost:8080/transactions/completed

GET /health

Health check endpoint.

curl http://localhost:8080/health

🔄 How Priority & Anti-Starvation Works

Priority Levels

Transactions are ordered by priority (0 = highest, 3 = lowest):

  1. swap (0) - Highest priority, processed first
  2. borrow (1) - High priority
  3. lend (2) - Medium priority
  4. transfer (3) - Lowest priority

Anti-Starvation Mechanism

The batcher alternates between two modes:

Odd Batches (1, 3, 5...): Priority-only mode

  • Strictly processes by priority
  • Highest priority transactions first

Even Batches (2, 4, 6...): Quota-based mode

  • Each priority level gets fair quota
  • Prevents low-priority transactions from being starved
  • Ensures all priorities eventually get processed

🔗 Fabric Integration Details

What Happens When You Submit a Transaction

  1. Client submits via HTTP POST to gateway
  2. Gateway validates and adds to mempool (sorted by priority)
  3. Batcher extracts batch when size/timeout threshold reached
  4. For each transaction in batch:
    • Transaction is sent to Fabric peer via gRPC
    • Peer endorses the transaction (executes chaincode)
    • Endorsement returned to gateway
  5. Gateway submits endorsed transaction to orderer
  6. Orderer orders transactions into a block
  7. Block is broadcast to all peers
  8. Peers validate and commit block to ledger
  9. Transaction confirmed - now permanently on blockchain

Consensus Process

Your transactions go through Fabric's complete consensus:

  • Endorsement: Peers execute chaincode and sign results
  • Ordering: Orderer service sequences transactions
  • Validation: Peers verify endorsements and check for conflicts
  • Commitment: Valid transactions written to ledger

🧪 Testing

Run the included test script

# Test with simulation (no Fabric needed)
./test_anti_starvation.sh http://localhost:8080
# The script will:# - Submit 10+ transactions with different priorities# - Show how batching works# - Demonstrate anti-starvation mechanism

Manual testing

# Terminal 1: Start server
go run . --use-fabric --port=8080 --batch-size=5 --batch-timeout=10s
# Terminal 2: Submit various transactions# High priority swap
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user1","to":"user2","amount":"100","txType":"swap"}'# Low priority transfer
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user3","to":"user4","amount":"50","txType":"transfer"}'# Check mempool
curl http://localhost:8080/mempool/status
# View completed transactions
curl http://localhost:8080/transactions/completed

📁 Project Structure

priority-fabric-project/
├── chaincode/ # Smart contract (deployed to Fabric)
│ ├── main.go # Chaincode implementation
│ └── go.mod
├── types/ # Shared data types
│ ├── transaction.go # Transaction structures
│ ├── wallet.go # Wallet structures
│ └── ...
├── fabric_client.go # Fabric Gateway SDK client
├── batcher.go # Transaction batching logic
├── mempool.go # Priority mempool implementation
├── gateway.go # HTTP API gateway
├── server.go # Main server entry point
├── priority_queue.go # Priority queue data structure
├── deploy-chaincode.sh # Chaincode deployment script
└── README.md # This file

🔍 Monitoring & Debugging

View server logs

The server provides detailed logging of:

  • Transaction submissions
  • Mempool operations
  • Batch processing
  • Fabric network communication

Check Fabric network

# View running containers
docker ps
# View peer logs
docker logs peer0.org1.example.com
# View orderer logs
docker logs orderer.example.com

Query chaincode directly

# Set environment for Org1cd /Users/sathvikcustiv/fabric-dev/fabric-samples/test-network
export PATH=${PWD}/../bin:$PATHexport FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
# Create a wallet
peer chaincode invoke \
-o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls \
--cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n wallet \
-c '{"function":"CreateWallet","Args":[]}'# Query a wallet (use address from CreateWallet response)
peer chaincode query \
-C mychannel \
-n wallet \
-c '{"function":"GetWallet","Args":["<wallet-address>"]}'

🛠️ Troubleshooting

"Failed to connect to Fabric"

  • Ensure Fabric network is running: cd fabric-samples/test-network && ./network.sh up createChannel
  • Check Docker containers are running: docker ps
  • Verify chaincode is deployed: Run ./deploy-chaincode.sh

"Chaincode not found"

  • Deploy chaincode: ./deploy-chaincode.sh
  • Check deployment: peer lifecycle chaincode querycommitted -C mychannel -n wallet

Port already in use

  • Kill process on port: lsof -ti:8080 | xargs kill -9
  • Or use different port: go run . --port=8081

Simulation mode when expecting Fabric

  • Ensure you're using --use-fabric flag
  • Check network connectivity to peer (localhost:7051)

📚 Learn More

🎓 Key Concepts Explained

Mempool

A temporary storage area where transactions wait before being processed. Like a priority queue at a bank - VIP customers (high priority) get served first, but regular customers aren't ignored forever.

Batching

Grouping multiple transactions together for efficiency. Instead of submitting transactions one-by-one to Fabric, we batch them to reduce network overhead and improve throughput.

Endorsement

Peers execute the chaincode and sign the result. This proves the transaction was validated by trusted parties before being added to the ledger.

Consensus

The distributed agreement process ensuring all peers have the same ledger state. Your transactions must pass through this to be considered valid.

Anti-Starvation

Mechanism ensuring low-priority transactions eventually get processed, even when high-priority transactions keep arriving.


Built with ❤️ for Hyperledger Fabric

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Priority Fabric Transaction Gateway

A priority-based transaction ordering system integrated with Hyperledger Fabric, featuring a mempool with anti-starvation mechanisms and batch processing.

🎯 What This System Does

This project implements a priority-based transaction gateway that:

  1. Accepts transactions via HTTP API with different priority levels (swap, borrow, lend, transfer)
  2. Queues transactions in a priority mempool with anti-starvation protection
  3. Batches transactions for efficient processing
  4. Submits to Fabric through the complete consensus process:
    • ✅ Endorsement by peers
    • ✅ Ordering by orderer service
    • ✅ Validation and commitment to distributed ledger
    • ✅ Consensus through Raft/BFT

🏗️ Architecture

┌─────────────┐
│ Clients │
└──────┬──────┘
│ HTTP POST /submit
▼
┌─────────────────────────────────┐
│ Transaction Gateway (server.go)│
└──────┬──────────────────────────┘
│
▼
┌──────────────────┐
│ Priority Mempool │ ← Transactions queued by priority
│ - swap (0) │
│ - borrow (1) │
│ - lend (2) │
│ - transfer (3) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Batcher │ ← Groups transactions into batches
│ - Size trigger │ (alternates between priority-only
│ - Time trigger │ and anti-starvation modes)
└──────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ Fabric Gateway SDK (gRPC) │
└──────┬───────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ Hyperledger Fabric Network │
│ ┌────────┐ ┌────────┐ │
│ │ Peer 1 │ │ Peer 2 │ Endorse │
│ └────┬───┘ └────┬───┘ │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ ┌──────────┐ │
│ │ Orderer │ Order │
│ └─────┬────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Commit Block │ │
│ │ to Ledger │ │
│ └──────────────┘ │
└──────────────────────────────────┘

📋 Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose
  • Hyperledger Fabric binaries (included in fabric-samples)
  • fabric-samples repository (already present in your setup)

🚀 Quick Start

Step 1: Deploy Chaincode to Fabric Network

The deployment script will automatically:

  • Start the Fabric test-network (if not running)
  • Package your chaincode
  • Install on both org peers
  • Approve for both organizations
  • Commit to the channel
cd /Users/sathvikcustiv/fabric-dev/priority-fabric-project
./deploy-chaincode.sh

What happens during deployment:

  1. Network Check: Verifies if Fabric network is running, starts if needed
  2. Package: Creates a chaincode package from your Go code
  3. Install: Installs chaincode on Org1 and Org2 peers
  4. Approve: Gets approval from both organizations
  5. Commit: Commits chaincode definition to the channel
  6. Verify: Confirms successful deployment

Step 2: Start Gateway Server with Fabric Integration

# Run in simulation mode (no Fabric connection)
go run . --port=8080
# Run with Fabric integration (connects to network)
go run . --port=8080 --use-fabric
# Custom configuration
go run . --port=8080 --use-fabric --batch-size=50 --batch-timeout=5s --mempool-size=2000

Command-line flags:

  • --port: HTTP server port (default: 8080)
  • --use-fabric: Connect to Fabric network (default: false - simulation mode)
  • --batch-size: Transactions per batch (default: 100)
  • --batch-timeout: Max time before processing batch (default: 2s)
  • --mempool-size: Maximum mempool capacity (default: 1000)
  • --verbose: Enable verbose logging (default: false)

Step 3: Submit Transactions

# Create wallets first (run these commands in a new terminal)
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{ "from": "wallet1", "to": "wallet2", "amount": "100", "txType": "swap" }'

📡 API Endpoints

POST /submit

Submit a new transaction to the mempool.

Request:

{
"from": "address1",
"to": "address2",
"amount": "100.50",
"txType": "swap"
}

Valid Transaction Types:

  • swap - Priority 0 (highest)
  • borrow - Priority 1
  • lend - Priority 2
  • transfer - Priority 3 (lowest)

Response:

{
"transactionId": "a1b2c3d4...",
"status": "queued",
"priority": 0,
"message": "Transaction queued with priority 0"
}

GET /mempool/status

View current mempool statistics.

curl http://localhost:8080/mempool/status

GET /batcher/status

View batcher statistics and processing info.

curl http://localhost:8080/batcher/status

GET /transaction/status?id=

Check status of a specific transaction.

curl http://localhost:8080/transaction/status?id=a1b2c3d4

GET /transactions/completed

View all completed transactions.

curl http://localhost:8080/transactions/completed

GET /health

Health check endpoint.

curl http://localhost:8080/health

🔄 How Priority & Anti-Starvation Works

Priority Levels

Transactions are ordered by priority (0 = highest, 3 = lowest):

  1. swap (0) - Highest priority, processed first
  2. borrow (1) - High priority
  3. lend (2) - Medium priority
  4. transfer (3) - Lowest priority

Anti-Starvation Mechanism

The batcher alternates between two modes:

Odd Batches (1, 3, 5...): Priority-only mode

  • Strictly processes by priority
  • Highest priority transactions first

Even Batches (2, 4, 6...): Quota-based mode

  • Each priority level gets fair quota
  • Prevents low-priority transactions from being starved
  • Ensures all priorities eventually get processed

🔗 Fabric Integration Details

What Happens When You Submit a Transaction

  1. Client submits via HTTP POST to gateway
  2. Gateway validates and adds to mempool (sorted by priority)
  3. Batcher extracts batch when size/timeout threshold reached
  4. For each transaction in batch:
    • Transaction is sent to Fabric peer via gRPC
    • Peer endorses the transaction (executes chaincode)
    • Endorsement returned to gateway
  5. Gateway submits endorsed transaction to orderer
  6. Orderer orders transactions into a block
  7. Block is broadcast to all peers
  8. Peers validate and commit block to ledger
  9. Transaction confirmed - now permanently on blockchain

Consensus Process

Your transactions go through Fabric's complete consensus:

  • Endorsement: Peers execute chaincode and sign results
  • Ordering: Orderer service sequences transactions
  • Validation: Peers verify endorsements and check for conflicts
  • Commitment: Valid transactions written to ledger

🧪 Testing

Run the included test script

# Test with simulation (no Fabric needed)
./test_anti_starvation.sh http://localhost:8080
# The script will:# - Submit 10+ transactions with different priorities# - Show how batching works# - Demonstrate anti-starvation mechanism

Manual testing

# Terminal 1: Start server
go run . --use-fabric --port=8080 --batch-size=5 --batch-timeout=10s
# Terminal 2: Submit various transactions# High priority swap
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user1","to":"user2","amount":"100","txType":"swap"}'# Low priority transfer
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user3","to":"user4","amount":"50","txType":"transfer"}'# Check mempool
curl http://localhost:8080/mempool/status
# View completed transactions
curl http://localhost:8080/transactions/completed

📁 Project Structure

priority-fabric-project/
├── chaincode/ # Smart contract (deployed to Fabric)
│ ├── main.go # Chaincode implementation
│ └── go.mod
├── types/ # Shared data types
│ ├── transaction.go # Transaction structures
│ ├── wallet.go # Wallet structures
│ └── ...
├── fabric_client.go # Fabric Gateway SDK client
├── batcher.go # Transaction batching logic
├── mempool.go # Priority mempool implementation
├── gateway.go # HTTP API gateway
├── server.go # Main server entry point
├── priority_queue.go # Priority queue data structure
├── deploy-chaincode.sh # Chaincode deployment script
└── README.md # This file

🔍 Monitoring & Debugging

View server logs

The server provides detailed logging of:

  • Transaction submissions
  • Mempool operations
  • Batch processing
  • Fabric network communication

Check Fabric network

# View running containers
docker ps
# View peer logs
docker logs peer0.org1.example.com
# View orderer logs
docker logs orderer.example.com

Query chaincode directly

# Set environment for Org1cd /Users/sathvikcustiv/fabric-dev/fabric-samples/test-network
export PATH=${PWD}/../bin:$PATHexport FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
# Create a wallet
peer chaincode invoke \
-o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls \
--cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n wallet \
-c '{"function":"CreateWallet","Args":[]}'# Query a wallet (use address from CreateWallet response)
peer chaincode query \
-C mychannel \
-n wallet \
-c '{"function":"GetWallet","Args":["<wallet-address>"]}'

🛠️ Troubleshooting

"Failed to connect to Fabric"

  • Ensure Fabric network is running: cd fabric-samples/test-network && ./network.sh up createChannel
  • Check Docker containers are running: docker ps
  • Verify chaincode is deployed: Run ./deploy-chaincode.sh

"Chaincode not found"

  • Deploy chaincode: ./deploy-chaincode.sh
  • Check deployment: peer lifecycle chaincode querycommitted -C mychannel -n wallet

Port already in use

  • Kill process on port: lsof -ti:8080 | xargs kill -9
  • Or use different port: go run . --port=8081

Simulation mode when expecting Fabric

  • Ensure you're using --use-fabric flag
  • Check network connectivity to peer (localhost:7051)

📚 Learn More

🎓 Key Concepts Explained

Mempool

A temporary storage area where transactions wait before being processed. Like a priority queue at a bank - VIP customers (high priority) get served first, but regular customers aren't ignored forever.

Batching

Grouping multiple transactions together for efficiency. Instead of submitting transactions one-by-one to Fabric, we batch them to reduce network overhead and improve throughput.

Endorsement

Peers execute the chaincode and sign the result. This proves the transaction was validated by trusted parties before being added to the ledger.

Consensus

The distributed agreement process ensuring all peers have the same ledger state. Your transactions must pass through this to be considered valid.

Anti-Starvation

Mechanism ensuring low-priority transactions eventually get processed, even when high-priority transactions keep arriving.


Built with ❤️ for Hyperledger Fabric

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Priority Fabric Transaction Gateway

A priority-based transaction ordering system integrated with Hyperledger Fabric, featuring a mempool with anti-starvation mechanisms and batch processing.

🎯 What This System Does

This project implements a priority-based transaction gateway that:

  1. Accepts transactions via HTTP API with different priority levels (swap, borrow, lend, transfer)
  2. Queues transactions in a priority mempool with anti-starvation protection
  3. Batches transactions for efficient processing
  4. Submits to Fabric through the complete consensus process:
    • ✅ Endorsement by peers
    • ✅ Ordering by orderer service
    • ✅ Validation and commitment to distributed ledger
    • ✅ Consensus through Raft/BFT

🏗️ Architecture

┌─────────────┐
│ Clients │
└──────┬──────┘
│ HTTP POST /submit
▼
┌─────────────────────────────────┐
│ Transaction Gateway (server.go)│
└──────┬──────────────────────────┘
│
▼
┌──────────────────┐
│ Priority Mempool │ ← Transactions queued by priority
│ - swap (0) │
│ - borrow (1) │
│ - lend (2) │
│ - transfer (3) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Batcher │ ← Groups transactions into batches
│ - Size trigger │ (alternates between priority-only
│ - Time trigger │ and anti-starvation modes)
└──────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ Fabric Gateway SDK (gRPC) │
└──────┬───────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ Hyperledger Fabric Network │
│ ┌────────┐ ┌────────┐ │
│ │ Peer 1 │ │ Peer 2 │ Endorse │
│ └────┬───┘ └────┬───┘ │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ ┌──────────┐ │
│ │ Orderer │ Order │
│ └─────┬────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Commit Block │ │
│ │ to Ledger │ │
│ └──────────────┘ │
└──────────────────────────────────┘

📋 Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose
  • Hyperledger Fabric binaries (included in fabric-samples)
  • fabric-samples repository (already present in your setup)

🚀 Quick Start

Step 1: Deploy Chaincode to Fabric Network

The deployment script will automatically:

  • Start the Fabric test-network (if not running)
  • Package your chaincode
  • Install on both org peers
  • Approve for both organizations
  • Commit to the channel
cd /Users/sathvikcustiv/fabric-dev/priority-fabric-project
./deploy-chaincode.sh

What happens during deployment:

  1. Network Check: Verifies if Fabric network is running, starts if needed
  2. Package: Creates a chaincode package from your Go code
  3. Install: Installs chaincode on Org1 and Org2 peers
  4. Approve: Gets approval from both organizations
  5. Commit: Commits chaincode definition to the channel
  6. Verify: Confirms successful deployment

Step 2: Start Gateway Server with Fabric Integration

# Run in simulation mode (no Fabric connection)
go run . --port=8080
# Run with Fabric integration (connects to network)
go run . --port=8080 --use-fabric
# Custom configuration
go run . --port=8080 --use-fabric --batch-size=50 --batch-timeout=5s --mempool-size=2000

Command-line flags:

  • --port: HTTP server port (default: 8080)
  • --use-fabric: Connect to Fabric network (default: false - simulation mode)
  • --batch-size: Transactions per batch (default: 100)
  • --batch-timeout: Max time before processing batch (default: 2s)
  • --mempool-size: Maximum mempool capacity (default: 1000)
  • --verbose: Enable verbose logging (default: false)

Step 3: Submit Transactions

# Create wallets first (run these commands in a new terminal)
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{ "from": "wallet1", "to": "wallet2", "amount": "100", "txType": "swap" }'

📡 API Endpoints

POST /submit

Submit a new transaction to the mempool.

Request:

{
"from": "address1",
"to": "address2",
"amount": "100.50",
"txType": "swap"
}

Valid Transaction Types:

  • swap - Priority 0 (highest)
  • borrow - Priority 1
  • lend - Priority 2
  • transfer - Priority 3 (lowest)

Response:

{
"transactionId": "a1b2c3d4...",
"status": "queued",
"priority": 0,
"message": "Transaction queued with priority 0"
}

GET /mempool/status

View current mempool statistics.

curl http://localhost:8080/mempool/status

GET /batcher/status

View batcher statistics and processing info.

curl http://localhost:8080/batcher/status

GET /transaction/status?id=

Check status of a specific transaction.

curl http://localhost:8080/transaction/status?id=a1b2c3d4

GET /transactions/completed

View all completed transactions.

curl http://localhost:8080/transactions/completed

GET /health

Health check endpoint.

curl http://localhost:8080/health

🔄 How Priority & Anti-Starvation Works

Priority Levels

Transactions are ordered by priority (0 = highest, 3 = lowest):

  1. swap (0) - Highest priority, processed first
  2. borrow (1) - High priority
  3. lend (2) - Medium priority
  4. transfer (3) - Lowest priority

Anti-Starvation Mechanism

The batcher alternates between two modes:

Odd Batches (1, 3, 5...): Priority-only mode

  • Strictly processes by priority
  • Highest priority transactions first

Even Batches (2, 4, 6...): Quota-based mode

  • Each priority level gets fair quota
  • Prevents low-priority transactions from being starved
  • Ensures all priorities eventually get processed

🔗 Fabric Integration Details

What Happens When You Submit a Transaction

  1. Client submits via HTTP POST to gateway
  2. Gateway validates and adds to mempool (sorted by priority)
  3. Batcher extracts batch when size/timeout threshold reached
  4. For each transaction in batch:
    • Transaction is sent to Fabric peer via gRPC
    • Peer endorses the transaction (executes chaincode)
    • Endorsement returned to gateway
  5. Gateway submits endorsed transaction to orderer
  6. Orderer orders transactions into a block
  7. Block is broadcast to all peers
  8. Peers validate and commit block to ledger
  9. Transaction confirmed - now permanently on blockchain

Consensus Process

Your transactions go through Fabric's complete consensus:

  • Endorsement: Peers execute chaincode and sign results
  • Ordering: Orderer service sequences transactions
  • Validation: Peers verify endorsements and check for conflicts
  • Commitment: Valid transactions written to ledger

🧪 Testing

Run the included test script

# Test with simulation (no Fabric needed)
./test_anti_starvation.sh http://localhost:8080
# The script will:# - Submit 10+ transactions with different priorities# - Show how batching works# - Demonstrate anti-starvation mechanism

Manual testing

# Terminal 1: Start server
go run . --use-fabric --port=8080 --batch-size=5 --batch-timeout=10s
# Terminal 2: Submit various transactions# High priority swap
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user1","to":"user2","amount":"100","txType":"swap"}'# Low priority transfer
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user3","to":"user4","amount":"50","txType":"transfer"}'# Check mempool
curl http://localhost:8080/mempool/status
# View completed transactions
curl http://localhost:8080/transactions/completed

📁 Project Structure

priority-fabric-project/
├── chaincode/ # Smart contract (deployed to Fabric)
│ ├── main.go # Chaincode implementation
│ └── go.mod
├── types/ # Shared data types
│ ├── transaction.go # Transaction structures
│ ├── wallet.go # Wallet structures
│ └── ...
├── fabric_client.go # Fabric Gateway SDK client
├── batcher.go # Transaction batching logic
├── mempool.go # Priority mempool implementation
├── gateway.go # HTTP API gateway
├── server.go # Main server entry point
├── priority_queue.go # Priority queue data structure
├── deploy-chaincode.sh # Chaincode deployment script
└── README.md # This file

🔍 Monitoring & Debugging

View server logs

The server provides detailed logging of:

  • Transaction submissions
  • Mempool operations
  • Batch processing
  • Fabric network communication

Check Fabric network

# View running containers
docker ps
# View peer logs
docker logs peer0.org1.example.com
# View orderer logs
docker logs orderer.example.com

Query chaincode directly

# Set environment for Org1cd /Users/sathvikcustiv/fabric-dev/fabric-samples/test-network
export PATH=${PWD}/../bin:$PATHexport FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
# Create a wallet
peer chaincode invoke \
-o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls \
--cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n wallet \
-c '{"function":"CreateWallet","Args":[]}'# Query a wallet (use address from CreateWallet response)
peer chaincode query \
-C mychannel \
-n wallet \
-c '{"function":"GetWallet","Args":["<wallet-address>"]}'

🛠️ Troubleshooting

"Failed to connect to Fabric"

  • Ensure Fabric network is running: cd fabric-samples/test-network && ./network.sh up createChannel
  • Check Docker containers are running: docker ps
  • Verify chaincode is deployed: Run ./deploy-chaincode.sh

"Chaincode not found"

  • Deploy chaincode: ./deploy-chaincode.sh
  • Check deployment: peer lifecycle chaincode querycommitted -C mychannel -n wallet

Port already in use

  • Kill process on port: lsof -ti:8080 | xargs kill -9
  • Or use different port: go run . --port=8081

Simulation mode when expecting Fabric

  • Ensure you're using --use-fabric flag
  • Check network connectivity to peer (localhost:7051)

📚 Learn More

🎓 Key Concepts Explained

Mempool

A temporary storage area where transactions wait before being processed. Like a priority queue at a bank - VIP customers (high priority) get served first, but regular customers aren't ignored forever.

Batching

Grouping multiple transactions together for efficiency. Instead of submitting transactions one-by-one to Fabric, we batch them to reduce network overhead and improve throughput.

Endorsement

Peers execute the chaincode and sign the result. This proves the transaction was validated by trusted parties before being added to the ledger.

Consensus

The distributed agreement process ensuring all peers have the same ledger state. Your transactions must pass through this to be considered valid.

Anti-Starvation

Mechanism ensuring low-priority transactions eventually get processed, even when high-priority transactions keep arriving.


Built with ❤️ for Hyperledger Fabric

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Priority Fabric Transaction Gateway

A priority-based transaction ordering system integrated with Hyperledger Fabric, featuring a mempool with anti-starvation mechanisms and batch processing.

🎯 What This System Does

This project implements a priority-based transaction gateway that:

  1. Accepts transactions via HTTP API with different priority levels (swap, borrow, lend, transfer)
  2. Queues transactions in a priority mempool with anti-starvation protection
  3. Batches transactions for efficient processing
  4. Submits to Fabric through the complete consensus process:
    • ✅ Endorsement by peers
    • ✅ Ordering by orderer service
    • ✅ Validation and commitment to distributed ledger
    • ✅ Consensus through Raft/BFT

🏗️ Architecture

┌─────────────┐
│ Clients │
└──────┬──────┘
│ HTTP POST /submit
▼
┌─────────────────────────────────┐
│ Transaction Gateway (server.go)│
└──────┬──────────────────────────┘
│
▼
┌──────────────────┐
│ Priority Mempool │ ← Transactions queued by priority
│ - swap (0) │
│ - borrow (1) │
│ - lend (2) │
│ - transfer (3) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Batcher │ ← Groups transactions into batches
│ - Size trigger │ (alternates between priority-only
│ - Time trigger │ and anti-starvation modes)
└──────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ Fabric Gateway SDK (gRPC) │
└──────┬───────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ Hyperledger Fabric Network │
│ ┌────────┐ ┌────────┐ │
│ │ Peer 1 │ │ Peer 2 │ Endorse │
│ └────┬───┘ └────┬───┘ │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ ┌──────────┐ │
│ │ Orderer │ Order │
│ └─────┬────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Commit Block │ │
│ │ to Ledger │ │
│ └──────────────┘ │
└──────────────────────────────────┘

📋 Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose
  • Hyperledger Fabric binaries (included in fabric-samples)
  • fabric-samples repository (already present in your setup)

🚀 Quick Start

Step 1: Deploy Chaincode to Fabric Network

The deployment script will automatically:

  • Start the Fabric test-network (if not running)
  • Package your chaincode
  • Install on both org peers
  • Approve for both organizations
  • Commit to the channel
cd /Users/sathvikcustiv/fabric-dev/priority-fabric-project
./deploy-chaincode.sh

What happens during deployment:

  1. Network Check: Verifies if Fabric network is running, starts if needed
  2. Package: Creates a chaincode package from your Go code
  3. Install: Installs chaincode on Org1 and Org2 peers
  4. Approve: Gets approval from both organizations
  5. Commit: Commits chaincode definition to the channel
  6. Verify: Confirms successful deployment

Step 2: Start Gateway Server with Fabric Integration

# Run in simulation mode (no Fabric connection)
go run . --port=8080
# Run with Fabric integration (connects to network)
go run . --port=8080 --use-fabric
# Custom configuration
go run . --port=8080 --use-fabric --batch-size=50 --batch-timeout=5s --mempool-size=2000

Command-line flags:

  • --port: HTTP server port (default: 8080)
  • --use-fabric: Connect to Fabric network (default: false - simulation mode)
  • --batch-size: Transactions per batch (default: 100)
  • --batch-timeout: Max time before processing batch (default: 2s)
  • --mempool-size: Maximum mempool capacity (default: 1000)
  • --verbose: Enable verbose logging (default: false)

Step 3: Submit Transactions

# Create wallets first (run these commands in a new terminal)
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{ "from": "wallet1", "to": "wallet2", "amount": "100", "txType": "swap" }'

📡 API Endpoints

POST /submit

Submit a new transaction to the mempool.

Request:

{
"from": "address1",
"to": "address2",
"amount": "100.50",
"txType": "swap"
}

Valid Transaction Types:

  • swap - Priority 0 (highest)
  • borrow - Priority 1
  • lend - Priority 2
  • transfer - Priority 3 (lowest)

Response:

{
"transactionId": "a1b2c3d4...",
"status": "queued",
"priority": 0,
"message": "Transaction queued with priority 0"
}

GET /mempool/status

View current mempool statistics.

curl http://localhost:8080/mempool/status

GET /batcher/status

View batcher statistics and processing info.

curl http://localhost:8080/batcher/status

GET /transaction/status?id=

Check status of a specific transaction.

curl http://localhost:8080/transaction/status?id=a1b2c3d4

GET /transactions/completed

View all completed transactions.

curl http://localhost:8080/transactions/completed

GET /health

Health check endpoint.

curl http://localhost:8080/health

🔄 How Priority & Anti-Starvation Works

Priority Levels

Transactions are ordered by priority (0 = highest, 3 = lowest):

  1. swap (0) - Highest priority, processed first
  2. borrow (1) - High priority
  3. lend (2) - Medium priority
  4. transfer (3) - Lowest priority

Anti-Starvation Mechanism

The batcher alternates between two modes:

Odd Batches (1, 3, 5...): Priority-only mode

  • Strictly processes by priority
  • Highest priority transactions first

Even Batches (2, 4, 6...): Quota-based mode

  • Each priority level gets fair quota
  • Prevents low-priority transactions from being starved
  • Ensures all priorities eventually get processed

🔗 Fabric Integration Details

What Happens When You Submit a Transaction

  1. Client submits via HTTP POST to gateway
  2. Gateway validates and adds to mempool (sorted by priority)
  3. Batcher extracts batch when size/timeout threshold reached
  4. For each transaction in batch:
    • Transaction is sent to Fabric peer via gRPC
    • Peer endorses the transaction (executes chaincode)
    • Endorsement returned to gateway
  5. Gateway submits endorsed transaction to orderer
  6. Orderer orders transactions into a block
  7. Block is broadcast to all peers
  8. Peers validate and commit block to ledger
  9. Transaction confirmed - now permanently on blockchain

Consensus Process

Your transactions go through Fabric's complete consensus:

  • Endorsement: Peers execute chaincode and sign results
  • Ordering: Orderer service sequences transactions
  • Validation: Peers verify endorsements and check for conflicts
  • Commitment: Valid transactions written to ledger

🧪 Testing

Run the included test script

# Test with simulation (no Fabric needed)
./test_anti_starvation.sh http://localhost:8080
# The script will:# - Submit 10+ transactions with different priorities# - Show how batching works# - Demonstrate anti-starvation mechanism

Manual testing

# Terminal 1: Start server
go run . --use-fabric --port=8080 --batch-size=5 --batch-timeout=10s
# Terminal 2: Submit various transactions# High priority swap
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user1","to":"user2","amount":"100","txType":"swap"}'# Low priority transfer
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user3","to":"user4","amount":"50","txType":"transfer"}'# Check mempool
curl http://localhost:8080/mempool/status
# View completed transactions
curl http://localhost:8080/transactions/completed

📁 Project Structure

priority-fabric-project/
├── chaincode/ # Smart contract (deployed to Fabric)
│ ├── main.go # Chaincode implementation
│ └── go.mod
├── types/ # Shared data types
│ ├── transaction.go # Transaction structures
│ ├── wallet.go # Wallet structures
│ └── ...
├── fabric_client.go # Fabric Gateway SDK client
├── batcher.go # Transaction batching logic
├── mempool.go # Priority mempool implementation
├── gateway.go # HTTP API gateway
├── server.go # Main server entry point
├── priority_queue.go # Priority queue data structure
├── deploy-chaincode.sh # Chaincode deployment script
└── README.md # This file

🔍 Monitoring & Debugging

View server logs

The server provides detailed logging of:

  • Transaction submissions
  • Mempool operations
  • Batch processing
  • Fabric network communication

Check Fabric network

# View running containers
docker ps
# View peer logs
docker logs peer0.org1.example.com
# View orderer logs
docker logs orderer.example.com

Query chaincode directly

# Set environment for Org1cd /Users/sathvikcustiv/fabric-dev/fabric-samples/test-network
export PATH=${PWD}/../bin:$PATHexport FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
# Create a wallet
peer chaincode invoke \
-o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls \
--cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n wallet \
-c '{"function":"CreateWallet","Args":[]}'# Query a wallet (use address from CreateWallet response)
peer chaincode query \
-C mychannel \
-n wallet \
-c '{"function":"GetWallet","Args":["<wallet-address>"]}'

🛠️ Troubleshooting

"Failed to connect to Fabric"

  • Ensure Fabric network is running: cd fabric-samples/test-network && ./network.sh up createChannel
  • Check Docker containers are running: docker ps
  • Verify chaincode is deployed: Run ./deploy-chaincode.sh

"Chaincode not found"

  • Deploy chaincode: ./deploy-chaincode.sh
  • Check deployment: peer lifecycle chaincode querycommitted -C mychannel -n wallet

Port already in use

  • Kill process on port: lsof -ti:8080 | xargs kill -9
  • Or use different port: go run . --port=8081

Simulation mode when expecting Fabric

  • Ensure you're using --use-fabric flag
  • Check network connectivity to peer (localhost:7051)

📚 Learn More

🎓 Key Concepts Explained

Mempool

A temporary storage area where transactions wait before being processed. Like a priority queue at a bank - VIP customers (high priority) get served first, but regular customers aren't ignored forever.

Batching

Grouping multiple transactions together for efficiency. Instead of submitting transactions one-by-one to Fabric, we batch them to reduce network overhead and improve throughput.

Endorsement

Peers execute the chaincode and sign the result. This proves the transaction was validated by trusted parties before being added to the ledger.

Consensus

The distributed agreement process ensuring all peers have the same ledger state. Your transactions must pass through this to be considered valid.

Anti-Starvation

Mechanism ensuring low-priority transactions eventually get processed, even when high-priority transactions keep arriving.


Built with ❤️ for Hyperledger Fabric

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Priority Fabric Transaction Gateway

A priority-based transaction ordering system integrated with Hyperledger Fabric, featuring a mempool with anti-starvation mechanisms and batch processing.

🎯 What This System Does

This project implements a priority-based transaction gateway that:

  1. Accepts transactions via HTTP API with different priority levels (swap, borrow, lend, transfer)
  2. Queues transactions in a priority mempool with anti-starvation protection
  3. Batches transactions for efficient processing
  4. Submits to Fabric through the complete consensus process:
    • ✅ Endorsement by peers
    • ✅ Ordering by orderer service
    • ✅ Validation and commitment to distributed ledger
    • ✅ Consensus through Raft/BFT

🏗️ Architecture

┌─────────────┐
│ Clients │
└──────┬──────┘
│ HTTP POST /submit
▼
┌─────────────────────────────────┐
│ Transaction Gateway (server.go)│
└──────┬──────────────────────────┘
│
▼
┌──────────────────┐
│ Priority Mempool │ ← Transactions queued by priority
│ - swap (0) │
│ - borrow (1) │
│ - lend (2) │
│ - transfer (3) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Batcher │ ← Groups transactions into batches
│ - Size trigger │ (alternates between priority-only
│ - Time trigger │ and anti-starvation modes)
└──────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ Fabric Gateway SDK (gRPC) │
└──────┬───────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ Hyperledger Fabric Network │
│ ┌────────┐ ┌────────┐ │
│ │ Peer 1 │ │ Peer 2 │ Endorse │
│ └────┬───┘ └────┬───┘ │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ ┌──────────┐ │
│ │ Orderer │ Order │
│ └─────┬────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Commit Block │ │
│ │ to Ledger │ │
│ └──────────────┘ │
└──────────────────────────────────┘

📋 Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose
  • Hyperledger Fabric binaries (included in fabric-samples)
  • fabric-samples repository (already present in your setup)

🚀 Quick Start

Step 1: Deploy Chaincode to Fabric Network

The deployment script will automatically:

  • Start the Fabric test-network (if not running)
  • Package your chaincode
  • Install on both org peers
  • Approve for both organizations
  • Commit to the channel
cd /Users/sathvikcustiv/fabric-dev/priority-fabric-project
./deploy-chaincode.sh

What happens during deployment:

  1. Network Check: Verifies if Fabric network is running, starts if needed
  2. Package: Creates a chaincode package from your Go code
  3. Install: Installs chaincode on Org1 and Org2 peers
  4. Approve: Gets approval from both organizations
  5. Commit: Commits chaincode definition to the channel
  6. Verify: Confirms successful deployment

Step 2: Start Gateway Server with Fabric Integration

# Run in simulation mode (no Fabric connection)
go run . --port=8080
# Run with Fabric integration (connects to network)
go run . --port=8080 --use-fabric
# Custom configuration
go run . --port=8080 --use-fabric --batch-size=50 --batch-timeout=5s --mempool-size=2000

Command-line flags:

  • --port: HTTP server port (default: 8080)
  • --use-fabric: Connect to Fabric network (default: false - simulation mode)
  • --batch-size: Transactions per batch (default: 100)
  • --batch-timeout: Max time before processing batch (default: 2s)
  • --mempool-size: Maximum mempool capacity (default: 1000)
  • --verbose: Enable verbose logging (default: false)

Step 3: Submit Transactions

# Create wallets first (run these commands in a new terminal)
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{ "from": "wallet1", "to": "wallet2", "amount": "100", "txType": "swap" }'

📡 API Endpoints

POST /submit

Submit a new transaction to the mempool.

Request:

{
"from": "address1",
"to": "address2",
"amount": "100.50",
"txType": "swap"
}

Valid Transaction Types:

  • swap - Priority 0 (highest)
  • borrow - Priority 1
  • lend - Priority 2
  • transfer - Priority 3 (lowest)

Response:

{
"transactionId": "a1b2c3d4...",
"status": "queued",
"priority": 0,
"message": "Transaction queued with priority 0"
}

GET /mempool/status

View current mempool statistics.

curl http://localhost:8080/mempool/status

GET /batcher/status

View batcher statistics and processing info.

curl http://localhost:8080/batcher/status

GET /transaction/status?id=

Check status of a specific transaction.

curl http://localhost:8080/transaction/status?id=a1b2c3d4

GET /transactions/completed

View all completed transactions.

curl http://localhost:8080/transactions/completed

GET /health

Health check endpoint.

curl http://localhost:8080/health

🔄 How Priority & Anti-Starvation Works

Priority Levels

Transactions are ordered by priority (0 = highest, 3 = lowest):

  1. swap (0) - Highest priority, processed first
  2. borrow (1) - High priority
  3. lend (2) - Medium priority
  4. transfer (3) - Lowest priority

Anti-Starvation Mechanism

The batcher alternates between two modes:

Odd Batches (1, 3, 5...): Priority-only mode

  • Strictly processes by priority
  • Highest priority transactions first

Even Batches (2, 4, 6...): Quota-based mode

  • Each priority level gets fair quota
  • Prevents low-priority transactions from being starved
  • Ensures all priorities eventually get processed

🔗 Fabric Integration Details

What Happens When You Submit a Transaction

  1. Client submits via HTTP POST to gateway
  2. Gateway validates and adds to mempool (sorted by priority)
  3. Batcher extracts batch when size/timeout threshold reached
  4. For each transaction in batch:
    • Transaction is sent to Fabric peer via gRPC
    • Peer endorses the transaction (executes chaincode)
    • Endorsement returned to gateway
  5. Gateway submits endorsed transaction to orderer
  6. Orderer orders transactions into a block
  7. Block is broadcast to all peers
  8. Peers validate and commit block to ledger
  9. Transaction confirmed - now permanently on blockchain

Consensus Process

Your transactions go through Fabric's complete consensus:

  • Endorsement: Peers execute chaincode and sign results
  • Ordering: Orderer service sequences transactions
  • Validation: Peers verify endorsements and check for conflicts
  • Commitment: Valid transactions written to ledger

🧪 Testing

Run the included test script

# Test with simulation (no Fabric needed)
./test_anti_starvation.sh http://localhost:8080
# The script will:# - Submit 10+ transactions with different priorities# - Show how batching works# - Demonstrate anti-starvation mechanism

Manual testing

# Terminal 1: Start server
go run . --use-fabric --port=8080 --batch-size=5 --batch-timeout=10s
# Terminal 2: Submit various transactions# High priority swap
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user1","to":"user2","amount":"100","txType":"swap"}'# Low priority transfer
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user3","to":"user4","amount":"50","txType":"transfer"}'# Check mempool
curl http://localhost:8080/mempool/status
# View completed transactions
curl http://localhost:8080/transactions/completed

📁 Project Structure

priority-fabric-project/
├── chaincode/ # Smart contract (deployed to Fabric)
│ ├── main.go # Chaincode implementation
│ └── go.mod
├── types/ # Shared data types
│ ├── transaction.go # Transaction structures
│ ├── wallet.go # Wallet structures
│ └── ...
├── fabric_client.go # Fabric Gateway SDK client
├── batcher.go # Transaction batching logic
├── mempool.go # Priority mempool implementation
├── gateway.go # HTTP API gateway
├── server.go # Main server entry point
├── priority_queue.go # Priority queue data structure
├── deploy-chaincode.sh # Chaincode deployment script
└── README.md # This file

🔍 Monitoring & Debugging

View server logs

The server provides detailed logging of:

  • Transaction submissions
  • Mempool operations
  • Batch processing
  • Fabric network communication

Check Fabric network

# View running containers
docker ps
# View peer logs
docker logs peer0.org1.example.com
# View orderer logs
docker logs orderer.example.com

Query chaincode directly

# Set environment for Org1cd /Users/sathvikcustiv/fabric-dev/fabric-samples/test-network
export PATH=${PWD}/../bin:$PATHexport FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
# Create a wallet
peer chaincode invoke \
-o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls \
--cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n wallet \
-c '{"function":"CreateWallet","Args":[]}'# Query a wallet (use address from CreateWallet response)
peer chaincode query \
-C mychannel \
-n wallet \
-c '{"function":"GetWallet","Args":["<wallet-address>"]}'

🛠️ Troubleshooting

"Failed to connect to Fabric"

  • Ensure Fabric network is running: cd fabric-samples/test-network && ./network.sh up createChannel
  • Check Docker containers are running: docker ps
  • Verify chaincode is deployed: Run ./deploy-chaincode.sh

"Chaincode not found"

  • Deploy chaincode: ./deploy-chaincode.sh
  • Check deployment: peer lifecycle chaincode querycommitted -C mychannel -n wallet

Port already in use

  • Kill process on port: lsof -ti:8080 | xargs kill -9
  • Or use different port: go run . --port=8081

Simulation mode when expecting Fabric

  • Ensure you're using --use-fabric flag
  • Check network connectivity to peer (localhost:7051)

📚 Learn More

🎓 Key Concepts Explained

Mempool

A temporary storage area where transactions wait before being processed. Like a priority queue at a bank - VIP customers (high priority) get served first, but regular customers aren't ignored forever.

Batching

Grouping multiple transactions together for efficiency. Instead of submitting transactions one-by-one to Fabric, we batch them to reduce network overhead and improve throughput.

Endorsement

Peers execute the chaincode and sign the result. This proves the transaction was validated by trusted parties before being added to the ledger.

Consensus

The distributed agreement process ensuring all peers have the same ledger state. Your transactions must pass through this to be considered valid.

Anti-Starvation

Mechanism ensuring low-priority transactions eventually get processed, even when high-priority transactions keep arriving.


Built with ❤️ for Hyperledger Fabric

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Priority Fabric Transaction Gateway

A priority-based transaction ordering system integrated with Hyperledger Fabric, featuring a mempool with anti-starvation mechanisms and batch processing.

🎯 What This System Does

This project implements a priority-based transaction gateway that:

  1. Accepts transactions via HTTP API with different priority levels (swap, borrow, lend, transfer)
  2. Queues transactions in a priority mempool with anti-starvation protection
  3. Batches transactions for efficient processing
  4. Submits to Fabric through the complete consensus process:
    • ✅ Endorsement by peers
    • ✅ Ordering by orderer service
    • ✅ Validation and commitment to distributed ledger
    • ✅ Consensus through Raft/BFT

🏗️ Architecture

┌─────────────┐
│ Clients │
└──────┬──────┘
│ HTTP POST /submit
▼
┌─────────────────────────────────┐
│ Transaction Gateway (server.go)│
└──────┬──────────────────────────┘
│
▼
┌──────────────────┐
│ Priority Mempool │ ← Transactions queued by priority
│ - swap (0) │
│ - borrow (1) │
│ - lend (2) │
│ - transfer (3) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Batcher │ ← Groups transactions into batches
│ - Size trigger │ (alternates between priority-only
│ - Time trigger │ and anti-starvation modes)
└──────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ Fabric Gateway SDK (gRPC) │
└──────┬───────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ Hyperledger Fabric Network │
│ ┌────────┐ ┌────────┐ │
│ │ Peer 1 │ │ Peer 2 │ Endorse │
│ └────┬───┘ └────┬───┘ │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ ┌──────────┐ │
│ │ Orderer │ Order │
│ └─────┬────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Commit Block │ │
│ │ to Ledger │ │
│ └──────────────┘ │
└──────────────────────────────────┘

📋 Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose
  • Hyperledger Fabric binaries (included in fabric-samples)
  • fabric-samples repository (already present in your setup)

🚀 Quick Start

Step 1: Deploy Chaincode to Fabric Network

The deployment script will automatically:

  • Start the Fabric test-network (if not running)
  • Package your chaincode
  • Install on both org peers
  • Approve for both organizations
  • Commit to the channel
cd /Users/sathvikcustiv/fabric-dev/priority-fabric-project
./deploy-chaincode.sh

What happens during deployment:

  1. Network Check: Verifies if Fabric network is running, starts if needed
  2. Package: Creates a chaincode package from your Go code
  3. Install: Installs chaincode on Org1 and Org2 peers
  4. Approve: Gets approval from both organizations
  5. Commit: Commits chaincode definition to the channel
  6. Verify: Confirms successful deployment

Step 2: Start Gateway Server with Fabric Integration

# Run in simulation mode (no Fabric connection)
go run . --port=8080
# Run with Fabric integration (connects to network)
go run . --port=8080 --use-fabric
# Custom configuration
go run . --port=8080 --use-fabric --batch-size=50 --batch-timeout=5s --mempool-size=2000

Command-line flags:

  • --port: HTTP server port (default: 8080)
  • --use-fabric: Connect to Fabric network (default: false - simulation mode)
  • --batch-size: Transactions per batch (default: 100)
  • --batch-timeout: Max time before processing batch (default: 2s)
  • --mempool-size: Maximum mempool capacity (default: 1000)
  • --verbose: Enable verbose logging (default: false)

Step 3: Submit Transactions

# Create wallets first (run these commands in a new terminal)
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{ "from": "wallet1", "to": "wallet2", "amount": "100", "txType": "swap" }'

📡 API Endpoints

POST /submit

Submit a new transaction to the mempool.

Request:

{
"from": "address1",
"to": "address2",
"amount": "100.50",
"txType": "swap"
}

Valid Transaction Types:

  • swap - Priority 0 (highest)
  • borrow - Priority 1
  • lend - Priority 2
  • transfer - Priority 3 (lowest)

Response:

{
"transactionId": "a1b2c3d4...",
"status": "queued",
"priority": 0,
"message": "Transaction queued with priority 0"
}

GET /mempool/status

View current mempool statistics.

curl http://localhost:8080/mempool/status

GET /batcher/status

View batcher statistics and processing info.

curl http://localhost:8080/batcher/status

GET /transaction/status?id=

Check status of a specific transaction.

curl http://localhost:8080/transaction/status?id=a1b2c3d4

GET /transactions/completed

View all completed transactions.

curl http://localhost:8080/transactions/completed

GET /health

Health check endpoint.

curl http://localhost:8080/health

🔄 How Priority & Anti-Starvation Works

Priority Levels

Transactions are ordered by priority (0 = highest, 3 = lowest):

  1. swap (0) - Highest priority, processed first
  2. borrow (1) - High priority
  3. lend (2) - Medium priority
  4. transfer (3) - Lowest priority

Anti-Starvation Mechanism

The batcher alternates between two modes:

Odd Batches (1, 3, 5...): Priority-only mode

  • Strictly processes by priority
  • Highest priority transactions first

Even Batches (2, 4, 6...): Quota-based mode

  • Each priority level gets fair quota
  • Prevents low-priority transactions from being starved
  • Ensures all priorities eventually get processed

🔗 Fabric Integration Details

What Happens When You Submit a Transaction

  1. Client submits via HTTP POST to gateway
  2. Gateway validates and adds to mempool (sorted by priority)
  3. Batcher extracts batch when size/timeout threshold reached
  4. For each transaction in batch:
    • Transaction is sent to Fabric peer via gRPC
    • Peer endorses the transaction (executes chaincode)
    • Endorsement returned to gateway
  5. Gateway submits endorsed transaction to orderer
  6. Orderer orders transactions into a block
  7. Block is broadcast to all peers
  8. Peers validate and commit block to ledger
  9. Transaction confirmed - now permanently on blockchain

Consensus Process

Your transactions go through Fabric's complete consensus:

  • Endorsement: Peers execute chaincode and sign results
  • Ordering: Orderer service sequences transactions
  • Validation: Peers verify endorsements and check for conflicts
  • Commitment: Valid transactions written to ledger

🧪 Testing

Run the included test script

# Test with simulation (no Fabric needed)
./test_anti_starvation.sh http://localhost:8080
# The script will:# - Submit 10+ transactions with different priorities# - Show how batching works# - Demonstrate anti-starvation mechanism

Manual testing

# Terminal 1: Start server
go run . --use-fabric --port=8080 --batch-size=5 --batch-timeout=10s
# Terminal 2: Submit various transactions# High priority swap
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user1","to":"user2","amount":"100","txType":"swap"}'# Low priority transfer
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user3","to":"user4","amount":"50","txType":"transfer"}'# Check mempool
curl http://localhost:8080/mempool/status
# View completed transactions
curl http://localhost:8080/transactions/completed

📁 Project Structure

priority-fabric-project/
├── chaincode/ # Smart contract (deployed to Fabric)
│ ├── main.go # Chaincode implementation
│ └── go.mod
├── types/ # Shared data types
│ ├── transaction.go # Transaction structures
│ ├── wallet.go # Wallet structures
│ └── ...
├── fabric_client.go # Fabric Gateway SDK client
├── batcher.go # Transaction batching logic
├── mempool.go # Priority mempool implementation
├── gateway.go # HTTP API gateway
├── server.go # Main server entry point
├── priority_queue.go # Priority queue data structure
├── deploy-chaincode.sh # Chaincode deployment script
└── README.md # This file

🔍 Monitoring & Debugging

View server logs

The server provides detailed logging of:

  • Transaction submissions
  • Mempool operations
  • Batch processing
  • Fabric network communication

Check Fabric network

# View running containers
docker ps
# View peer logs
docker logs peer0.org1.example.com
# View orderer logs
docker logs orderer.example.com

Query chaincode directly

# Set environment for Org1cd /Users/sathvikcustiv/fabric-dev/fabric-samples/test-network
export PATH=${PWD}/../bin:$PATHexport FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
# Create a wallet
peer chaincode invoke \
-o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls \
--cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n wallet \
-c '{"function":"CreateWallet","Args":[]}'# Query a wallet (use address from CreateWallet response)
peer chaincode query \
-C mychannel \
-n wallet \
-c '{"function":"GetWallet","Args":["<wallet-address>"]}'

🛠️ Troubleshooting

"Failed to connect to Fabric"

  • Ensure Fabric network is running: cd fabric-samples/test-network && ./network.sh up createChannel
  • Check Docker containers are running: docker ps
  • Verify chaincode is deployed: Run ./deploy-chaincode.sh

"Chaincode not found"

  • Deploy chaincode: ./deploy-chaincode.sh
  • Check deployment: peer lifecycle chaincode querycommitted -C mychannel -n wallet

Port already in use

  • Kill process on port: lsof -ti:8080 | xargs kill -9
  • Or use different port: go run . --port=8081

Simulation mode when expecting Fabric

  • Ensure you're using --use-fabric flag
  • Check network connectivity to peer (localhost:7051)

📚 Learn More

🎓 Key Concepts Explained

Mempool

A temporary storage area where transactions wait before being processed. Like a priority queue at a bank - VIP customers (high priority) get served first, but regular customers aren't ignored forever.

Batching

Grouping multiple transactions together for efficiency. Instead of submitting transactions one-by-one to Fabric, we batch them to reduce network overhead and improve throughput.

Endorsement

Peers execute the chaincode and sign the result. This proves the transaction was validated by trusted parties before being added to the ledger.

Consensus

The distributed agreement process ensuring all peers have the same ledger state. Your transactions must pass through this to be considered valid.

Anti-Starvation

Mechanism ensuring low-priority transactions eventually get processed, even when high-priority transactions keep arriving.


Built with ❤️ for Hyperledger Fabric

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Priority Fabric Transaction Gateway

A priority-based transaction ordering system integrated with Hyperledger Fabric, featuring a mempool with anti-starvation mechanisms and batch processing.

🎯 What This System Does

This project implements a priority-based transaction gateway that:

  1. Accepts transactions via HTTP API with different priority levels (swap, borrow, lend, transfer)
  2. Queues transactions in a priority mempool with anti-starvation protection
  3. Batches transactions for efficient processing
  4. Submits to Fabric through the complete consensus process:
    • ✅ Endorsement by peers
    • ✅ Ordering by orderer service
    • ✅ Validation and commitment to distributed ledger
    • ✅ Consensus through Raft/BFT

🏗️ Architecture

┌─────────────┐
│ Clients │
└──────┬──────┘
│ HTTP POST /submit
▼
┌─────────────────────────────────┐
│ Transaction Gateway (server.go)│
└──────┬──────────────────────────┘
│
▼
┌──────────────────┐
│ Priority Mempool │ ← Transactions queued by priority
│ - swap (0) │
│ - borrow (1) │
│ - lend (2) │
│ - transfer (3) │
└──────┬───────────┘
│
▼
┌──────────────────┐
│ Batcher │ ← Groups transactions into batches
│ - Size trigger │ (alternates between priority-only
│ - Time trigger │ and anti-starvation modes)
└──────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ Fabric Gateway SDK (gRPC) │
└──────┬───────────────────────────┘
│
▼
┌──────────────────────────────────┐
│ Hyperledger Fabric Network │
│ ┌────────┐ ┌────────┐ │
│ │ Peer 1 │ │ Peer 2 │ Endorse │
│ └────┬───┘ └────┬───┘ │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ ┌──────────┐ │
│ │ Orderer │ Order │
│ └─────┬────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Commit Block │ │
│ │ to Ledger │ │
│ └──────────────┘ │
└──────────────────────────────────┘

📋 Prerequisites

  • Go 1.21 or higher
  • Docker and Docker Compose
  • Hyperledger Fabric binaries (included in fabric-samples)
  • fabric-samples repository (already present in your setup)

🚀 Quick Start

Step 1: Deploy Chaincode to Fabric Network

The deployment script will automatically:

  • Start the Fabric test-network (if not running)
  • Package your chaincode
  • Install on both org peers
  • Approve for both organizations
  • Commit to the channel
cd /Users/sathvikcustiv/fabric-dev/priority-fabric-project
./deploy-chaincode.sh

What happens during deployment:

  1. Network Check: Verifies if Fabric network is running, starts if needed
  2. Package: Creates a chaincode package from your Go code
  3. Install: Installs chaincode on Org1 and Org2 peers
  4. Approve: Gets approval from both organizations
  5. Commit: Commits chaincode definition to the channel
  6. Verify: Confirms successful deployment

Step 2: Start Gateway Server with Fabric Integration

# Run in simulation mode (no Fabric connection)
go run . --port=8080
# Run with Fabric integration (connects to network)
go run . --port=8080 --use-fabric
# Custom configuration
go run . --port=8080 --use-fabric --batch-size=50 --batch-timeout=5s --mempool-size=2000

Command-line flags:

  • --port: HTTP server port (default: 8080)
  • --use-fabric: Connect to Fabric network (default: false - simulation mode)
  • --batch-size: Transactions per batch (default: 100)
  • --batch-timeout: Max time before processing batch (default: 2s)
  • --mempool-size: Maximum mempool capacity (default: 1000)
  • --verbose: Enable verbose logging (default: false)

Step 3: Submit Transactions

# Create wallets first (run these commands in a new terminal)
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{ "from": "wallet1", "to": "wallet2", "amount": "100", "txType": "swap" }'

📡 API Endpoints

POST /submit

Submit a new transaction to the mempool.

Request:

{
"from": "address1",
"to": "address2",
"amount": "100.50",
"txType": "swap"
}

Valid Transaction Types:

  • swap - Priority 0 (highest)
  • borrow - Priority 1
  • lend - Priority 2
  • transfer - Priority 3 (lowest)

Response:

{
"transactionId": "a1b2c3d4...",
"status": "queued",
"priority": 0,
"message": "Transaction queued with priority 0"
}

GET /mempool/status

View current mempool statistics.

curl http://localhost:8080/mempool/status

GET /batcher/status

View batcher statistics and processing info.

curl http://localhost:8080/batcher/status

GET /transaction/status?id=

Check status of a specific transaction.

curl http://localhost:8080/transaction/status?id=a1b2c3d4

GET /transactions/completed

View all completed transactions.

curl http://localhost:8080/transactions/completed

GET /health

Health check endpoint.

curl http://localhost:8080/health

🔄 How Priority & Anti-Starvation Works

Priority Levels

Transactions are ordered by priority (0 = highest, 3 = lowest):

  1. swap (0) - Highest priority, processed first
  2. borrow (1) - High priority
  3. lend (2) - Medium priority
  4. transfer (3) - Lowest priority

Anti-Starvation Mechanism

The batcher alternates between two modes:

Odd Batches (1, 3, 5...): Priority-only mode

  • Strictly processes by priority
  • Highest priority transactions first

Even Batches (2, 4, 6...): Quota-based mode

  • Each priority level gets fair quota
  • Prevents low-priority transactions from being starved
  • Ensures all priorities eventually get processed

🔗 Fabric Integration Details

What Happens When You Submit a Transaction

  1. Client submits via HTTP POST to gateway
  2. Gateway validates and adds to mempool (sorted by priority)
  3. Batcher extracts batch when size/timeout threshold reached
  4. For each transaction in batch:
    • Transaction is sent to Fabric peer via gRPC
    • Peer endorses the transaction (executes chaincode)
    • Endorsement returned to gateway
  5. Gateway submits endorsed transaction to orderer
  6. Orderer orders transactions into a block
  7. Block is broadcast to all peers
  8. Peers validate and commit block to ledger
  9. Transaction confirmed - now permanently on blockchain

Consensus Process

Your transactions go through Fabric's complete consensus:

  • Endorsement: Peers execute chaincode and sign results
  • Ordering: Orderer service sequences transactions
  • Validation: Peers verify endorsements and check for conflicts
  • Commitment: Valid transactions written to ledger

🧪 Testing

Run the included test script

# Test with simulation (no Fabric needed)
./test_anti_starvation.sh http://localhost:8080
# The script will:# - Submit 10+ transactions with different priorities# - Show how batching works# - Demonstrate anti-starvation mechanism

Manual testing

# Terminal 1: Start server
go run . --use-fabric --port=8080 --batch-size=5 --batch-timeout=10s
# Terminal 2: Submit various transactions# High priority swap
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user1","to":"user2","amount":"100","txType":"swap"}'# Low priority transfer
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{"from":"user3","to":"user4","amount":"50","txType":"transfer"}'# Check mempool
curl http://localhost:8080/mempool/status
# View completed transactions
curl http://localhost:8080/transactions/completed

📁 Project Structure

priority-fabric-project/
├── chaincode/ # Smart contract (deployed to Fabric)
│ ├── main.go # Chaincode implementation
│ └── go.mod
├── types/ # Shared data types
│ ├── transaction.go # Transaction structures
│ ├── wallet.go # Wallet structures
│ └── ...
├── fabric_client.go # Fabric Gateway SDK client
├── batcher.go # Transaction batching logic
├── mempool.go # Priority mempool implementation
├── gateway.go # HTTP API gateway
├── server.go # Main server entry point
├── priority_queue.go # Priority queue data structure
├── deploy-chaincode.sh # Chaincode deployment script
└── README.md # This file

🔍 Monitoring & Debugging

View server logs

The server provides detailed logging of:

  • Transaction submissions
  • Mempool operations
  • Batch processing
  • Fabric network communication

Check Fabric network

# View running containers
docker ps
# View peer logs
docker logs peer0.org1.example.com
# View orderer logs
docker logs orderer.example.com

Query chaincode directly

# Set environment for Org1cd /Users/sathvikcustiv/fabric-dev/fabric-samples/test-network
export PATH=${PWD}/../bin:$PATHexport FABRIC_CFG_PATH=$PWD/../config/
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051
# Create a wallet
peer chaincode invoke \
-o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls \
--cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n wallet \
-c '{"function":"CreateWallet","Args":[]}'# Query a wallet (use address from CreateWallet response)
peer chaincode query \
-C mychannel \
-n wallet \
-c '{"function":"GetWallet","Args":["<wallet-address>"]}'

🛠️ Troubleshooting

"Failed to connect to Fabric"

  • Ensure Fabric network is running: cd fabric-samples/test-network && ./network.sh up createChannel
  • Check Docker containers are running: docker ps
  • Verify chaincode is deployed: Run ./deploy-chaincode.sh

"Chaincode not found"

  • Deploy chaincode: ./deploy-chaincode.sh
  • Check deployment: peer lifecycle chaincode querycommitted -C mychannel -n wallet

Port already in use

  • Kill process on port: lsof -ti:8080 | xargs kill -9
  • Or use different port: go run . --port=8081

Simulation mode when expecting Fabric

  • Ensure you're using --use-fabric flag
  • Check network connectivity to peer (localhost:7051)

📚 Learn More

🎓 Key Concepts Explained

Mempool

A temporary storage area where transactions wait before being processed. Like a priority queue at a bank - VIP customers (high priority) get served first, but regular customers aren't ignored forever.

Batching

Grouping multiple transactions together for efficiency. Instead of submitting transactions one-by-one to Fabric, we batch them to reduce network overhead and improve throughput.

Endorsement

Peers execute the chaincode and sign the result. This proves the transaction was validated by trusted parties before being added to the ledger.

Consensus

The distributed agreement process ensuring all peers have the same ledger state. Your transactions must pass through this to be considered valid.

Anti-Starvation

Mechanism ensuring low-priority transactions eventually get processed, even when high-priority transactions keep arriving.


Built with ❤️ for Hyperledger Fabric

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages