examples: port bitcoin/ethereum/lux/solana/tfhe MPC signing demos from hanzoai/mpc

Consolidate the hanzoai/mpc repo into luxfi/mpc (the canonical, deployed MPC —
v1.16.0, running as ghcr.io/luxfi/mpc across all clusters). hanzoai/mpc (legacy
v1.0.6) carried 5 chain-specific threshold-signing examples luxfi/mpc lacked;
they already import github.com/luxfi/mpc/pkg/threshold, so this is a clean port.
hanzoai/mpc is being archived — nothing imports it and the deployments already
run luxfi/mpc.
This commit is contained in:
2026-06-28 14:49:40 -07:00
parent 5e04d411e2
commit acd726682a
5 changed files with 992 additions and 0 deletions
+98
View File
@@ -0,0 +1,98 @@
// Copyright (c) 2024-2025 Hanzo AI Inc.
// SPDX-License-Identifier: BSD-3-Clause
// Bitcoin Threshold Signing Example
// Demonstrates both Legacy/SegWit (ECDSA) and Taproot (Schnorr) signing
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"github.com/luxfi/mpc/pkg/threshold"
)
func main() {
fmt.Println("=== Bitcoin Threshold Signing Examples ===")
fmt.Println()
// Create unified threshold API
api := threshold.NewUnifiedThresholdAPI()
defer api.Close()
// Define 3 MPC nodes with 2-of-3 threshold
partyIDs := []string{"node1", "node2", "node3"}
thresholdValue := 1 // t=1 means 2-of-3 (t+1 signers required)
// Example 1: Bitcoin Legacy/SegWit (ECDSA/secp256k1)
fmt.Println("1. Bitcoin Legacy/SegWit Transaction Signing")
fmt.Println(" Protocol: CGGMP21 (ECDSA on secp256k1)")
fmt.Println(" Use case: P2PKH, P2SH, P2WPKH, P2WSH addresses")
fmt.Println()
legacyParty, err := api.KeyGen(threshold.SchemeECDSA, "node1", partyIDs, thresholdValue)
if err != nil {
log.Fatalf("Failed to start Legacy keygen: %v", err)
}
// Simulate a Bitcoin transaction hash to sign
// In production: serialized tx -> double SHA256
txData := []byte("Bitcoin Legacy Transaction Data")
legacyTxHash := doubleSHA256(txData)
fmt.Printf(" ✓ Key generation initiated\n")
fmt.Printf(" ✓ Transaction hash: %s\n", hex.EncodeToString(legacyTxHash[:16])+"...")
fmt.Printf(" ✓ Threshold: %d-of-%d signers required\n", thresholdValue+1, len(partyIDs))
fmt.Printf(" ✓ Party status: Done=%v\n", legacyParty.Done())
fmt.Println()
// Example 2: Bitcoin Taproot (Schnorr/BIP-340)
fmt.Println("2. Bitcoin Taproot Transaction Signing")
fmt.Println(" Protocol: FROST (Schnorr on secp256k1)")
fmt.Println(" Use case: P2TR addresses, script path spending")
fmt.Println()
taprootParty, err := api.KeyGen(threshold.SchemeTaproot, "node2", partyIDs, thresholdValue)
if err != nil {
log.Fatalf("Failed to start Taproot keygen: %v", err)
}
// Taproot uses tagged hashes (BIP-340)
taprootTxHash := taggedHash("TapSighash", txData)
fmt.Printf(" ✓ Key generation initiated\n")
fmt.Printf(" ✓ Tagged hash: %s\n", hex.EncodeToString(taprootTxHash[:16])+"...")
fmt.Printf(" ✓ Threshold: %d-of-%d signers required\n", thresholdValue+1, len(partyIDs))
fmt.Printf(" ✓ Party status: Done=%v\n", taprootParty.Done())
fmt.Println()
// Summary
fmt.Println("=== Bitcoin MPC Benefits ===")
fmt.Println(" • No single point of failure for private keys")
fmt.Println(" • Distributed custody across multiple parties")
fmt.Println(" • Standard Bitcoin transactions (indistinguishable on-chain)")
fmt.Println(" • Taproot: smaller signatures, better privacy")
fmt.Println(" • Legacy: broad wallet compatibility")
fmt.Println()
fmt.Println("✅ Bitcoin threshold signing ready!")
}
// doubleSHA256 computes SHA256(SHA256(data)) for Bitcoin tx signing
func doubleSHA256(data []byte) [32]byte {
first := sha256.Sum256(data)
return sha256.Sum256(first[:])
}
// taggedHash computes SHA256(SHA256(tag) || SHA256(tag) || msg) per BIP-340
func taggedHash(tag string, msg []byte) [32]byte {
tagHash := sha256.Sum256([]byte(tag))
h := sha256.New()
h.Write(tagHash[:])
h.Write(tagHash[:])
h.Write(msg)
var result [32]byte
copy(result[:], h.Sum(nil))
return result
}
+176
View File
@@ -0,0 +1,176 @@
// Copyright (c) 2024-2025 Hanzo AI Inc.
// SPDX-License-Identifier: BSD-3-Clause
// Ethereum/EVM Threshold Signing Example
// Demonstrates threshold ECDSA signing for Ethereum and EVM-compatible chains
package main
import (
"encoding/hex"
"fmt"
"log"
"math/big"
"github.com/luxfi/mpc/pkg/threshold"
"golang.org/x/crypto/sha3"
)
func main() {
fmt.Println("=== Ethereum/EVM Threshold Signing Example ===")
fmt.Println()
// Create unified threshold API
api := threshold.NewUnifiedThresholdAPI()
defer api.Close()
// Define MPC nodes with 2-of-3 threshold
partyIDs := []string{"signer1", "signer2", "signer3"}
thresholdValue := 1 // 2-of-3 threshold
fmt.Println("1. Ethereum Transaction Signing")
fmt.Println(" Protocol: CGGMP21 (ECDSA on secp256k1)")
fmt.Println(" Compatible: Ethereum, Polygon, BSC, Arbitrum, Optimism, Avalanche C-Chain")
fmt.Println()
// Initialize key generation
party, err := api.KeyGen(threshold.SchemeECDSA, "signer1", partyIDs, thresholdValue)
if err != nil {
log.Fatalf("Failed to start keygen: %v", err)
}
// Example EIP-155 transaction (Ethereum mainnet)
tx := &EthTransaction{
Nonce: uint64(42),
GasPrice: big.NewInt(50_000_000_000), // 50 Gwei
GasLimit: uint64(21000),
To: "0x742d35Cc6634C0532925a3b844Bc9e7595f1D123",
Value: big.NewInt(1_000_000_000_000_000_000), // 1 ETH
Data: []byte{},
ChainID: big.NewInt(1), // Mainnet
}
// Compute transaction hash (Keccak256)
txHash := tx.Hash()
fmt.Printf(" ✓ Key generation initiated\n")
fmt.Printf(" ✓ Transaction details:\n")
fmt.Printf(" - Nonce: %d\n", tx.Nonce)
fmt.Printf(" - Gas Price: %s Gwei\n", new(big.Int).Div(tx.GasPrice, big.NewInt(1_000_000_000)))
fmt.Printf(" - Gas Limit: %d\n", tx.GasLimit)
fmt.Printf(" - To: %s\n", tx.To)
fmt.Printf(" - Value: %s ETH\n", formatEther(tx.Value))
fmt.Printf(" - Chain ID: %d (Mainnet)\n", tx.ChainID)
fmt.Printf(" ✓ TX Hash: 0x%s\n", hex.EncodeToString(txHash[:16])+"...")
fmt.Printf(" ✓ Threshold: %d-of-%d signers required\n", thresholdValue+1, len(partyIDs))
fmt.Printf(" ✓ Party status: Done=%v\n", party.Done())
fmt.Println()
// Example 2: ERC-20 Token Transfer
fmt.Println("2. ERC-20 Token Transfer")
fmt.Println()
// ERC-20 transfer function signature: transfer(address,uint256)
transferData := encodeERC20Transfer(
"0x1234567890123456789012345678901234567890",
big.NewInt(1000_000_000_000_000_000), // 1 token (18 decimals)
)
erc20Tx := &EthTransaction{
Nonce: uint64(43),
GasPrice: big.NewInt(50_000_000_000),
GasLimit: uint64(60000),
To: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // Example: USDC
Value: big.NewInt(0),
Data: transferData,
ChainID: big.NewInt(1),
}
erc20Hash := erc20Tx.Hash()
fmt.Printf(" ✓ ERC-20 Transfer encoded\n")
fmt.Printf(" ✓ Contract: %s\n", erc20Tx.To)
fmt.Printf(" ✓ TX Hash: 0x%s\n", hex.EncodeToString(erc20Hash[:16])+"...")
fmt.Println()
// Supported EVM chains
fmt.Println("=== Supported EVM Chains ===")
chains := []struct {
name string
chainID int64
}{
{"Ethereum Mainnet", 1},
{"Polygon", 137},
{"BNB Smart Chain", 56},
{"Arbitrum One", 42161},
{"Optimism", 10},
{"Avalanche C-Chain", 43114},
{"Base", 8453},
{"Lux Network", 9000},
}
for _, chain := range chains {
fmt.Printf(" ✓ %s (Chain ID: %d)\n", chain.name, chain.chainID)
}
fmt.Println()
fmt.Println("=== EVM MPC Benefits ===")
fmt.Println(" • Institutional-grade custody for ETH and tokens")
fmt.Println(" • Compatible with all ERC-20, ERC-721, ERC-1155 tokens")
fmt.Println(" • DeFi protocol interaction support")
fmt.Println(" • Multi-chain deployment with single key setup")
fmt.Println(" • EIP-712 typed data signing support")
fmt.Println()
fmt.Println("✅ Ethereum/EVM threshold signing ready!")
}
// EthTransaction represents a simplified Ethereum transaction
type EthTransaction struct {
Nonce uint64
GasPrice *big.Int
GasLimit uint64
To string
Value *big.Int
Data []byte
ChainID *big.Int
}
// Hash computes the Keccak256 hash of the transaction for signing
func (tx *EthTransaction) Hash() [32]byte {
// Simplified: in production use RLP encoding
h := sha3.NewLegacyKeccak256()
h.Write(big.NewInt(int64(tx.Nonce)).Bytes())
h.Write(tx.GasPrice.Bytes())
h.Write(big.NewInt(int64(tx.GasLimit)).Bytes())
h.Write([]byte(tx.To))
h.Write(tx.Value.Bytes())
h.Write(tx.Data)
h.Write(tx.ChainID.Bytes())
var result [32]byte
copy(result[:], h.Sum(nil))
return result
}
// encodeERC20Transfer encodes an ERC-20 transfer call
func encodeERC20Transfer(to string, amount *big.Int) []byte {
// Function selector: keccak256("transfer(address,uint256)")[:4]
selector := []byte{0xa9, 0x05, 0x9c, 0xbb}
// Pad address to 32 bytes
addrBytes := make([]byte, 32)
copy(addrBytes[12:], []byte(to)[2:22]) // Remove 0x prefix
// Pad amount to 32 bytes
amountBytes := make([]byte, 32)
amount.FillBytes(amountBytes)
result := make([]byte, 0, 68)
result = append(result, selector...)
result = append(result, addrBytes...)
result = append(result, amountBytes...)
return result
}
// formatEther converts wei to ETH string
func formatEther(wei *big.Int) string {
eth := new(big.Float).SetInt(wei)
divisor := new(big.Float).SetInt(big.NewInt(1_000_000_000_000_000_000))
eth.Quo(eth, divisor)
return eth.Text('f', 4)
}
+285
View File
@@ -0,0 +1,285 @@
// Copyright (c) 2024-2025 Hanzo AI Inc.
// SPDX-License-Identifier: BSD-3-Clause
// Lux Network Threshold Signing Example
// Demonstrates threshold signing for Lux Network (X-Chain, P-Chain, C-Chain)
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"math/big"
"github.com/luxfi/mpc/pkg/threshold"
"golang.org/x/crypto/sha3"
)
func main() {
fmt.Println("=== Lux Network Threshold Signing Example ===")
fmt.Println()
// Create unified threshold API
api := threshold.NewUnifiedThresholdAPI()
defer api.Close()
// Define MPC nodes with 2-of-3 threshold
partyIDs := []string{"validator1", "validator2", "validator3"}
thresholdValue := 1 // 2-of-3 threshold
// Example 1: X-Chain (Exchange Chain) - ECDSA/secp256k1
fmt.Println("1. X-Chain (Exchange Chain) Transaction Signing")
fmt.Println(" Protocol: CGGMP21 (ECDSA on secp256k1)")
fmt.Println(" Use case: Asset transfers, LUX native token")
fmt.Println()
xchainParty, err := api.KeyGen(threshold.SchemeECDSA, "validator1", partyIDs, thresholdValue)
if err != nil {
log.Fatalf("Failed to start X-Chain keygen: %v", err)
}
// Example X-Chain transfer transaction
xchainTx := &LuxTransaction{
NetworkID: 9000, // Lux Mainnet
ChainID: "X",
TypeID: 0, // Base transaction
Inputs: []UTXO{{TxID: "abc123", OutputIndex: 0, Amount: 1_000_000_000}},
Outputs: []Output{{Address: "X-lux1...", Amount: 999_000_000}},
Memo: []byte("MPC threshold transfer"),
}
xchainHash := xchainTx.Hash()
fmt.Printf(" ✓ Key generation initiated\n")
fmt.Printf(" ✓ Transaction details:\n")
fmt.Printf(" - Network ID: %d (Lux Mainnet)\n", xchainTx.NetworkID)
fmt.Printf(" - Chain: %s-Chain\n", xchainTx.ChainID)
fmt.Printf(" - Inputs: %d UTXO(s)\n", len(xchainTx.Inputs))
fmt.Printf(" - Outputs: %d\n", len(xchainTx.Outputs))
fmt.Printf(" ✓ TX Hash: %s\n", hex.EncodeToString(xchainHash[:16])+"...")
fmt.Printf(" ✓ Threshold: %d-of-%d signers required\n", thresholdValue+1, len(partyIDs))
fmt.Printf(" ✓ Party status: Done=%v\n", xchainParty.Done())
fmt.Println()
// Example 2: P-Chain (Platform Chain) - ECDSA/secp256k1
fmt.Println("2. P-Chain (Platform Chain) Transaction Signing")
fmt.Println(" Protocol: CGGMP21 (ECDSA on secp256k1)")
fmt.Println(" Use case: Staking, subnet creation, validator management")
fmt.Println()
pchainParty, err := api.KeyGen(threshold.SchemeECDSA, "validator2", partyIDs, thresholdValue)
if err != nil {
log.Fatalf("Failed to start P-Chain keygen: %v", err)
}
// Example P-Chain staking transaction
stakingTx := &StakingTransaction{
NetworkID: 9000,
NodeID: "NodeID-7Xhw2mDxuDS44j42TCB6U5579esbSt3Lg",
StakeAmount: 2000_000_000_000, // 2000 LUX
StartTime: 1704067200, // Unix timestamp
EndTime: 1735689600, // Unix timestamp
RewardAddress: "P-lux1...",
}
stakingHash := stakingTx.Hash()
fmt.Printf(" ✓ Key generation initiated\n")
fmt.Printf(" ✓ Staking details:\n")
fmt.Printf(" - Node ID: %s...\n", stakingTx.NodeID[:20])
fmt.Printf(" - Stake Amount: %d LUX\n", stakingTx.StakeAmount/1_000_000_000)
fmt.Printf(" - Duration: ~1 year\n")
fmt.Printf(" ✓ TX Hash: %s\n", hex.EncodeToString(stakingHash[:16])+"...")
fmt.Printf(" ✓ Party status: Done=%v\n", pchainParty.Done())
fmt.Println()
// Example 3: C-Chain (Contract Chain) - EVM Compatible
fmt.Println("3. C-Chain (Contract Chain) Transaction Signing")
fmt.Println(" Protocol: CGGMP21 (ECDSA on secp256k1)")
fmt.Println(" Use case: Smart contracts, DeFi, ERC-20 tokens")
fmt.Println()
cchainParty, err := api.KeyGen(threshold.SchemeECDSA, "validator3", partyIDs, thresholdValue)
if err != nil {
log.Fatalf("Failed to start C-Chain keygen: %v", err)
}
// Example C-Chain EVM transaction
cchainTx := &EVMTransaction{
Nonce: uint64(42),
GasPrice: big.NewInt(25_000_000_000), // 25 nLUX
GasLimit: uint64(21000),
To: "0x742d35Cc6634C0532925a3b844Bc9e7595f1D123",
Value: big.NewInt(1_000_000_000_000_000_000), // 1 LUX
Data: []byte{},
ChainID: big.NewInt(9000), // Lux C-Chain
}
cchainHash := cchainTx.Hash()
fmt.Printf(" ✓ Key generation initiated\n")
fmt.Printf(" ✓ EVM Transaction details:\n")
fmt.Printf(" - Nonce: %d\n", cchainTx.Nonce)
fmt.Printf(" - Gas Price: %s nLUX\n", new(big.Int).Div(cchainTx.GasPrice, big.NewInt(1_000_000_000)))
fmt.Printf(" - Gas Limit: %d\n", cchainTx.GasLimit)
fmt.Printf(" - Chain ID: %d (Lux C-Chain)\n", cchainTx.ChainID)
fmt.Printf(" ✓ TX Hash: 0x%s\n", hex.EncodeToString(cchainHash[:16])+"...")
fmt.Printf(" ✓ Party status: Done=%v\n", cchainParty.Done())
fmt.Println()
// Example 4: Cross-Chain Transfer
fmt.Println("4. Cross-Chain Transfer (X-Chain → C-Chain)")
fmt.Println()
crossChainTx := &CrossChainTransaction{
SourceChain: "X",
DestChain: "C",
Amount: 100_000_000_000, // 100 LUX
ExportTxID: "export123",
}
crossChainHash := crossChainTx.Hash()
fmt.Printf(" ✓ Cross-chain transfer encoded\n")
fmt.Printf(" ✓ Source: %s-Chain → Dest: %s-Chain\n", crossChainTx.SourceChain, crossChainTx.DestChain)
fmt.Printf(" ✓ Amount: %d LUX\n", crossChainTx.Amount/1_000_000_000)
fmt.Printf(" ✓ TX Hash: %s\n", hex.EncodeToString(crossChainHash[:16])+"...")
fmt.Println()
// Lux Network features
fmt.Println("=== Lux Network Chain Support ===")
chains := []struct {
name string
chainID string
purpose string
}{
{"X-Chain", "X", "Asset transfers, native tokens"},
{"P-Chain", "P", "Staking, validators, subnets"},
{"C-Chain", "C", "Smart contracts, EVM/DeFi"},
}
for _, chain := range chains {
fmt.Printf(" ✓ %s (%s): %s\n", chain.name, chain.chainID, chain.purpose)
}
fmt.Println()
fmt.Println("=== Lux MPC Benefits ===")
fmt.Println(" • Multi-chain threshold custody (X, P, C chains)")
fmt.Println(" • Institutional-grade staking security")
fmt.Println(" • Cross-chain atomic swaps with MPC")
fmt.Println(" • Subnet deployment with distributed keys")
fmt.Println(" • EVM compatibility for DeFi protocols")
fmt.Println(" • Post-quantum ready (future upgrades)")
fmt.Println()
fmt.Println("✅ Lux Network threshold signing ready!")
}
// LuxTransaction represents a simplified Lux X-Chain transaction
type LuxTransaction struct {
NetworkID uint32
ChainID string
TypeID uint32
Inputs []UTXO
Outputs []Output
Memo []byte
}
// UTXO represents an unspent transaction output
type UTXO struct {
TxID string
OutputIndex uint32
Amount uint64
}
// Output represents a transaction output
type Output struct {
Address string
Amount uint64
}
// Hash computes the transaction hash for signing
func (tx *LuxTransaction) Hash() [32]byte {
h := sha256.New()
// Simplified: in production use proper Lux serialization
h.Write([]byte(fmt.Sprintf("%d", tx.NetworkID)))
h.Write([]byte(tx.ChainID))
for _, input := range tx.Inputs {
h.Write([]byte(input.TxID))
}
for _, output := range tx.Outputs {
h.Write([]byte(output.Address))
}
h.Write(tx.Memo)
var result [32]byte
copy(result[:], h.Sum(nil))
return result
}
// StakingTransaction represents a P-Chain staking transaction
type StakingTransaction struct {
NetworkID uint32
NodeID string
StakeAmount uint64
StartTime int64
EndTime int64
RewardAddress string
}
// Hash computes the staking transaction hash
func (tx *StakingTransaction) Hash() [32]byte {
h := sha256.New()
h.Write([]byte(fmt.Sprintf("%d", tx.NetworkID)))
h.Write([]byte(tx.NodeID))
h.Write([]byte(fmt.Sprintf("%d", tx.StakeAmount)))
h.Write([]byte(fmt.Sprintf("%d", tx.StartTime)))
h.Write([]byte(fmt.Sprintf("%d", tx.EndTime)))
h.Write([]byte(tx.RewardAddress))
var result [32]byte
copy(result[:], h.Sum(nil))
return result
}
// EVMTransaction represents a C-Chain EVM transaction
type EVMTransaction struct {
Nonce uint64
GasPrice *big.Int
GasLimit uint64
To string
Value *big.Int
Data []byte
ChainID *big.Int
}
// Hash computes the Keccak256 hash for EVM signing
func (tx *EVMTransaction) Hash() [32]byte {
h := sha3.NewLegacyKeccak256()
h.Write(big.NewInt(int64(tx.Nonce)).Bytes())
h.Write(tx.GasPrice.Bytes())
h.Write(big.NewInt(int64(tx.GasLimit)).Bytes())
h.Write([]byte(tx.To))
h.Write(tx.Value.Bytes())
h.Write(tx.Data)
h.Write(tx.ChainID.Bytes())
var result [32]byte
copy(result[:], h.Sum(nil))
return result
}
// CrossChainTransaction represents a cross-chain transfer
type CrossChainTransaction struct {
SourceChain string
DestChain string
Amount uint64
ExportTxID string
}
// Hash computes the cross-chain transaction hash
func (tx *CrossChainTransaction) Hash() [32]byte {
h := sha256.New()
h.Write([]byte(tx.SourceChain))
h.Write([]byte(tx.DestChain))
h.Write([]byte(fmt.Sprintf("%d", tx.Amount)))
h.Write([]byte(tx.ExportTxID))
var result [32]byte
copy(result[:], h.Sum(nil))
return result
}
+194
View File
@@ -0,0 +1,194 @@
// Copyright (c) 2024-2025 Hanzo AI Inc.
// SPDX-License-Identifier: BSD-3-Clause
// Solana Threshold Signing Example
// Demonstrates threshold EdDSA signing for Solana
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"github.com/luxfi/mpc/pkg/threshold"
)
func main() {
fmt.Println("=== Solana Threshold Signing Example ===")
fmt.Println()
// Create unified threshold API
api := threshold.NewUnifiedThresholdAPI()
defer api.Close()
// Define MPC nodes with 2-of-3 threshold
partyIDs := []string{"validator1", "validator2", "validator3"}
thresholdValue := 1 // 2-of-3 threshold
fmt.Println("1. Solana Transaction Signing")
fmt.Println(" Protocol: FROST (EdDSA on Ed25519)")
fmt.Println(" Note: Uses Taproot FROST variant for Schnorr compatibility")
fmt.Println()
// Initialize EdDSA key generation
party, err := api.KeyGen(threshold.SchemeEdDSA, "validator1", partyIDs, thresholdValue)
if err != nil {
log.Fatalf("Failed to start keygen: %v", err)
}
// Example Solana transfer transaction
tx := &SolanaTransaction{
RecentBlockhash: "EkSnNWid2cvwEVnVx9aBqawnmiCNiDgp3gUdkDPTKN1N",
FeePayer: "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin",
Instructions: []Instruction{
{
ProgramID: "11111111111111111111111111111111", // System Program
Accounts: []AccountMeta{
{Pubkey: "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin", IsSigner: true, IsWritable: true},
{Pubkey: "2wmVCSfPxGPjrnMMn7rchp4uaeoTqN39mXFC2zhPdri9", IsSigner: false, IsWritable: true},
},
Data: encodeTransferInstruction(1_000_000_000), // 1 SOL in lamports
},
},
}
// Compute transaction hash
txHash := tx.Hash()
fmt.Printf(" ✓ Key generation initiated\n")
fmt.Printf(" ✓ Transaction details:\n")
fmt.Printf(" - Fee Payer: %s...\n", tx.FeePayer[:16])
fmt.Printf(" - Recent Blockhash: %s...\n", tx.RecentBlockhash[:16])
fmt.Printf(" - Instructions: %d\n", len(tx.Instructions))
fmt.Printf(" - Amount: 1 SOL (1,000,000,000 lamports)\n")
fmt.Printf(" ✓ TX Hash: %s\n", hex.EncodeToString(txHash[:16])+"...")
fmt.Printf(" ✓ Threshold: %d-of-%d signers required\n", thresholdValue+1, len(partyIDs))
fmt.Printf(" ✓ Party status: Done=%v\n", party.Done())
fmt.Println()
// Example 2: SPL Token Transfer
fmt.Println("2. SPL Token Transfer")
fmt.Println()
splTx := &SolanaTransaction{
RecentBlockhash: "EkSnNWid2cvwEVnVx9aBqawnmiCNiDgp3gUdkDPTKN1N",
FeePayer: "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin",
Instructions: []Instruction{
{
ProgramID: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // SPL Token Program
Accounts: []AccountMeta{
{Pubkey: "sourceTokenAccount", IsSigner: false, IsWritable: true},
{Pubkey: "destTokenAccount", IsSigner: false, IsWritable: true},
{Pubkey: "ownerPubkey", IsSigner: true, IsWritable: false},
},
Data: encodeSPLTransfer(1_000_000), // 1 USDC (6 decimals)
},
},
}
splHash := splTx.Hash()
fmt.Printf(" ✓ SPL Token transfer encoded\n")
fmt.Printf(" ✓ Token Program: TokenkegQfeZyiNwAJbNbGKPFXC...\n")
fmt.Printf(" ✓ TX Hash: %s\n", hex.EncodeToString(splHash[:16])+"...")
fmt.Println()
// Solana ecosystem
fmt.Println("=== Solana Ecosystem Support ===")
programs := []struct {
name string
programID string
}{
{"System Program", "11111111111111111111111111111111"},
{"SPL Token", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
{"Token 2022", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"},
{"Associated Token", "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"},
{"Memo Program", "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"},
}
for _, prog := range programs {
fmt.Printf(" ✓ %s\n", prog.name)
}
fmt.Println()
fmt.Println("=== Solana MPC Benefits ===")
fmt.Println(" • Native Ed25519 threshold signatures")
fmt.Println(" • Sub-second transaction finality")
fmt.Println(" • Support for all SPL tokens")
fmt.Println(" • DeFi protocol compatibility (Raydium, Jupiter, etc.)")
fmt.Println(" • NFT marketplace support (Magic Eden, Tensor)")
fmt.Println()
fmt.Println("✅ Solana threshold signing ready!")
}
// SolanaTransaction represents a simplified Solana transaction
type SolanaTransaction struct {
RecentBlockhash string
FeePayer string
Instructions []Instruction
}
// Instruction represents a Solana instruction
type Instruction struct {
ProgramID string
Accounts []AccountMeta
Data []byte
}
// AccountMeta represents account metadata
type AccountMeta struct {
Pubkey string
IsSigner bool
IsWritable bool
}
// Hash computes the transaction hash for signing
func (tx *SolanaTransaction) Hash() [32]byte {
h := sha256.New()
// Simplified: in production use proper Solana serialization
h.Write([]byte(tx.RecentBlockhash))
h.Write([]byte(tx.FeePayer))
for _, ix := range tx.Instructions {
h.Write([]byte(ix.ProgramID))
h.Write(ix.Data)
}
var result [32]byte
copy(result[:], h.Sum(nil))
return result
}
// encodeTransferInstruction encodes a System Program transfer
func encodeTransferInstruction(lamports uint64) []byte {
// Instruction: Transfer (index 2)
data := make([]byte, 12)
data[0] = 2 // Transfer instruction
// Little-endian lamports
for i := 0; i < 8; i++ {
data[4+i] = byte(lamports >> (i * 8))
}
return data
}
// encodeSPLTransfer encodes an SPL Token transfer
func encodeSPLTransfer(amount uint64) []byte {
// Instruction: Transfer (index 3)
data := make([]byte, 9)
data[0] = 3 // Transfer instruction
// Little-endian amount
for i := 0; i < 8; i++ {
data[1+i] = byte(amount >> (i * 8))
}
return data
}
// base58Alphabet is the Bitcoin/Solana base58 alphabet
const base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
// base58Encode encodes data to base58 (simplified implementation)
func base58Encode(data []byte) string {
if len(data) == 0 {
return ""
}
// Simplified: just return hex for demonstration
// Production code would use a proper base58 implementation
return hex.EncodeToString(data)
}
+239
View File
@@ -0,0 +1,239 @@
// Copyright (c) 2024-2025 Hanzo AI Inc.
// SPDX-License-Identifier: BSD-3-Clause
// TFHE (Threshold Fully Homomorphic Encryption) Example
// Demonstrates FHE computations on encrypted data with threshold decryption
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"math/big"
)
func main() {
fmt.Println("=== TFHE (Threshold Fully Homomorphic Encryption) Example ===")
fmt.Println()
// Note: This example demonstrates the concepts and API usage.
// Full TFHE requires the luxfi/fhe package to be properly configured.
// Define MPC nodes with 2-of-3 threshold
partyIDs := []string{"node1", "node2", "node3"}
thresholdValue := 1 // 2-of-3 threshold (t+1 signers required)
fmt.Println("1. TFHE Key Generation (Threshold)")
fmt.Println(" Protocol: Threshold FHE Key Generation")
fmt.Println(" Use case: Distributed encryption/decryption with computation")
fmt.Println()
// Simulate TFHE key generation
tfheKeyGen := &TFHEKeyGenSession{
PartyIDs: partyIDs,
Threshold: thresholdValue,
SessionID: generateSessionID(),
}
fmt.Printf(" ✓ Session ID: %s\n", tfheKeyGen.SessionID[:16]+"...")
fmt.Printf(" ✓ Parties: %v\n", tfheKeyGen.PartyIDs)
fmt.Printf(" ✓ Threshold: %d-of-%d\n", thresholdValue+1, len(partyIDs))
fmt.Println()
// Example 2: Encrypted Computation
fmt.Println("2. Homomorphic Computation Example")
fmt.Println(" Operation: Encrypted addition and multiplication")
fmt.Println()
// Simulate encrypted values
plaintext1 := big.NewInt(42)
plaintext2 := big.NewInt(17)
// In real TFHE, these would be ciphertexts
encrypted1 := simulateEncrypt(plaintext1)
encrypted2 := simulateEncrypt(plaintext2)
fmt.Printf(" ✓ Value 1 (plaintext): %d\n", plaintext1)
fmt.Printf(" ✓ Value 2 (plaintext): %d\n", plaintext2)
fmt.Printf(" ✓ Encrypted 1: %s...\n", hex.EncodeToString(encrypted1[:16]))
fmt.Printf(" ✓ Encrypted 2: %s...\n", hex.EncodeToString(encrypted2[:16]))
fmt.Println()
// Homomorphic operations (simulated)
encryptedSum := simulateHomomorphicAdd(encrypted1, encrypted2)
encryptedProduct := simulateHomomorphicMul(encrypted1, encrypted2)
fmt.Printf(" ✓ Encrypted Sum: %s...\n", hex.EncodeToString(encryptedSum[:16]))
fmt.Printf(" ✓ Encrypted Product: %s...\n", hex.EncodeToString(encryptedProduct[:16]))
fmt.Println()
// Example 3: Threshold Decryption
fmt.Println("3. Threshold Decryption")
fmt.Printf(" Requires %d-of-%d parties to decrypt\n", thresholdValue+1, len(partyIDs))
fmt.Println()
// Simulate partial decryption shares
share1 := generateDecryptionShare("node1")
share2 := generateDecryptionShare("node2")
fmt.Printf(" ✓ Decryption share from node1: %s...\n", hex.EncodeToString(share1[:16]))
fmt.Printf(" ✓ Decryption share from node2: %s...\n", hex.EncodeToString(share2[:16]))
fmt.Printf(" ✓ Threshold met (2 of 3 shares)\n")
fmt.Printf(" ✓ Decrypted sum would be: %d\n", plaintext1.Int64()+plaintext2.Int64())
fmt.Printf(" ✓ Decrypted product would be: %d\n", plaintext1.Int64()*plaintext2.Int64())
fmt.Println()
// Example 4: Private Smart Contract Execution
fmt.Println("4. Private Smart Contract Execution")
fmt.Println(" Use case: Confidential DeFi transactions")
fmt.Println()
contract := &PrivateContract{
Name: "ConfidentialSwap",
InputTypes: []string{"encrypted_amount", "encrypted_price"},
OutputTypes: []string{"encrypted_result"},
}
fmt.Printf(" ✓ Contract: %s\n", contract.Name)
fmt.Printf(" ✓ Inputs: %v\n", contract.InputTypes)
fmt.Printf(" ✓ Outputs: %v\n", contract.OutputTypes)
fmt.Printf(" ✓ Computation runs on encrypted data\n")
fmt.Printf(" ✓ Only threshold parties can decrypt result\n")
fmt.Println()
// Example 5: Encrypted Database Query
fmt.Println("5. Encrypted Database Query")
fmt.Println(" Use case: Private data analytics")
fmt.Println()
query := &EncryptedQuery{
Operation: "SUM",
Column: "encrypted_balance",
Filter: "encrypted_age > threshold",
}
fmt.Printf(" ✓ Query: %s(%s) WHERE %s\n", query.Operation, query.Column, query.Filter)
fmt.Printf(" ✓ Database never sees plaintext values\n")
fmt.Printf(" ✓ Result is encrypted, needs threshold decryption\n")
fmt.Println()
// TFHE capabilities
fmt.Println("=== TFHE Capabilities ===")
capabilities := []struct {
name string
desc string
}{
{"Threshold Key Generation", "Distributed key generation with no single party holding full key"},
{"Homomorphic Addition", "Add encrypted values without decryption"},
{"Homomorphic Multiplication", "Multiply encrypted values without decryption"},
{"Threshold Decryption", "t-of-n parties required to decrypt results"},
{"Bootstrapping", "Refresh ciphertexts to enable unlimited operations"},
{"SIMD Operations", "Parallel operations on encrypted vectors"},
}
for _, cap := range capabilities {
fmt.Printf(" ✓ %s\n %s\n", cap.name, cap.desc)
}
fmt.Println()
// Use cases
fmt.Println("=== TFHE Use Cases ===")
useCases := []struct {
name string
desc string
}{
{"Private DeFi", "Confidential swaps, lending, and trading"},
{"Healthcare", "Compute on encrypted patient data"},
{"Finance", "Risk analysis on encrypted portfolios"},
{"Voting", "Verifiable elections with voter privacy"},
{"ML/AI", "Private inference on encrypted models"},
{"Supply Chain", "Track goods without revealing business data"},
}
for _, uc := range useCases {
fmt.Printf(" ✓ %s: %s\n", uc.name, uc.desc)
}
fmt.Println()
fmt.Println("=== TFHE + MPC Benefits ===")
fmt.Println(" • Computation on encrypted data (FHE)")
fmt.Println(" • No single point of decryption (threshold)")
fmt.Println(" • Key shares distributed across parties")
fmt.Println(" • Verifiable computation results")
fmt.Println(" • Post-quantum security (lattice-based)")
fmt.Println(" • Integration with blockchain for trustless execution")
fmt.Println()
fmt.Println("✅ TFHE threshold computation ready!")
}
// TFHEKeyGenSession represents a threshold FHE key generation session
type TFHEKeyGenSession struct {
PartyIDs []string
Threshold int
SessionID string
}
// PrivateContract represents a confidential smart contract
type PrivateContract struct {
Name string
InputTypes []string
OutputTypes []string
}
// EncryptedQuery represents a query on encrypted data
type EncryptedQuery struct {
Operation string
Column string
Filter string
}
// generateSessionID creates a random session identifier
func generateSessionID() string {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
log.Fatalf("Failed to generate session ID: %v", err)
}
return hex.EncodeToString(b)
}
// simulateEncrypt simulates FHE encryption (placeholder)
func simulateEncrypt(plaintext *big.Int) []byte {
// In real TFHE, this would produce a ciphertext
// Here we just create a deterministic "encrypted" representation
result := make([]byte, 64)
copy(result[:], plaintext.Bytes())
// Add some "noise" to simulate encryption
noise := make([]byte, 32)
rand.Read(noise)
copy(result[32:], noise)
return result
}
// simulateHomomorphicAdd simulates homomorphic addition
func simulateHomomorphicAdd(a, b []byte) []byte {
result := make([]byte, 64)
// In real TFHE, this would be actual homomorphic addition
for i := 0; i < len(a) && i < len(result); i++ {
result[i] = a[i] ^ b[i] // XOR as placeholder
}
return result
}
// simulateHomomorphicMul simulates homomorphic multiplication
func simulateHomomorphicMul(a, b []byte) []byte {
result := make([]byte, 64)
// In real TFHE, this would be actual homomorphic multiplication
for i := 0; i < len(a) && i < len(result); i++ {
result[i] = a[i] & b[i] // AND as placeholder
}
return result
}
// generateDecryptionShare generates a simulated decryption share
func generateDecryptionShare(nodeID string) []byte {
share := make([]byte, 32)
rand.Read(share)
// Include node ID in the share for demonstration
copy(share[:len(nodeID)], []byte(nodeID))
return share
}